
// on vérifie que le global JS n'est chargé qu'une fois, notamment lors d'un refrechDiv
if (window.hasOwnProperty('isGlobalJSLoaded')) {
    window.stop();
} 

window.isGlobalJSLoaded = true;

/**
 * 
 * @param callback : nom de la fonction à appeler
 * @param args : paramètres de la fonction 
 * 					=> exemple lors d'envoi des paramètres en twig : "['toto']" 
 * 					=> appel de la fonction depuis php, il faut changer les doubles quotes en quotes, exemple : myFunc(".$myFunction.", ".str_replace('"',"'",$myParams).")
 * Pour le JS direct il faut faire un appel de ce type : myFunc(test_msa, ["test"]);
 * Pour le JS direct , si il y a une variable contenant le nom de la fonction en question : myFunc(eval(fonction), ["test"]);
 */
function myFunc(callback, args)
{
    callback.apply(this, args);
}

function executeSRM(http, session)
{    
    sAppQuery = "ID_AUTO_SESSION=-A" + session;

    var sHREF = http + "PublishedApplications/OxaSas/IPADE.application?" + sAppQuery;

    window.location.href = sHREF;

}



//_____________________________________________________________________________
// Helpers

/**
 * Generate aunique id
 */
window.genid = window.genid | 0;
function uid() {
    return window.genid++;
}


function createElement(name, mapAttribute) {
    let el = document.createElement(name);
    for (attrKey in mapAttribute) {
        el.setAttribute(attrKey, mapAttribute[ attrKey ]);
    }
    return el;
}


//_____________________________________________________________________________
// Autocomplete (fourniss)

function setupAutocomplete(input, autocomplete) {
    // Autofill
    if (input.value == '' && autocomplete.length == 1) {
        input.value = autocomplete[0];
    }

    let wrapper = input.closest('.input-wrapper');
    let datalist = wrapper.querySelector('datalist');

    // Case : no previous datalist -> create one
    if (datalist == null) {
        datalist = createElement('datalist', {id: 'datalist-' + uid()});
        wrapper.appendChild(datalist);
        input.setAttribute('list', datalist.id)
    }

    // Udpate datalist
    datalist.innerHTML = '';
    for (option of autocomplete) {
        datalist.appendChild( createElement('option', {value: option}) );
    }
}

//_____________________________________________________________________________


/**
 * 
 * function qui permet d'afficher des popups
 * @returns popup
 */
function activePopup( title, body, classCss, reload = false )
{
    if (title) {
        document.getElementById('modal-title').innerHTML = title;
    }
    if (classCss) {
        classCss = classCss.trim(); // TODO : remove space in the caller
        document.getElementById('modal-content').classList.add(classCss);
    }
    if (body) {
        // Jq.html is required here in order to execute <script> inside body
        $(document.getElementById('modal-body')).html(body);
    }
    
    // Get the modal
    var modal = document.getElementById('myModal');
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("modal-close")[0];
    
    // When the user clicks the button, open the modal 
    modal.style.display = "block";
    
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // Close the popoup with esc key 
    document.addEventListener('keydown', function(event) {
        const key = event.key; // const {key} = event; in ES6+
        if (key === "Escape") {
            modal.style.display = "none";
        }
    });

    if (reload) {
        let modalObserver = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.attributeName === 'style') {
                    if (modal.style.display === 'none') {
                        window.location.reload();
                    }
                }
            });
        });

        let config = { attributes: true, childList: false, subtree: false };
        modalObserver.observe(modal, config);
    }
    
    // PopUp draggable
    $('#myModal .modal-content').css({'top':'0', 'left': '0'});
    $('#myModal .modal-content').draggable({
        handle: ".modal-header"
    });

    $('.modal-header').removeClass('popup_informative');
    $('.modal-header').removeClass('popup_error');
    $('.modal-header').removeClass('popup_alert');
       
    return modal;
}

function ajaxDynamiqueTab(path, title, data)
{
    activeLoader();
    
    $.ajax({
        dataType: 'html',
        url: path,
        data: data,
        type: "POST",
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            },
            500: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Internal Server Error.');
            }
        },
        success: function(result){
            activeHiddenDiv(title, result);
        }
    });
}

function activeHiddenDiv(title, body)
{
    desactiveLoader();
    desactivePopup();
    $('#mainAriane').nextAll().hide();
    $('#mainAriane li').removeClass('active');

    $('#arianeHidden').show();
    $('#arianeHidden').addClass('active');

    $('#divArianeHidden').show();

    if (body) {
        $('#divArianeHidden').html(body);
    }
    if (title) {
        $('#textArianeHidden').html(title);
    }   
    
    $('.hiddenAriane').show();
}

function desactiveHiddenDiv(undefinedJform = true)
{
    $('#arianeHidden').hide();
    
    $('#mainAriane').nextAll('div').show();
    $('#mainAriane li:visible:last').addClass('active');

    $('#textArianeHidden').html('');
    $('#divArianeHidden').html('');

    $('.hiddenAriane').hide();
    if (undefinedJform) {
        jForm = undefined;
    }
}


function activePopupInfo( title, body, classCss, fnFermer ) {
    let modal = activePopup(title, '', classCss);
    let onclickAction = fnFermer 
    ? fnFermer
    : 'desactivePopup();';
    modal.querySelector('#modal-body').innerHTML = 
        '<div class="display_table">'
        + '<span class="icone-modal information"></span>' 
        + '<div class="display_cell">' + body + '</div>'
        + '</div>'
        + '<div class="modal-footer">'
        + '<button type="button" class="button secondaire" '
        + 'data-dismiss="modal" onclick="' + onclickAction + '">'
        + window.oxaproc.trad['Fermer'] + '</button>'
        + '</div>';
    ;
}

function activePopupError( title, body, classCss, redirect = false ) {
    let modal = activePopup(title, '', classCss);
    modal.querySelector('#modal-body').innerHTML = 
        '<div class="modal_erreur">' 
        + body
        + '</div>'
        + '<div class="modal-footer">'
        + (redirect 
            ? '<a class="button principal" href="' + redirect.path + '">' + redirect.pathName + '</a>'
            : '')
        + '<button type="button" class="button secondaire" '
        +	'data-dismiss="modal" onclick="desactivePopup ();"'
        + '>'+window.oxaproc.trad['Fermer']+'</button>'
        + '</div>'
    ;
}

//function draggable

function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
}

function dragMouseDown(e) {
    e = e || window.event;
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
}

function elementDrag(e) {
    e = e || window.event;
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}

function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
}
}


document.addEventListener('click',(event) => {
    var target = event.target;
    if (! (target instanceof HTMLElement) ) return;
    if (
        ! target.hasAttribute('data-dismiss') 
        || target.getAttribute('data-dismiss') != 'modal'
    ) return;

    desactivePopup()
    return false;
});

// fin function draggable
// TODO : Ajouter un timer sur la désactivation de la popup
function desactivePopup () {
    
    document.getElementById('myModal').style.display = "none";
    
    $("#modal-content").removeClass('modal_small');
    $("#modal-content").removeClass('modal_large');

    $("#modal-title").html('');
    $("#modal-body").html('');

    $('iframe').not($('#bandeau > iframe')).show();

    $('#wanteeedPanel').hide();
}

function triggerChangeEvent(element) {
    element.dispatchEvent(new Event('change',{
        bubbles: true,
        detail: { target: element },
    }));
}

// dans le panier, la fonction est surchargé
function changeCodeLibelle(divCode, codeValue, divLibelle, libelleValue)
{
    if(libelleValue)
    {
        var split_label 		= libelleValue.split(' (');
        var label				= split_label[0].toUpperCase();

        if (divCode) {
            var tooltip 			= $('#'+CSS.escape(divCode)).parent().find('.sec-label-tooltip');
        }
    }
    
    if(divLibelle){

        let $divLib = $('#'+CSS.escape(divLibelle));
        if ($divLib.data('updatevalue')) {
            let el = document.getElementById(divLibelle);
            $divLib.trigger('focus');

            if (divCode) {
                if (el) {
                    $(el).val(codeValue).blur();
                    triggerChangeEvent(el);
                }
            } else {
                $divLib.val(libelleValue);	
                triggerChangeEvent(el);
            }

            return;
        }

        if (libelleValue) {
            $divLib.val(libelleValue);			
        } else {
            $divLib.val(codeValue).change();			
        }
        $divLib.removeClass('error white-tooltip');
        $divLib.removeAttr("data-original-title");
    }
    
    if (divCode) {
        let el = document.getElementById(divCode);

        if (el) {
            $(el).val(codeValue).blur();
            
            triggerChangeEvent(el);
        }
    }
    
    if(libelleValue && divCode)
    {
        let $divCode = $('#'+CSS.escape(divCode));
        $divCode.attr({'data-libelle' : label });

        if (tooltip.length > 0) {
            tooltip.text(label);
            
            $divCode.parent().addClass('white-tooltip');
        }
    }
}

function addEmailV2(input, mail, inputMail)
{
    mails = ''; 
    if (input != '') {
        mails += $('#'+inputMail).val() + ",";
    } else {
        mails += $('#'+inputMail).val().trim()+mail.trim() + ",";
    }
    $('#'+inputMail).val(mails);
}

function fermerOnglet(idTrigger, idClose, iDivReset)
{
    //trigger l'onglet a afficher
    if(idTrigger)
    {
        $('#'+idTrigger).find('a').trigger('click');
        $('#'+idClose).hide();
        $('#'+iDivReset).html('');
        
    }
} 

function ajaxPopup(path, title, divCode, divLibelle, params, width_popup, reload = false)
{
    if(path == null)
        throw 'Invalid path';
    activeLoader();
    var post = {'divCode' : divCode, 'divLibelle' : divLibelle};
    post = $.extend( post, params );
    
    $.ajax({
        dataType: 'html',
        url: path,
        data: post,
        type: "POST",
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            },
            500: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Internal Server Error.');
            }
        },
        success: function(result, textStatus, request){            

            // Case : json popup
            if (request.getResponseHeader('Content-Type') == 'application/json') {
                let data = JSON.parse(result);

                if (data.action != undefined) {
                    window.action[ data.action ]( request, null );
                    return;
                }

                window.action.successFormPopup(data, textStatus, request);
                desactiveLoader();
                return;
            }

            if(width_popup == null || width_popup == '' )
                width_popup = 'modal_small';
            
            $("#modal-content").removeClass('modal_large modal_small');
            
            activePopup(title, result, width_popup, reload);

            desactiveLoader();
        },
        error: function (xhr) {
            // Assume http 400 -> show constraint validation error
            desactiveLoader();
            activePopup(
                'Erreur validation', // TODO : translate
                xhr.responseText,
                'modal_small',
                reload
            );
        }
    });
}

/**	
 * La recherche en ajax sur un formulaire passer en paramètres
 * @param path (Le chemin de notr redirection de notre ajax)
 * @param div (Le contenue de la div qu'on cherche à modifier)
 * @param nomForm (Le nom de notre forumaire qu'on va envoyer)
 * @returns
 */
function ajaxRechercheTableau(path, div, nomForm){

    if(path != '')
    {
        activeLoader();
        $.ajax({
            url: path,
            type: 'POST',
            dataType: 'html',
            data: $('#'+ nomForm).serialize(),
            success: function (htmlData) {
                desactiveLoader();
                var result = $('<div />').append(htmlData).find('#'+div).html()+"<script type='text/javascript' src='"+baseUrl+"js/parametre.js'></script>";
                $('#'+div).html(result);
            }
        });
    }

}

/**
 * Le deploiement d'une infoBull coulissante 
 * @param path (Le chemin de notre redirection de notre ajax
 * @param div (le contenue de la div qu'on va ajouter au depliement
 * @params (pour selectionner qu'elle éléments on va afficher )
 * @param idForm (Le boutton sur lequelles on va effectuer notre action)
 * @returns
 */
function toggleSlide(path, div, params, idForm, tableHide, refresh, children = false)
{
    activeLoader();
    if(idForm !='' && params =='')
    {
        var data = $('#'+ idForm).serialize();
    }
    else
    {
        var data = params;
    }

    index = div.replace('detail', '');
    if($('#'+index+'detail').hasClass('hide_detail') || refresh){
    
        $.ajax
        ({
            url: path,
            type: 'POST',
            dataType: 'html',
            data: data,
            success: function (htmlData) 
            {
                $('#'+div).html(htmlData+"<script type='text/javascript' src='"+baseUrl+"js/parametre.js'></script>");

                // index = div.replace('detail', '');

                

                    if (children === false) {
                        if(typeof tableHide !== "undefined" && tableHide != '')
                        {
                            $('#'+tableHide+' .detail_ligne').addClass('hide_detail');
                            $('#'+tableHide+' tr').removeAttr( 'style' );
                            // $('#'+tableHide+' .detail_ligne').removeAttr( 'style' );
                        }
                        else
                        {
                            $('.detail_ligne').addClass('hide_detail');
                            // $('.loupe').removeClass('actif');
                            $('table tr').removeAttr( 'style' );
                        }
                    }


                    $('#'+index+'detail').removeAttr( 'style' );
                    // $('#'+index).children().addClass('actif');
                    $('#'+index+'detail').removeClass('hide_detail');
                    $('#'+index).css({
                            'border':'2px solid rgba(102, 175, 233,0.9)',
                            'border-bottom':'0px', 
                            'border-top':'2px solid rgba(102, 175, 233,0.9)',
                            'box-shadow':'none'
                            
                            });
                    $('#'+index+'detail').css({
                            'background-color': 'rgba(74, 85, 107, 0.06)',
                            'border':'2px solid rgba(102, 175, 233,0.9)',
                            'border-top':'0px',
                            'border-bottom':'2px solid rgba(102, 175, 233,0.9)',
                            'box-shadow':'none'
                    });
                
                
                desactiveLoader();
            }
        });	
    } else {
        
        desactiveLoader();
        // $('#'+index).children().removeClass('actif');
        $('#'+index+'detail').addClass('hide_detail');
        $('#'+index).removeAttr( 'style' );
        $('#'+index+'detail').removeAttr( 'style' );

    }
    
}


function exportCsv(path, fileName, divForm, type)
{
    $("#typeExport").val(type);
    $("#exportDocument").val('1');
    $.ajax
    ({
        url: path,
        type: 'POST',
        dataType: 'html',
        data: $('#'+ divForm).serialize(),
        success: function (htmlData) 
        {
            $("#typeExport").val('');
            $("#exportDocument").val('');
        }
    });	
}

/** SI - CDC - SCA - CG **/

function switchSIetDirectionOptionSelect()
{
    if($('#input_selectOptionSietDirection').val() == 'si' )
    {
        $('#input_CODE_SI').val('');
        $('#text_CODE_SI').val('');
        $('#input_CODE_DIR').val('');
        $('#text_CODE_DIR').val('');
        $('#spanSi').show();
        $('#spanDirection').hide();
    }
    else
    {
        $('#input_CODE_SI').val('');
        $('#text_CODE_SI').val('');
        $('#input_CODE_DIR').val('');
        $('#text_CODE_DIR').val('');
        $('#spanSi').hide();
        $('#spanDirection').show();	
    }
}

function switchCDCetNAOptionSelect()
{
    if($('#input_SELECT_CDC_NA').val() == 'cdc' )
    {
        $('#input_CODE_CDC').val('');
        $('#text_CODE_CDC').val('');
        $('#input_CODNAN').val('');
        $('#text_CODNAN').val('');
        $('#spanCdc').show();
        $('#spanNa').hide();
    }
    else
    {
        $('#input_CODE_CDC').val('');
        $('#text_CODE_CDC').val('');
        $('#input_CODNAN').val('');
        $('#text_CODNAN').val('');
        $('#spanCdc').hide();
        $('#spanNa').show();	
    }
}

function switchSCAetCAOptionSelect()
{
    if($('#input_selectOptionSCAetCA').val() == 'sca' )
    {
        $('#input_CODE_SCA').val('');
        $('#text_CODE_SCA').val('');
        $('#input_CODE_CTA').val('');
        $('#text_CODE_CTA').val('');
        $('#spanSca').show();
        $('#spanCa').hide();
    }
    else
    {
        $('#input_CODE_SCA').val('');
        $('#text_CODE_SCA').val('');
        $('#input_CODE_CTA').val('');
        $('#text_CODE_CTA').val('');
        $('#spanSca').hide();
        $('#spanCa').show();	
    }
}

function affichageCG(path, inputSI, divCG, div2addMargin, inputSociete)
{
    if(div2addMargin != ''){
        $('#'+div2addMargin).removeClass('margin10');
    }
    if($('#'+inputSI).val()!='')
    {
        $.ajax({
            url : path,
            type : 'POST',
            dataType : 'JSON',
            data: {'CODE_SI' : $('#'+inputSI).val(), 'CODE_STE' : $('#'+inputSociete).val()}, 
            success : function(json){
                $('#'+divCG+' input').val('')
                if(json.saisie)
                {
                        $('#'+divCG).show();
                        if(div2addMargin != ''){
                        $('#'+div2addMargin).addClass('margin10');
                        }
                }
                else
                {
                    $('#'+divCG).hide();
                }
                }
        }); 
    }
    else{
        $('#'+divCG+' input').val('');
        $('#'+divCG).hide();
    }
}
    
function choixCG(path, inputCG, cgParId, affichagelibelle){
    idCG = $('#treeview li.node-selected').find('a').attr('href').substr(1);
    if(idCG!=''){
        $.ajax({
            url : path,
            type : 'POST',
            dataType : 'JSON',
            data: {'idCG' : idCG}, 
            success : function(json){				
                // Si le paramétrage CODE_GESTION_PAR_ID == 1, la valeur à prendre est CODE_GES, sinon CODE_AFF
                if(cgParId){
                    inputValue = json.CODE_GES;
                }
                else{
                    inputValue = json.CODE_AFF;
                }
                
                if(affichagelibelle == '1'){
                    textValue = json.LIB_GES+' ('+json.CODE_AFF+')';
                }
                else{
                    textValue = json.CODE_AFF;
                }

                // [Dossier n°34705]
                var input_parent_id 	= $('#text_'+inputCG).parent().attr('id');
                var custom_tooltip 		= $('#' + input_parent_id).parent().find('.sec-label-tooltip');
                if (custom_tooltip.length > 0) {
                    custom_tooltip.text(json.LIB_GES);
                    $('#' + input_parent_id).parent().addClass('white-tooltip');
                }

                if ($('#text_'+inputCG).data('updatevalue')) {
                    $('#text_'+inputCG).val(inputValue).removeClass( "error white-tooltip" ).attr("data-original-title", '');

                    let el = document.getElementById('text_'+inputCG);
                    triggerChangeEvent(el);
                } else {
                    $('#input_'+inputCG).val(inputValue).removeClass( "error white-tooltip" ).attr("data-original-title", '').trigger('change');
                    $('#text_'+inputCG).val(textValue).removeClass( "error white-tooltip" ).attr("data-original-title", '');
                }
                
                desactivePopup();
            }
        }); 
    }
}

/** Fonction permettant de charger l'ID_CG et de changer le code saisie du Code Gestion par son libellé **/
function convertLibelleCodeGestion(path, object, CodeBDD, LibelleBDD, inputCode, inputText, CODE_STE, NUM_LOT, CODE_SI, input_SI, affichageLibelle, nonAffichageCode)
{
    if (!path) {
        return;
    }

    value=object.value;

    if(input_SI != ''){
        CODE_SI = $('#'+input_SI).val();
    }

    paramAjax = {'value' : value, 'CodeBDD' : CodeBDD, 'LibelleBDD' : LibelleBDD, 'filter_egal_NUM_LOT' : NUM_LOT, 'filter_egal_CODE_SI' : CODE_SI, 'affichageLibelle' : affichageLibelle};

    if(CODE_STE != null){
        paramAjax = $.extend(paramAjax, {'filter_egal_CODE_STE' : CODE_STE});;
    }
    
    $.ajax({
        dataType : 'html',
        data: paramAjax,
        url: path,
        type: 'POST', // la méthode indiquée dans le formulaire (get ou post)
        success: function(data) { // je récupère la réponse du fichier PHP
            data= data.split("$$");
            if(data[0]=='')
                data[0]=value;
            if(data[1]=='')
                data[1]=value;
            
            
            var libelle = '';
            
            if(data[2] && affichageLibelle)
            {
                if(nonAffichageCode){
                    libelle = data[2];
                }
                else{
                    libelle = data[2]+' ('+data[1]+')';
                }
            }
            else
            {
                libelle = data[1];
            }
            
            var input_parent_id 	= $('#'+inputText).parent().attr('id');
            var custom_tooltip 		= $('#' + input_parent_id).parent().find('.sec-label-tooltip');
            
                if (custom_tooltip.length > 0) {
                    custom_tooltip.text(libelle);
                    $('#' + input_parent_id).parent().addClass('white-tooltip');
                }
            
            $('#'+inputCode).val(data[0]).change();
            $('#'+inputText).val(libelle);
            desactiveLoader();
        }       
    });   
}

/**** IBAN ****/
function pressCleIban(inputIBANCLE, inputIBANCPT){
    if(inputIBANCLE.val().length==2){
        inputIBANCPT.focus();
    }
}



function formatNombre(nombre, separateur){
    nombre += '';
    var valeur = nombre.replace(',','.').split('.');
    valeur[0] = valeur[0] || '0';
    valeur[1] = valeur[1] || '00';
    var reg = /(\d+)(\d{3})/;
    while( reg.test( valeur[0])) {
        valeur[0] = valeur[0].replace( reg, '$1' + separateur +'$2');
    }
    return valeur.join('.');
}

function detail(path, id, idLigne)
{
    $.ajax({
        dataType : 'html',
        url: path,
        data: {'id' : id},
        type: "POST",
        success: function(result){
            $('#'+idLigne+id+'detail').html(result);
        }
    });

}

function supprimerFiltre(key, nomForm)
{
    if(key != '')
    {
        if($("#input_"+CSS.escape(key))) $("#input_"+CSS.escape(key)).val("");
        if($("#"+CSS.escape(key))) $("#"+CSS.escape(key)).val("");
    }
    $('#'+ nomForm).submit();
}

function addFiltre(key, value,  nomForm)
{
    $('#'+key).val(value);
    $('#'+ nomForm).append('<input type="hidden" name="initOnglet" id="initOnglet" value="1"/>');
    $('#'+ nomForm).submit();
}

/**
 * @deprecated use [data-checkall-input] instead
 */
function checkout(id, idBox)
{
    if ($("#"+idBox).is(':checked')) {
        $("."+id).prop('checked', true);
    }
    else
    {
        $("."+id).prop('checked', false);
    }
        
}

//_____________________________________________________________________________
// Checkall

document.addEventListener('change', function(event) {
    if (! event.target.hasAttribute('data-checkall-input')) return;

    let checked = event.target.checked;
    let checkallId = event.target.getAttribute('data-checkall-input');

    for (el of document.querySelectorAll('[data-checkall="'+ checkallId +'"]')) {
        el.checked = checked;

        el.dispatchEvent(new Event("change"));
    }
});

// Sub-layer of check-all
document.addEventListener('change', function(event) {
    if (! event.target.hasAttribute('data-checkall-input-keep') ) return;

    let checked = event.target.checked;
    let checkallId = event.target.getAttribute('data-checkall-input-keep');
    let allCheckAll = document.querySelectorAll('[data-checkall-keep="'+checkallId+'"]');

    for (const el of allCheckAll) {
        el.checked = checked;
        el.dispatchEvent(new Event("change"));
    }
});

/**
 * Uncheck parent input when one of its child is unchecked 
 */
document.addEventListener('change', function(event) {
    if (
        ! event.target.hasAttribute('data-checkall')
        || event.target.checked == true
    ) {
        return;
    }

    let checkallId = event.target.getAttribute('data-checkall');

    if ( event.target.checked == false ) {
        document
            .querySelector('[data-checkall-input="'+checkallId+'"]')
            .checked = false;
    }
});

/**
 * Check parent input when one of its child is check in data-checkall-input-keep 
 */
document.addEventListener('change', function(event) {
    if (
        ! event.target.hasAttribute('data-checkall-keep')
    ) {
        return;
    }

    let checkallId = event.target.getAttribute('data-checkall-keep');

    for(const el of checkallId.split(',')) {
        document
            .querySelector('[data-checkall-input-keep="'+el+'"]')
            .checked = (
                 document.querySelector('[data-checkall-keep*="'+el+'"]:checked') != null 
                 ? true 
                 : false
            );
    }
});

// check parent if all children are checked
$(function() {
    $('[data-checkall-input]').each(function(){
        let checked = 1;
        id = $(this).attr('data-checkall-input');
        if ($('[data-checkall="' + id + '"]:not(:checked)').length > 0) {
            checked = 0;
        }
        if (checked == 1) {
            $('[data-checkall-input="' + id + '"]').attr("checked", true);
        }
    })
});

//_____________________________________________________________________________

/** Fonction permettant de changer le code saisie dans un Zoom par son libellé **/
function ConvertLibelle(path, object, Entity, CodeBDD, LibelleBDD, inputCode, inputText, remplissage, saisieCode, param, codeOnly)
{
    if (!path) {
        return;
    }
    
    value = object.value;
    
    // Reset code
    $('#'+CSS.escape(inputCode)).val('');

    var SI = '';

    $inputText = $('#'+CSS.escape(inputText));
    if ($inputText.data('silink')) {
        var siLink = $inputText.data('silink');
        SI = $('#'+CSS.escape(siLink)).val();
    }  else if ($inputText.data('si')) {
        SI = $inputText.data('si');
    }

    var codeSte = '';

    if ($inputText.data('stelink')) {
        var steLink = $inputText.data('stelink');
        codeSte = $('#'+CSS.escape(steLink)).val();
    }  else if ($inputText.data('codeste')) {
        codeSte = $inputText.data('codeste');
    }

    var tsdon = '';
    if ($inputText.data('tsdon')) {
        tsdon = $inputText.data('tsdon');
    }
    

    paramAjax = {'value' : value, 'Entity' : Entity, 'CodeBDD' : CodeBDD, 'LibelleBDD' : LibelleBDD, 'SI' : SI, 'codeSte' : codeSte, 'tsdon' : tsdon};
    if(param != undefined && param != ''){
        paramAjax = $.extend(paramAjax, param);
    }
    
    $.ajax({
        dataType : 'html',
        data: paramAjax,
        url: path,
        type: 'POST', // la méthode indiquée dans le formulaire (get ou post)
        success: function(data) { // je récupère la réponse du fichier PHP

            $inputCode = $('#'+CSS.escape(inputCode));

            data = data.split("$$");
            if(data[0]=='')
                data[0] = value;
            if(data[1]=='')
                data[1] = value;
            
            if(saisieCode) {
                $inputCode.val(data[0]);
                $inputText.val(
                    data[1] ? 
                        data[1]+' ('+data[0]+')' : ''
                ).change();
                return;
            }
            if(!remplissage) {
                $inputCode.val(data[0]).change();
                $inputText.val(
                    data[1] ? 
                        data[1]+' ('+data[0]+')' : ''
                );
            } else {
                $inputCode.val(data[1]).change();
                $inputText.val(
                    codeOnly ? 
                        data[0] : data[0]+' ('+data[1]+')'
                );	 
            }
            desactiveLoader();
        }       
    });   
}
/** FONCTION POPUP ERREUR **/
/**
 * @TODO : can be replaced ?
 */
function activePopupErreur(path, titre, value, urlErreur, params, enteteTableau, pathArret)
{ 
    
    activeLoader();
    if(params==null){
        params='';
    }
    if(enteteTableau==null){
        enteteTableau='';
    }
    if(pathArret==null){
        pathArret='';
    }

    $( document ).ready(function() {
        $.ajax({
            url: path,
            data: {'Erreur' : value, 'Path' : urlErreur, 'params' : params, 'enteteTableau' : enteteTableau, 'pathArret': pathArret},
            type: "POST",
            success: function(result){
                desactiveLoader();
                document.getElementById('modal-content').classList.add('modal_small');
                document.getElementById('modal-title').innerHTML = titre;
                // TODO : remove script tag from ajax and use ``document.getElementById('modal-body').innerHTML = result;``
                $('#modal-body').html(result);
                activePopup();  
                $('.modal-header').addClass('popup_error');  
            }
        });	
    });
}

/** FONCTION POPUP ERREUR **/
function activePopupInformation(path, titre, value, urlErreur, params, enteteTableau, pathArret, message)
{ 
    
    activeLoader();
    if(params==null){
        params='';
    }
    if(enteteTableau==null){
        enteteTableau='';
    }
    if(pathArret==null){
        pathArret='';
    }

    $( document ).ready(function() {
        $.ajax({
            url: path,
            data: {'Erreur' : value, 'Path' : urlErreur, 'params' : params, 'enteteTableau' : enteteTableau, 'pathArret': pathArret, 'message' : message},
            type: "POST",
            success: function(result){
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-title").html(titre);
                $("#modal-body").html(result);
                activePopup();
            }
        });
    });
    
}
/** gestion des fournisseurs **/
function exportListeFournisseur(path)
{
    document.getElementById("loader").style.display = "block";
    $.ajax({
        dataType : 'html',
        url: path,
        type: "POST",
        data: $('#filtre_fournisseur').serialize(),
        success: function(result){
            document.getElementById("loader").style.display = "none";
            window.open(result, '_blank');
        }
    }); 
}
/******* FIN FOURNISSEUR ************/


/**************** MARCHE ************/
function changeCreateur(input2Change)
{
    $('#'+input2Change).val($('#loginUtilisateur').text());
}
/************ FIN MARCHE ************/


/* Popup de confirmation */
function ajaxValidationPopupRedirect(path, form)
{
    activeLoader();
    $.ajax({
        url : path ,
        type: 'POST',
        data: $('#'+form).serialize(),
        success: function (data) {            
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-body").html(data);
                $("#modal-title").html('Erreur validation');
                activePopup();
        },
        error: function (data){
            var data = jQuery.parseJSON(data.responseText);
            window.location.href = data.path;
        }
    });
};
/**
 * ID -> Entity ou Reload selon le controller qui suivra
 * **/
function popupConfirmation(path, id, URL, message, div, option, loader, popup, form, onclick, refresh, div_refresh, form_refresh, iconePopup, title, withOutPopup, reload)
{
    desactivePopup();
    activeLoader();
    if(div == undefined)
        div = "content_tableau";
    
    $( document ).ready(function() {
        $.ajax({
            dataType : 'html',
            url: path,
            data: {'Path' : URL , 'Message' : message, 'Entity' : id, 'div' : div, 'option' : option, 'loader' : loader, 'popup' : popup, 'form' : form, 'onclick' : onclick, 'refresh' : refresh, 'div_refresh' : div_refresh, 'form_refresh' : form_refresh, 'iconePopup' : iconePopup, 'withOutPopup' : withOutPopup, 'reload' : reload},
            type: "POST",
            success: function(result){      
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-title").html(title);
                $("#modal-body").html(result);
                activePopup ();
            }
        });
    });
}

function popupConfirmSimple(
    title,
    textContent,
    action,
    payload,
    fnCallback
) {
    // TODO : translate
    activePopup(
        title,
        `<div class="modal-body bs-row flex-y-center">
            <div class="icone-modal interrogation"></div>
            <div class="bs-col p-base">${textContent}</div>
        </div>
        <div class="modal-footer">
            <button type="button" class="button secondaire" 
                data-dismiss="modal" 
                onclick="desactivePopup();"
            >${window.oxaproc.trad['Annuler']}</button>
            <button type="button" class="button principal" data-popupconfirm-btnconfirm>
                ${window.oxaproc.trad['Confirmer']}
            </button>
        </div>`,
        'modal_small'
    );

    let btn = document.querySelector('[data-popupconfirm-btnconfirm]');
    btn.addEventListener('click', function() {
        activeLoader();
        $.ajax({
            url: action,
            data: payload,
            type: "POST",
            success: fnCallback
        });
    });
}

/* Gestion entity */
function ajouterEntity(path, entity, div)
{
    $.ajax({
        dataType : 'html',
        url: path,
        data: {'entity' : entity},
        type: "POST",
        success: function(result){  			
            refrechDiv(window.location.pathname, div);
            desactivePopup();
        }
    });
}
/* ****** */
function AjaxGestion(path, div, params, popup, form)
{
    activeLoader();

    $.ajax({
        dataType : 'html',
        url: path,
        type: "POST",
        data: {'option' : params},
        success: function(result){
            desactiveLoader();
            if(div=='page')
            window.location.reload();
            else if(popup=='true')
            {
                $("#modal-content").addClass("modal_small");
                $("#modal-title").html('');
                $("#modal-body").html(result);
                activePopup ();
                
                refrechDiv(window.location.pathname, div, form);
            }
            else
            {
                refrechDiv(window.location.pathname, div, form);
            }

        }
    });
}
function AjaxTypeAchat(path, typeAchat)
{
    $.ajax({
        dataType : 'html',
        url: path,
        data : { 'typeAchat' : typeAchat },
        type: "POST",
        success: function(result){
            //$('#content_tableau').html(result);
            window.location.reload();
        }
    });
}
/**Export CSV **/
function exportCSV(path, nomFormulaire)
{
    document.getElementById("loader").style.display = "block";
    $.ajax({
        dataType : 'html',
        url: path,
        type: "POST",
        data: $('#'+nomFormulaire).serialize(),
        success: function(result){
            document.getElementById("loader").style.display = "none";
            window.open(result, '_blank');
        }
    }); 
}

function exportCSV2(path, nomFormulaire,pathInformation, pathPopupCreatFic)
{
    activeLoader();
    var myForm = [];

    if (nomFormulaire !== '') {
        myForm = $('#'+nomFormulaire).serializeArray();
    }


    myForm.push({name : 'exportPathAction', value :path});

    jQuery.ajax({
        url: pathPopupCreatFic,
        type: 'POST',
        dataType : 'HTML', 
        data: myForm,
        success: function (data) 
        {	
            desactiveLoader();
            var convert = jQuery.parseJSON(data);
            activePopupInformation(pathInformation,'Informations', "", "", "", "", "",convert.msgInfo);
        },	
    });		 
}

function exportCSVWsdl(path, nomFormulaire, pathErreur)
{
    document.getElementById("loader").style.display = "block";
    
    $.ajax({
        url : path,
        type: 'POST',
        dataType : 'JSON',
        data: $('#'+nomFormulaire).serialize(),
        success: function (json) {
            document.getElementById("loader").style.display = "none";
            if(json.statut=='O'){
                window.open(json.url, '_blank');
            }else{
                activePopupErreur(pathErreur, '',  json.erreur);
            }
        }
    });
}

function openPdf(path, nomFormulaire, pathErreur)
{
    document.getElementById("loader").style.display = "block";
    
    $.ajax({
        url : path,
        type: 'POST',
        dataType : 'JSON',
        data: $('#'+nomFormulaire).serialize(),
        success: function (json) {
            document.getElementById("loader").style.display = "none";
            if(json.statut=='O'){
                window.open(json.url, '_blank');
            }else{
                activePopupErreur(pathErreur, '',  json.erreur);
            }
        }
    });
}

function setSessionModule(path, form, fnCallback)
{
    if (!(form instanceof FormData)) {
        form = new FormData(document.getElementById(form));
    }
    
    $.ajax({
        url: path,
        data: form,
        type: "POST",
        contentType: false,
        processData: false,
        success: function(result){
            if (fnCallback != null) {
                fnCallback(result);
            }
        }
    });
}

function unsetSession(path, module, redirection)
{
    $.ajax({
        dataType : 'html',
        url: path,
        type: "POST",
        data: {'module' : module, 'redirection' : redirection},
        success: function(result){
            window.location.href = result;
        }
    });
}
function clickOnglet(path, onglet, module, redirection)
{
    $.ajax({
        url: path,
        type: 'POST',
        dataType: 'html',
        data: {'onglet' : onglet, 'module' : module},
        success: function (htmlData) {
            window.location.href = redirection;
        }
    });
}

function convertDeviseInput()
{
    $('.span_devise_change').html($('#input_DEVISE').val());
//	console.log($('#input_DEVISE').val());
}


function activeLoader()
{
    document.getElementById("loader").style.display = "block";
}
function desactiveLoader()
{
    document.getElementById("loader").style.display = "none";
}

function refreshPage() {
    window.location = window.location.pathname;
}

/**
 * @param {string} s 
 */
function parseHtml(s) {
    const parserEl = document.createElement('div'); // TODO
    parserEl.innerHTML = s;
    return parserEl.firstElementChild;
}

// Cette fonction nous permet lors du clique sur un boutton d'ajouter un élément en plus dans le tableau 

//function addRow(idTab){
//	
//	$("#tableID").find('tbody').append($('<tr>').append($('<td>'))));
//}
//


/**
 * Fonction Convert string representation of date and time to a timestamp
 */
function strtotime(str, now) {  
    // Convert string representation of date and time to a timestamp    
    //   
    // version: 902.2516  
    // discuss at: http://phpjs.org/functions/strtotime  
    // +   original by: Caio Ariede (http://caioariede.com)  
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
    // +      input by: David  
    // +   improved by: Caio Ariede (http://caioariede.com)  
    // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)  
    // *     example 1: strtotime('+1 day', 1129633200);  
    // *     returns 1: 1129719600  
    // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);  
    // *     returns 2: 1130425202  
    // *     example 3: strtotime('last month', 1129633200);  
    // *     returns 3: 1127041200  
    // *     example 4: strtotime('2009-05-04 08:30:00');  
    // *     returns 4: 1241418600  
    var i, match, s, strTmp = '', parse = '';  

    strTmp = str;  
    strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces  
    strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars  

    if (strTmp == 'now') {  
        return (new Date()).getTime();  
    } else if (!isNaN(parse = Date.parse(strTmp))) {  
        return parse/1000;  
    } else if (now) {  
        now = new Date(now);  
    } else {  
        now = new Date();  
    }  

    strTmp = strTmp.toLowerCase();  

    var process = function (m) {  
        var ago = (m[2] && m[2] == 'ago');  
        var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);  

        switch (m[0]) {  
            case 'last':  
            case 'next':  
                switch (m[1].substring(0, 3)) {  
                    case 'yea':  
                        now.setFullYear(now.getFullYear() + num);  
                        break;  
                    case 'mon':  
                        now.setMonth(now.getMonth() + num);  
                        break;  
                    case 'wee':  
                        now.setDate(now.getDate() + (num * 7));  
                        break;  
                    case 'day':  
                        now.setDate(now.getDate() + num);  
                        break;  
                    case 'hou':  
                        now.setHours(now.getHours() + num);  
                        break;  
                    case 'min':  
                        now.setMinutes(now.getMinutes() + num);  
                        break;  
                    case 'sec':  
                        now.setSeconds(now.getSeconds() + num);  
                        break;  
                    default:  
                        var day;  
                        if (typeof (day = __is_day[m[1].substring(0, 3)]) != 'undefined') {  
                            var diff = day - now.getDay();  
                            if (diff == 0) {  
                                diff = 7 * num;  
                            } else if (diff > 0) {  
                                if (m[0] == 'last') diff -= 7;  
                            } else {  
                                if (m[0] == 'next') diff += 7;  
                            }  

                            now.setDate(now.getDate() + diff);  
                        }  
                }  

                break;  

            default:  
                if (/\d+/.test(m[0])) {  
                    num *= parseInt(m[0]);  

                    switch (m[1].substring(0, 3)) {  
                        case 'yea':  
                            now.setFullYear(now.getFullYear() + num);  
                            break;  
                        case 'mon':  
                            now.setMonth(now.getMonth() + num);  
                            break;  
                        case 'wee':  
                            now.setDate(now.getDate() + (num * 7));  
                            break;  
                        case 'day':  
                            now.setDate(now.getDate() + num);  
                            break;  
                        case 'hou':  
                            now.setHours(now.getHours() + num);  
                            break;  
                        case 'min':  
                            now.setMinutes(now.getMinutes() + num);  
                            break;  
                        case 'sec':  
                            now.setSeconds(now.getSeconds() + num);  
                            break;  
                    }  
                } else {  
                    return false;  
                }  

                break;  
        }  

        return true;  
    }  

    var __is =  
    {  
        day:  
        {  
            'sun': 0,  
            'mon': 1,  
            'tue': 2,  
            'wed': 3,  
            'thu': 4,  
            'fri': 5,  
            'sat': 6  
        },  
        mon:  
        {  
            'jan': 0,  
            'feb': 1,  
            'mar': 2,  
            'apr': 3,  
            'may': 4,  
            'jun': 5,  
            'jul': 6,  
            'aug': 7,  
            'sep': 8,  
            'oct': 9,  
            'nov': 10,  
            'dec': 11  
        }  
    }  

    match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/);  

    if (match != null) {  
        if (!match[2]) {  
            match[2] = '00:00:00';  
        } else if (!match[3]) {  
            match[2] += ':00';  
        }  

        s = match[1].split(/-/g);  

        for (i in __is.mon) {  
            if (__is.mon[i] == s[1] - 1) {  
                s[1] = i;  
            }  
        }  

        return strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]);  
    }  

    var regex = '([+-]?\\d+\\s'  
    + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'  
    + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'  
    + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday)'  
    + '|(last|next)\\s'  
    + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'  
    + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'  
    + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday))'  
    + '(\\sago)?';  

    match = strTmp.match(new RegExp(regex, 'g'));  

    if (match == null) {  
        return false;  
    }  

    for (i in match) {  
        if (!process(match[i].split(' '))) {  
            return false;  
        }  
    }  

    return (now);  
}

function refrechDiv(path, id, form, menu, paramJson)
{
    activeLoader();
    if (
        (paramJson != null || paramJson != 'undefined' )
        && (form == 'undefined' || form == null || form == '')
    ) {
        data = paramJson;
    } else if (form) {
        data = $('#'+form).serialize();
    } else {
        data = '';
    }

    $.ajax({
        url: path,
        type: 'POST',
        dataType: 'html',
        data : data,
        success: function (htmlData) {
            refreshFonction(id, htmlData);
            desactiveLoader();
            return true;
        }
    });	
    
    return false;

}

function addFonctionAjax(content)
{
    var parametreJS = '<script type="text/javascript" src="'+baseUrl+'js/parametre.js"></script>';
    var globalJS = '<script type="text/javascript" src="'+baseUrl+'js/global.js"></script>';
    var validator = '<script type="text/javascript" src="'+baseUrl+'js/validator.js"></script>';

    
    return parametreJS+globalJS+validator+content;
}

function refreshFonction(id, content)
{
    let selector = '#'+id;
    if (id.length == 0) {
        selector = '.contenu';
    }

    var result = $('<div />').append(content).find(selector).html();

    $(selector).html(result);
}

function bulleFiltreAdd(path, id ,titre, value, form)
{
    if( $('#'+id).closest("#myModal").length==0)
    {
        $.ajax({
            url: path,
            type: 'POST',
            dataType: 'html',
            data : {'id' : id, 'titre' : titre, 'value' : value},
            success: function (htmlData) 
            {
                if(typeof form === 'object')
                {
                    if(document.form)
                    {
                        document.form.submit();
                    }
                    else
                    {					
                        form.submit();
                    }
                }else
                {
                    $('#'+form, document).submit();
                }
                return true;
            }
        });	
    }

    return false;

}

/**
 * Fonction qui nous split la value dédiée au onChange
 * @return value separated 
 */
function separateurMilier(id)
{
    var nombre = $(id).val();
    
    nombre = nombre.replace(new RegExp(' ', 'g'),'');
    
    nombre += '';
    var sep = ' ';
    var reg = /(\d+)(\d{3})/;
    while( reg.test( nombre)) {
        nombre = nombre.replace( reg, '$1' +sep +'$2');
    }
    
    if (nombre.includes('.')) {
        var splitNbr = nombre.split('.');
        splitNbr[1] = splitNbr[1].replace(' ', '');
        
        nombre = splitNbr[0]+'.'+splitNbr[1];
    }
    
    $(id).val(nombre);
}

/**
 * Fonction qui formate la date en fonction du parametrage
 * @returns date formaté
 */
function formatDate(input, format)
{
    var date = $(input).val();
    date = date.replace(new RegExp('/', 'g'),'');
    date = date.replace(/-/g,'');
    
    if(date=='')
    {
        $(input).val();
    }
    else
    {
        if(format=='jj/mm/aaaa')
        {
            jj = date.substr(0, 2);
            mm = date.substr(2, 2);
            aaaa = date.substr(4, 4);
            
            date = jj+'/'+mm+'/'+aaaa;
        }
        else if(format=='mm/jj/aaaa')
        {
            mm = date.substr(0, 2);
            jj = date.substr(2, 2);
            aaaa = date.substr(4, 4);
            
            date = mm+'/'+jj+'/'+aaaa;
        }
        else if(format=='aa-mm-jj')
        {
            aa = date.substr(0, 2);
            mm = date.substr(2, 2);
            jj = date.substr(4, 2);
            
            date = aa+'-'+mm+'-'+jj;
        }
        else if(format=='aaaa-mm-jj')
        {
            aaaa = date.substr(0, 4);
            mm = date.substr(4, 2);
            jj = date.substr(6, 2);
            
            date = aaaa+'-'+mm+'-'+jj;
        }	
        else if(format=='aaaa/mm/jj')
        {
            aaaa = date.substr(0, 4);
            mm = date.substr(4, 2);
            jj = date.substr(6, 2);
            
            date = aaaa+'/'+mm+'/'+jj;
        }
        
        $(input).val(date);
    }
}
/* CS */
function initCs(path, destination, source, value, code_edition, codeSte)
{
    $.ajax({
        dataType : 'JSON',
        url : path,
        data : {desti : destination, source : source, value : value, codeSte:codeSte},
        type: "POST",
        success: function (data) {
            separateur = data.Constante;
            if(data.ListeCS){
                for(i=0; i<data.ListeCS.length; i++){
                    valueCS = data.ListeCS[i].split(separateur);
                    if(valueCS[2]=='LOGIQUE')
                    {
                        
                        if(valueCS[1]=='O')
                        {
                            valueCS[1] = true;
                        }
                        else
                        {
                            valueCS[1] = false;
                        }
                        
                        changeValueSwitch('CS_EXTENTION'+separateur+destination+separateur+code_edition+separateur+valueCS[0], valueCS[1]);
                    }
                    else
                    {
                        console.log('#text_CS_EXTENTION'+separateur+destination+separateur+code_edition+separateur+valueCS[0]);
                        if($('#text_CS_EXTENTION'+separateur+destination+separateur+code_edition+separateur+valueCS[0]).length)
                        {
                            $('#text_CS_EXTENTION'+separateur+destination+separateur+code_edition+separateur+valueCS[0]).val(valueCS[1]).change();					
                        }else {
                            $('#input_CS_EXTENTION'+separateur+destination+separateur+code_edition+separateur+valueCS[0]).val(valueCS[1]);
                        }
                    }
                    
                }
            }
        }
    });
}
/* text_CS_EXTENTIONdebut-----finFAC_LIGdebut-----fin0000014521debut-----fin11 */

/* Menu Contextuel : Click droit FAVORIS */


$(function() {
    $.contextMenu({
        selector: '.menu_fav_ajout', 
        items: {
            "ajout": {
                name: addFavoris, 
                icon: "favoris",
                callback: function(itemKey, option, e) {
                    ajouterFavorisLeft(option.$trigger);
                }
            },    
        },
    });   
});

$(function() {
    $.contextMenu({
        selector: '.menu_fav_suppr', 
        items: {
            "suppresion": {
                name: deleteFavoris, 
                icon: "favoris",
                callback: function(itemKey, option, e) {
                    supprimerFavorisLeft(option.$trigger);
                }
            },    
        },
    });   
});

/* validator password */
function affichageValidatorPassword(path, div, idInput)
{
    $.ajax({
        dataType : 'html',
        url: path,
        data: {'input' : $('#'+idInput).val()}, 
        type: "POST",
        success: function(result){    				
            $("#"+div).html(result);

        }
    });
}

$('.switch input').click(function() {
    if ($(this).is(':checked')== true){
        $(this).parent().find('.value_switch').text('Oui');
    } else {
        $(this).parent().find('.value_switch').text('Non');

    }
    
});

/* permet le changement de value d'un switch avec son libelle */
function changeValueSwitch(input, value)
{
    if(value)
    {
        $("#input_"+input).prop('checked', true).blur();
        $("#value_switch_"+input).html($("#input_"+input).data('oui'));
    }
    else
    {
        $("#input_"+input).prop('checked', false);
        $("#value_switch_"+input).html($("#input_"+input).data('non'));
    }
}


function changeValueMultiSelect(divCode, codeValue, divLibelle, libelleValue)
{    
    $('#'+divLibelle).val(libelleValue);
    $('#'+divCode).val(codeValue).change();
    
    $('#'+divLibelle).removeClass('error white-tooltip');
    $('#'+divLibelle).removeAttr("data-original-title");

}

function notification(message, destinataire,onclick,url)
{
    var now = new Date();

    socket.emit('envoiNotification',  
            { 
                nom : jQuery('.nom').html(),
                initiale : jQuery('.client > .initiale').html(),
                destinataire : destinataire,
                onclick : onclick,
                url : url,
                nomSociete : jQuery('.nomSocieteHeader').html(),
                texte : now.getHours()+':'+ now.getMinutes()+ ', '+message,
            
            
            }
        ); 	
}
/* Popup ErreurPlusieursSignatures */
function showBtnIgnorerPopupErrSign()
{
    // noDocCheck = '';
    if($('#form_erreurPlusieursXML').find('[name^="noDoc_"]:checked').length>0){
        // $('#form_erreurPlusieursXML').find('[name^="noDoc_"]:checked').each(function() {
        // 	noDocCheck += '|' + $(this).attr('name').replace("noDoc_", "");
        // });
        
        $('#ignorer').show();
    }
    else{
        $('#ignorer').hide();
    }
    
    // $('#listNoDoc').val(noDocCheck.substr(1));
}

/* GlobalAplication Popup Contacts fournisseur */
function changeContactFou(idLigne, module){
    if(module == 'DA'){
        tel = $('#form_contact [name=TEL'+idLigne+']').val();
        fax = $('#form_contact [name=FAX'+idLigne+']').val();
        email = $('#form_contact [name=EMAIL'+idLigne+']').val();
        
        if($('#form_contact [name=TEL'+idLigne+']').val()==''){
            tel = $('#form_contact #telFou').val();
        }
        if($('#form_contact [name=FAX'+idLigne+']').val()==''){
            fax = $('#form_contact #faxFou').val();
        }
        if($('#form_contact [name=EMAIL'+idLigne+']').val()==''){
            email = $('#form_contact #emailFou').val();
        }
        
        $('#form_creationDA #input_TEL_CTCT').val(tel);
        $('#form_creationDA #input_POR_CFOU').val($('#form_contact [name=TELPORT'+idLigne+']').val());
        $('#form_creationDA #input_FAX_CTCT').val(fax);
        $('#form_creationDA #input_EMA_CTCT').val(email);
        if(email!=''){
            $('#iconeEmailFou').show();
        }else{
            $('#iconeEmailFou').hide();
        }
    }
}


function ajaxPopupV2(path,idForm, title)
{
    if (idForm) {
        form = $('#'+idForm).serialize();
    } else {
        form = {};
    }
    activeLoader();
    $.ajax({
        url: path,
        type: 'POST',
        dataType: 'html',
        data: form,
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            }
        },
        success: function (data) {
            desactiveLoader();
            $("#modal-content").addClass("modal_small");
            $("#modal-body").html(data);
            $("#modal-title").html(title);

            activePopup();
        },
        error: function (data){

            var data = jQuery.parseJSON(data.responseText);
            if (data.status == '500') {
                desactiveLoader();
                desactivePopup();
                alert('Internal Server Error.');
            } else {
                // window.location.href = data.path;
                if (data.action == 'close') {
                    desactivePopup();
                    desactiveLoader();
                } else if (data.redirectType == 'V1') {
                    transfertInformationAncienFramework(data.path);
                } else {
                    redirectJSWithPost(data.path , data.post);				
                }
            }
        }
    });
}

function ajaxPopupJSON(path,idForm)
{
    activeLoader();
    $.ajax({
        dataType : 'html',
        url: path,
        type: "POST",
        data: $('#'+idForm).serialize(),
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            }
        },
        success: function(result){
            var data = jQuery.parseJSON(result);
            
            if(data.statut == 'O')
            {
                redirectJSWithPost(data.path, data.post);
            }
            else
            {
                desactiveLoader();
                $("#modal-content").addClass("modal_small");
                $("#modal-body").html(data.content);
                activePopup();
            }
        }
    });	
}

/**
 * Support for css height transition value<->auto 
 */
function updateCollapsable() {
    document.querySelectorAll('[data-collaspsable]').forEach(function( elem ) {
        let prev = elem.style.width;
        elem.style.setProperty('width', 'auto', 'important');
        let s = elem.getBoundingClientRect().width.toString() + 'px';
        elem.style.setProperty('width', prev);
        setTimeout(() => {
            elem.style.setProperty('width', s);
        });
        
    });
}

function init(AjaxNotificationMajNotification, calendarJPG, paramDateFormat, AjaxAutoCompleteAutocomplete)
{
    window.config = {
        datepicker: {
            showOn: "button",
            changeYear: true,
            changeMonth: true,
            buttonImage: calendarJPG,
            buttonImageOnly: true,
            showAnim: "fade",
            dateFormat: paramDateFormat
        }
    };

    $(function() {
        //  $.ajax({
        // 	 url : AjaxNotificationMajNotification, 
        // 	 type: "POST",
        // 	 success : function(data){ 
        // 		 $( "#sidebarMenu" ).append(data);
        // 	 }
        //  });


        //_____________________________________________________________________
        // Datepicker

        // on vérifie l'existence d'un attritbut data-maxdate avant d'exécuter datepicker
        function datepickerConfig() {
            $('.datepicker:not(:read-only):not(:disabled)').each(function() {
                let params = window.config.datepicker;
                $(this).datepicker(Object.assign(params, {'maxDate': ($(this).attr('data-maxdate') ?? '')}));
            });
        }

        datepickerConfig();

        // Bind on dom mutation
        const observer = new MutationObserver(function (mutationList) {
            // TODO: only process new dom
            datepickerConfig();
        });
        observer.observe(document.body, {
            attributes: false,
            childList: true,
            subtree: true,
            characterData: false
        });

        //_____________________________________________________________________
        // Menu contextuel

        function listenMC() {
            let containers = document.querySelectorAll('[data-container-contextuel]');

            containers.forEach((element) => {
                let parentId = element.getAttribute('data-container-contextuel');
                
                // TODO : use CSS instead
                let parent = document.querySelector('#'+parentId);
                parent.addEventListener('mouseover', (event)=> {
                    element.style.opacity = 1;
                });
                parent.addEventListener('mouseout', (event) =>{
                    element.style.opacity = 0;
                });

                // Prevent element from been processed twice
                element.removeAttribute('data-container-contextuel');
            });
        }

        // Bind on dom mutation
        const observerMc = new MutationObserver(function (mutationList) {
            // TODO: only process new dom
            listenMC();
        });
        observerMc.observe(document.body, {
            attributes: false,
            childList: true,
            subtree: true,
            characterData: false
        });
        listenMC();
        

        //_____________________________________________________________________

        // TODO on dom mutation
        window.addEventListener('resize',updateCollapsable);
        updateCollapsable();
        //_____________________________________________________________________
        
        $( ".autocomplete" ).autocomplete({
         minLength: 0,
        source: function(requete, response){ // la fonction anonyme permet de maintenir une requête AJAX directement dans le plugin

                if (!$('#'+this.element[0].id).data('autocomplete')) {
                    return;
                }

                var $el = $('#'+this.element[0].id);
                var entity = $el.data().autocomplete;
                if($el.data().autocomplete.indexOf("libelle_") == 0)
                {
                    entity = $el.data().autocomplete.replace('libelle_', '');
                }
                
                if($el.data().autocompletefunction && $el.data().autocompletefunction != '')
                {
                    var pathAuto = AjaxAutoCompleteAutocomplete+'/'+$el.data().autocompletefunction;
                }else{
                    var pathAuto = AjaxAutoCompleteAutocomplete;
                }
                var autocompletearray ='';
                if($el.data().autocompletearray && $el.data().autocompletearray != '')
                {
                    autocompletearray =  $el.data().autocompletearray;
                }

                var codeSte = '';
                if($el.data().stelink) {
                    codeSte = $('#'+$el.data().stelink).val();
                } else if ($el.data().codeste) {
                    codeSte = $el.data().codeste;
                }

                var tsDon = '';
                if($el.data().tsdon) {
                    tsDon = $el.data().tsdon
                }

                // autocompletearray = JSON.parse(autocompletearray);
                var paramAjax = {'search' : requete.term, 'entity' : entity, 'codeSte': codeSte, 'tsDon' : tsDon};
                paramAjax = $.extend(paramAjax, autocompletearray);
                paramAjax.toto = eval("(" + paramAjax.toto + ")");


                if ($el.data().formperimetre != '') {
                    paramAjax.postperimetre = $('#'+$el.data().formperimetre).serialize();
                }
                
                $.ajax({
                    url : pathAuto, // on appelle le script JSON
                    dataType : 'json', // on spécifie bien que le type de données est en JSON
                    type: "POST",
                    data: paramAjax,
                    
                    success : function(data){ 
                        response(data);// on se prépare à renvoyer les données réceptionnées grâce à l'évènement de succès
                    }
                });
            },
            select: function(event, ui){
                var entity=event.target.attributes['data-autocomplete'].value;
                var i = 0;
                if(event.target.attributes['data-autocomplete'].value.indexOf("libelle_") == 0)
                {
                    entity = event.target.attributes['data-autocomplete'].value.replace('libelle_', '');
                    i = 1;
                }
    
                if(event.target.attributes['data-autocompletefunction'] && event.target.attributes['data-autocompletefunction'].value != '')
                {
                    var pathAuto = AjaxAutoCompleteAutocomplete+'/'+event.target.attributes['data-autocompletefunction'].value;
                }else{
                    var pathAuto = AjaxAutoCompleteAutocomplete;
                }

                var autocompletearray ='';
                if(event.target.attributes['data-autocompletearray'] && event.target.attributes['data-autocompletearray'].value != '')
                {
                    autocompletearray = event.target.attributes['data-autocompletearray'].value;
                }
                // autocompletearray = JSON.parse(autocompletearray);
                // console.log(event.target.attributes['data-autocompletearray'].value);
                var paramAjax = {'value' : ui.item.label, 'entity' : entity};
                paramAjax = $.extend(paramAjax, autocompletearray);

                $.ajax({
                    url : pathAuto, // on appelle le script JSON
                    dataType : 'json', // on spécifie bien que le type de données est en JSON
                    type: "POST",
                    data: paramAjax,
                    
                    success : function(data){ 
                        
                        
                        var idValue = event.target.attributes['id'].value;
                        if($('#'+event.target.attributes['id'].value.replace('text_', 'input_')).length != 0 && '#'+event.target.attributes['id'].value.replace('text_', 'input_') != '#'+event.target.attributes['id'].value)
                        {
                            var idHidden = event.target.attributes['id'].value.replace('text_', 'input_');
                            $('#'+idHidden).val(data);
                            $('#'+idValue).val(data);
                        }else
                        {
                            if(i)
                            {
                                $('#'+idValue).val(ui.item.label);
                            }else{
                                $('#'+idValue).val(data);
                            }
                        }

                        if(event.target.attributes['data-idform'] && event.target.attributes['data-idform'].value != '')
                        {
                            $('#'+event.target.attributes['data-idform'].value).submit();
                        }
                    }
                });
            
            }
        });
    });
    
    function showDatepicker(id,calendarJPG, paramDateFormat)
    {	

        $(id).datepicker({
            showOn: "button",
            changeYear: true,
            changeMonth: true,
            buttonImage: calendarJPG,
            buttonImageOnly: true,
            showAnim: "fade", 
            dateFormat: paramDateFormat
        });
    }
    
    var playSound = (function(){
        var s,
            sounds = {},
            soundUrls = {
        laser: baseUrl+'son/notification.mp3'
        };
        
        for(s in soundUrls){
        sounds[s] = new Audio(soundUrls[s]);
        sounds[s].preload = 'auto';
        sounds[s].load();
        }
        
        return function(soundname){
            if(soundname in sounds){
            sounds[soundname].play();
            }
        };
    })();
    
    var playSoundMessage = (function(){
        var s,
            sounds = {},
            soundUrls = {
        laser: baseUrl+'son/message.mp3'
        };
        
        for(s in soundUrls){
        sounds[s] = new Audio(soundUrls[s]);
        sounds[s].preload = 'auto';
        sounds[s].load();
        }
        
        return function(soundname){
            if(soundname in sounds){
            sounds[soundname].play();
            }
        };
    })();
        
    
    $(document).click(function(event) { 
        if(!$(event.target).closest('#sidebarMenu').length && !$(event.target).closest('#sidebarIconToggleId').length) {
        
            if($('#openSidebarMenu').is(':checked') ){
        
                $("#openSidebarMenu").prop('checked', false);
                $("#imgFooterLogo").hide();
            }
            } else
    
            if($(event.target).closest('#sidebarIconToggleId').length ){
        
                if(!$('#openSidebarMenu').is(':checked') ){
            
                    $("#imgFooterLogo").fadeIn();
                    $("#openSidebarMenu").prop('checked', true);
                }else{
                    
                    $("#imgFooterLogo").hide();
                    $("#openSidebarMenu").prop('checked', false);
                }
            }
            
    });
    
    jQuery(document).ready(function(){
        jQuery('.toast__close').click(function(e){
        e.preventDefault();
        var parent =  jQuery(this).parent('.toast');
        parent.fadeOut("slow", function() {  jQuery(this).remove(); } );
        });
    });
}

$(function() {
    $("[id^=mail_CS_EXTENTION]").click(function(){
        id = $(this).attr('id');
        name_input = id.replace('mail_', '');
        if($('[name="'+name_input+'"]').val() != ""){
            document.location.href = "mailto:"+$('[name="'+name_input+'"]').val();
        }
    });
    $("[id^=url_CS_EXTENTION]").click(function(){
        id = $(this).attr('id');
        name_input = id.replace('url_', '');
        if($('[name="'+name_input+'"]').val() != ""){
            window.open($('[name="'+name_input+'"]').val(), "_blank");
        }
    });
});

/** Function drag & drop (reorder) */

function reOrder(dom, domTarget, item, prev, next, newPosition, sign) {
    const initialPosition = item.attr('data-order')
    item.attr('data-order', 0)

    $(dom).find(domTarget).each(function(i, e) {
        const currentElementOrder = parseInt($(e).attr('data-order'))
        if(sign === "+") {
            if(currentElementOrder >= newPosition && currentElementOrder <= initialPosition) {
                $(e).attr('data-order', currentElementOrder+1)
            }
        } else {
            if(currentElementOrder <= newPosition && currentElementOrder >= initialPosition) {
                $(e).attr('data-order', currentElementOrder-1)
            }
        }
    });

    item.attr('data-order', newPosition)

    return newPosition
}

function findNewPosition(prev, next, sign) {
    if(sign === "-")
        return prev
    if(undefined === prev || isNaN(prev))
        return 1
    else
        return parseInt(prev)+1
}

function strBuild() {
    // TODO 
    // .replace('@1@', Math.ceil(fileSizeMax / 1000000)/* Convert byte to Mb */);
    
}


function formDataToObj(formData) {
    let obj = {};
    for (var pair of formData.entries()) {
        obj[ pair[0] ] = pair[1];
    }
    return obj;
}

function redirectJSWithPost(url, values, method, target, traditional, redirectTop)
{
    if(values)
    {
        values[$('#tokenCSRF').attr('name')] = $('#tokenCSRF').val();
    }
    $.redirect(url, values, method, target, traditional, redirectTop);
}
function changeModule(path, mode){
    activeLoader();
    $.ajax({
        dataType : 'html',
        url: path,
        data: {'type' : mode},
        type: "POST",
        statusCode: {
            413: function(xhr) {
                desactiveLoader();
                desactivePopup();
                alert('Error - ModSecurity.');
            }
        },
        success: function(result){
            refrechDiv(window.location.pathname, 'menu-principal');
        }
    });
}
// creation du unserialize
function unserialize(data) {
    data = data.split('&');
    var response = {};
    for (var s of data){
        var newData = s.split('=');
        response[newData[0]] = newData[1];
    }
    return response;
}

// Implementation du CSRF
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
   
    if (options.type.toLowerCase() != 'post') {
        return;
    }

    if( options.data instanceof FormData ) {
        if( ! options.data.has('tokenCSRF') ) {
            options.data.append($('#tokenCSRF').attr('name'), $('#tokenCSRF').val());
        }
        return;
    }

    if(!options.mimeType || options.mimeType == '') {
        if (typeof options.data === 'string' || options.data instanceof String) {
            var dataSerrialize = options.data;
            if('tokenCSRF' in unserialize(dataSerrialize) == false) {
                options.data += '&' + encodeURIComponent($('#tokenCSRF').attr('name')) + '='+encodeURIComponent($('#tokenCSRF').val());
    
                if (options.data.charAt(0) == '&') {
                    options.data = options.data.substr(1);
                }
            }
        } else if (typeof options.data == 'object') {
            options.data.tokenCSRF = $('#tokenCSRF').val();
        }
    } else {
        options.data.append($('#tokenCSRF').attr('name'), $('#tokenCSRF').val());
    }

});

function asyncPanier(url) {
    function asynchrone(){
        setTimeout(function(){
            $.ajax({
                dataType : 'JSON',
                url: url,
                data: {},
                type: 'POST',
                success: function(retour) {
                    if(retour.Statut == 'W') {
                        asynchrone();

                        return;
                    } else if(retour.Statut == 'O') {
                        redirectJSWithPost(retour.path, retour.post);
                    } else if (retour.Statut == 'E') {
                        desactiveLoader();
                        $("#modal-content").addClass("modal_small");
                        $("#modal-body").html(retour.content);
                        activePopup();
                        return;
                    } else {
                        return;
                    }
                }, 
                error: function (data){
                    desactiveLoader();
                    $("#modal-content").addClass("modal_small");
                    $("#modal-body").html(data.responseText);
                    activePopup();
                } 
            }); 
        }, 1000);
    }

    asynchrone();
}

function consoliderGrille(path, pathInformation, titrePopup) {
    activeLoader();

    $.ajax({
        url: path,
        type: 'POST',
        dataType: 'JSON',
        processData: false, // Required to use FormData
        success: (response) => {
            let message = (response.file !== '') ? response.file : '';
            activePopupInformation(pathInformation, response.titre, "", "", "", "", "", response.message+'\\r\\n'+message);
        },
        error: (response) => {
            desactiveLoader();
            $("#modal-content").addClass("modal_small");
            $("#modal-title").html(titrePopup);
            $("#modal-body").html(response.responseText);
            activePopup();
        },
    });
}
/**
 * usage :  
 *     onsubmit="return ajaxSubmit(event);"
 * @param SubmitEvent|HTMLFormElement event  
 * @param FormData|null formDataSup 
 */
function ajaxSubmit(event, formDataSup) {
    
    // Get form
    let form = event;
    if (event instanceof Event) {
        event.preventDefault();
        form = event.target;
    }

    activeLoader();
    let formData = new FormData(form);

    // Submitter data
    if (event.submitter && event.submitter.name) {
        formData.append(
            event.submitter.name,
            event.submitter.value
        );
    }

    // Merge formData
    if (formDataSup !== undefined) {
        for (const pair of formDataSup.entries()) {
            formData.append(pair[0], pair[1]);
        }
    }

    $.ajax({
        url: form.getAttribute('action'),
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function (response, status, xhr) {
            if (xhr.getResponseHeader('Content-Type') == 'application/json') {
                response = JSON.parse(xhr.responseText);
            }

            // Call success callback
            if (form.hasAttribute('data-onsuccess')) {
                window.action[ form.getAttribute('data-onsuccess') ](response, status, xhr, form);
                return;
            }
            if (form.hasAttribute('data-onsuccess-goto')) {
                location.href = form.getAttribute('data-onsuccess-goto');
                return;
            }
            desactiveLoader();
        },
        error: function (xhr) {

            // Case : json response (Erreur non bloquante)
            if (xhr.getResponseHeader('Content-Type') == 'application/json') {
                response = JSON.parse(xhr.responseText);

                // Failsafe : only handle response 'confirm' for json content type
                if (response.type != 'confirm') {
                    throw '!!!';
                }

                desactiveLoader();
                activePopup(
                    window.oxaproc.trad['Erreur validation'],
                    response.popupHtml,
                    'modal_small'
                );
                document.querySelector('[data-popupwarning-cancel]')
                    .addEventListener('click', function () {
                        desactivePopup();
                    });
                document.querySelector('[data-popupwarning-continue]')
                    .addEventListener('click', function () {
                        // Resend form with confirm
                        formData = new FormData();
                        formData.append('confirm', '1');
                        ajaxSubmit(form, formData);
                        desactivePopup();
                    });
                return;
            }

            // Call error callback
            if (form.hasAttribute('data-onerror')) {
                window.action[ form.getAttribute('data-onerror') ](xhr, form);
                return;
            }

            // Case : form has an error displayer
            let wrapperError = form.querySelector('[data-form-error]');
            if (wrapperError) {
                wrapperError.innerHTML = xhr.responseText;
                desactiveLoader();
                wrapperError.scrollIntoView({behavior: 'smooth', block: 'nearest'});
                return;
            }

            // Assume http 400 -> show constraint validation error
            desactiveLoader();
            activePopupError(
                window.oxaproc.trad['Erreur validation'],
                xhr.responseText,
                'modal_small'
            );
        }
    });
    return false;
}

/**
 * @param String path  
 * @param FormData|object|null data 
 */
function ajaxSimple(path, data, fnSuccess, fnError = null) {

    $.ajax({
        url: path,
        type: 'POST',
        data: toFormData(data),
        contentType: false,
        processData: false,
        success: function (response, status, xhr) {
            if (xhr.getResponseHeader('Content-Type') == 'application/json') {
                response = JSON.parse(xhr.responseText);
            }

            fnSuccess(response, status, xhr, data);
            desactiveLoader();
        },
        error: fnError ?? (function (xhr) {
            activePopupError(
                window.oxaproc.trad['Erreur validation'],
                xhr.responseText,
                'modal_small'
            );

            // Assume http 400 -> show constraint validation error
            desactiveLoader();
        })
    });
    return false;
}

function toFormData(payload) {
    if ( payload instanceof FormData ) {
        return payload;
    }
    var form_data = new FormData();
    for ( var key in payload ) {
        form_data.append(key, payload[key]);
    }
    return form_data;
}

function ajaxHtmlUpdate(target, path, payload, callback) {
    if (typeof target === 'string') {
        target = document.querySelector(target);
    }

    payload = toFormData(payload);
    
    activeLoader();
    return $.ajax({
        url: path,
        type: 'POST',
        data: payload,
        contentType: false,
        processData: false,
        success: function (response, status, xhr) {
            // target.innerHTML = response;
            target.innerHTML = response;
            if (callback) {
                callback(response, status, xhr);
            }
            
            desactiveLoader();
        },
        error: function (xhr) {
            if (callback) {
                callback(null, xhr.status, xhr);
            }
            desactiveLoader();
        }
    });
}

function iframeHeightAuto(obj) {
    obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
}

function gestionBackUp(path, id)
{
    activeLoader();
    $.ajax({
        url: path,
        type: 'POST',
        dataType: 'html',
        data: {idBackup : id},
        success: function (data) {
            desactiveLoader();
            $("#modal-content").addClass("modal_small");
            $("#modal-body").html(data);
            $("#modal-title").html('');

            activePopup();
        },
        error: function (data){
            var data = jQuery.parseJSON(data.responseText);
            if (data.status == '500') {
                desactiveLoader();
                desactivePopup();
                alert('Internal Server Error.');
            } else {
                //window.location.href = data.path;
                if (data.action == 'close') {
                    desactivePopup();
                    desactiveLoader();
                } else {
                    redirectJSWithPost(data.path , data.post);
                }
            }
        }
    });
}

window.action = Object.assign(window.action|{},{
    pageRefresh: () => {
        location.reload();	// TODO : for POST use redirection (ariane ?)
    },
    ajaxPopup: ( ev ) => {
        let el = ev.target;
        ajaxPopup(
            el.getAttribute('data-ajaxpopup-path'),
            el.getAttribute('data-ajaxpopup-title'),
        );
    },
    acsblt_changeFontSize: ( ev ) => {
        let value = parseInt(ev.target.value);
        window.acsblt_setRootFontSize( value );
        // Save into local storage
        localStorage.setItem('acsblt-fs', value);

        ev.target.scrollIntoView();
    },
    acsblt_closeBox: ( ev ) => {
        let section = document.getElementById('section-acsblt');
        section.firstElementChild.style.display = 'none';
        section.lastElementChild.style.display = '';
    },
    acsblt_openBox: ( ev ) => {
        let section = document.getElementById('section-acsblt');
        section.firstElementChild.style.display = '';
        section.lastElementChild.style.display = 'none';
    },
    acsblt_toggleHightContrast: () => {
        // Toggle contrast mode (0->1, 1->0)
        var i = window.acsblt_getContrastMode() ? 0 : 1;
        window.acsblt_setContrastMode( i );
        // Save into local storage
        localStorage.setItem('acsblt-contrast', i);
        // TODO : update button view
    },
    menuProfile_changeBackup: (event) => {

		idUser = $(event.target).attr('value');

        gestionBackUp(window.oxaproc.path.pathActiveBackup, idUser);

		// transfertInformationAncienFramework("TraiteAsync('user_backup.php?action=activeBackup&codeUser="+idUser+"',document.forms.form_gestion.listeBackup,'','Activation du mode backup en cours')");

    },
    menuProfile_quitBackup: (event) => {
        if( !confirm( 
            event.target.getAttribute('data-quit-message') 
        ) ) return;

        gestionBackUp(window.oxaproc.path.pathDesactiveBackup, '');
        // transfertInformationAncienFramework("CallUrlAsync('user_backup.php?action=deconnexionBackup',document.forms.form_gestion.listeBackup,'','Désactivation du mode backup en cours...')");
    },
    successFormDocTypeUpdate: function (response, status, xhr) { // TODO : rename into 'doNothing' or move somewhere else
        // TODO : reload page ?
        desactiveLoader();
        desactivePopup();
    },
    closePopup: function (response, status, xhr) {
        desactiveLoader();
        desactivePopup();
    },
    successFormPopup: function (response, status, xhr) {
        desactiveLoader();
        activePopup(
            response.title,
            response.bodyHtml,
            response.class
        );
    },
    arianePop: (response, status, xhr) => {
        let _ariane = window.oxaproc.ariane;
        if (_ariane.stack.length == 0) {
            throw 'ariane has no path';
        }
        let lastPath = _ariane.stack[ _ariane.stack.length - 2 ];
        // Case: Current route wasn't register inside the ariane -> take the next route
        if (lastPath == null) {
            lastPath = _ariane.stack[ _ariane.stack.length - 1 ];
        }
        if (lastPath == null) {
            window.action.pageRefresh();
            return;
        }

        activeLoader();	
        redirectJSWithPost( lastPath.path, lastPath.post );
    },
    arianeReload: () => {
        let _ariane = window.oxaproc.ariane;
        if (_ariane.stack.length == 0) {
            throw 'ariane has no path';
        }
        let lastPath = _ariane.stack[ _ariane.stack.length - 1 ];

        activeLoader();	
        redirectJSWithPost( lastPath.path, lastPath.post );
    },
    successPopupExport: () => {
        desactiveLoader();
        activePopupInfo(
            window.oxaproc.trad['Informations'],
            window.oxaproc.trad['SuccessPopupExportBody'],
            'modal_small'
        );
    },
    followLink: function (response, status, xhr) {
        window.location.href = response.resourceUrl ?? response.path;
    },
});

document.addEventListener('click',(event) => {
    let target = event.target;
    if (!(target instanceof HTMLElement)) return;
    let actioner = target.closest('[data-action-click]');
    if (actioner == null) return;

    window.action[ actioner.getAttribute('data-action-click') ]( event, actioner );
    return false;
});
document.addEventListener('change',(event) => {
    var target = event.target;
    if( !(target instanceof HTMLElement) ) return;
    if( !target.hasAttribute('data-action-change') ) return;

    window.action[ target.getAttribute('data-action-change') ]( event );
    return false;
});

window.acsblt_setRootFontSize = ( i ) => {

    if( !Number.isInteger( i ) ) throw 'Invalid value '+JSON.stringify(i); 
    var root = document.querySelector(':root');
    root.style.fontSize = (12 + i) + 'px';
}
window.acsblt_setContrastMode = ( i ) => {
    if( i == 1 )
        document.body.classList.add('hight-contrast-mode');
    else 
        document.body.classList.remove('hight-contrast-mode');
}
window.acsblt_getContrastMode = () => {
    return document.body.classList.contains('hight-contrast-mode') ? 1 : 0;
}

prPageLoad = new Promise(function( resolve, reject) {

    // Case : `DOMContentLoaded` has already fired
    if (document.readyState === 'complete')
        resolve(document);

    // Loading hasn't finished yet
    window.addEventListener('DOMContentLoaded', function( ev ) {
        resolve(document);
    });
});

prPageLoad.then(() => {
    // TODO : load AFTER dom parsing and BEFORE css rendering
    // Load prefered font-size from local storage
    let i = localStorage.getItem('acsblt-fs');
    if( i == null ) return;
    window.acsblt_setRootFontSize( parseInt(i) );
    var ascblt_control_box = document.getElementById('menu-acsblt');
    if( ascblt_control_box != null )
        ascblt_control_box.querySelector('input[type=range]').value = i;
}).then(() => {
    // TODO : load AFTER dom parsing and BEFORE css rendering
    // Load prefered contrast mode from local storage
    let i = localStorage.getItem('acsblt-contrast');
    if( i == null ) return;
    window.acsblt_setContrastMode( parseInt(i) );
})

var scrollTimeout = null;
window.addEventListener('scroll', function (event) {
    if(scrollTimeout) {
        clearTimeout(scrollTimeout);
    }
    
    scrollTimeout = setTimeout(function() {
        window.dispatchEvent(new CustomEvent(
            'scroll-echo',
            {detail: {original_event: event}}
        ));
    }, 10);
});

window.addEventListener('scroll-echo', function (event) {
    for (el of document.querySelectorAll('.follow-scroll')) {
        if (! el.hasOwnProperty('followScrollOffset'))
            el.followScrollOffset = el.offsetTop;
        if (window.pageYOffset > el.followScrollOffset) {
            // Create placeholder
            let markPlaceholder = 'data-followscroll-placeholder';
            if (! el.nextElementSibling.hasAttribute(markPlaceholder)) {
                let div = document.createElement('div');
                div.setAttribute(markPlaceholder, '');
                div.style.width = el.offsetWidth + 'px';
                div.style.height = el.offsetHeight + 'px';
                el.after(div);
            }
            el.classList.add('position-fixed');
        } else {
            el.classList.remove('position-fixed');
        }
    }
});

//_____________________________________________________________________________
// On change echo

document.addEventListener('change', function (event) {

    var target = event.target;

    if (!target.hasAttribute('data-onchangeecho')) {
        return;
    }

    if (target._change_echo != null) {
        clearTimeout(target._change_echo);
    }
    target._change_echo = setTimeout(function() {
        target.dispatchEvent(new CustomEvent(
            'change-echo',
            {
                bubbles: true,
                detail: {original_event: event}
            }
        ));
    }, target.getAttribute('data-onchangeecho-delta') ?? 750);
});

// Interpret attribute "data-onchangeecho"
document.addEventListener('change-echo', function (event) {
    let codejs = event.detail.original_event.target.getAttribute('data-onchangeecho');
    if (codejs == null || codejs.length == 0) {
        return;
    }
    eval(codejs);
});

//_____________________________________________________________________________
// Async WSDL

function asyncBackground(callback, payload, url) {

    function asynchrone(){
        setTimeout(function(){
            $.ajax({
                dataType : 'JSON',
                url: 
                    (typeof url !== 'undefined' ? 
                        url : 
                        window.oxaproc.path['Outil.Asynchrone.getResultAsynchrone']
                    ),
                data: payload,
                type: 'POST',
                success: function(retour) {
                    if(retour.Statut != 'O') {
                        asynchrone();
                        return;
                    }
                    
                    post = retour.post;
                    if(post.redirect){
                        redirectJSWithPost(post.pathRetour);
                        return;   
                    }
                    
                    // Success
                    if (callback != null) {
                        callback(payload, retour.reponseWSDL);
                    }
                    
                }, 
                error: function (data){
                    desactiveLoader();
                    $("#modal-content").addClass("modal_small");
                    $("#modal-body").html(data.responseText);
                    activePopup();
                } 
            }); 
        }, 2000);
    }

    asynchrone();

}

//_____________________________________________________________________________
// ErreurXMl

// TODO : remove pathAsync then replace ErreurXml_validationXML with ajaxSubmit


function ErreurXml_validationXML(path, pathAsync){
	activeLoader();
    $.ajax({
    	url : path ,
        type: 'POST',
		dataType : 'JSON',
        data: $('#form_erreurXML').serialize(),
        success: function (data) {
			if(data.statut == 'wsdlEnAsync' && pathAsync){
				asyncBackground(
					function(requestData, dataRetourWsdl) { 
						ErreurXml_wsdlEnAsync(pathAsync, requestData, dataRetourWsdl);
					},
					data
				);
				return;
            } else if(data.statut == 'waiting' && pathAsync){
				return;
			}else if (data.type == 'popup'){
                desactiveLoader();
                $("#modal-content").addClass(data.class);
                $("#modal-body").html(data.bodyHtml);
                $("#modal-title").html(data.title);
                activePopup();

                return;
            }
			
			desactiveLoader();
			$("#modal-title").html('');
			$("#modal-body").html(data);
        },
        error: function (data){

            var IS_JSON = true;
            try {
                var test = jQuery.parseJSON(data.responseText);
            } catch(e) {
                var IS_JSON = false;
            }

            if (IS_JSON) {
                //si retour json code 443, alors on fait la redirection
                var data = jQuery.parseJSON(data.responseText);
                if(data.postGestion){
                    redirectJSWithPost(data.path, data.postGestion);
                    return;
                }

                if (data.divRefresh) {
                   
                   
                    desactivePopup();
                    return;
                }

                window.location.href = data.path;
            } else {
                desactiveLoader();
                $("#modal-body").html(data.responseText);
                return;

            }
        }
    });
}

function ErreurXml_wsdlEnAsync(pathAsync, requestData, dataRetourWsdl) {   
	
	$.ajax({
		dataType : 'JSON',
		url: pathAsync,
		data: {
			dataAsync: requestData,
			dataRetourWsdl: dataRetourWsdl,
		},
		type: 'POST',
		success: function(data) {
			if(data.statut == 'wsdlEnAsync') {
				asyncBackground(
					function(requestData, dataRetourWsdl) { 
						wsdlEnAsync(pathAsync, requestData, dataRetourWsdl);
					},
					data
				);
				return;
			} else if(data.statut == 'waiting' && pathAsync){
				return;
			}
			
			if(data.postGestion){
				redirectJSWithPost(data.path, data.postGestion);
				return;
			}
			
			window.location.href = data.path;
		}, 
		error: function (data){
			desactiveLoader();
			$("#modal-content").addClass("modal_small");
			$("#modal-body").html(data.responseText);
			activePopup();
		} 
	}); 
}

function copyToClipBoard(element, successMessage = '', errorMessage = '', nullMessage = '') {
    let el = document.getElementById(element);

    if (el !== null) {
        let value = el.value;

        navigator.clipboard.writeText(value)
            .then(function() {
                // alert('Texte copié');
            })
            .catch(function(error) {
                // alert('Erreur copy : '+error);
            });
    } else {
        // alert(nullMessage);
    }
}

if(! jForm) {
    var jForm = new FormData();
}
function inputFile(name) {
    

    $input = $("#import"+name);

    $input.on("change", function (e) {
        let file = this.files[0];
        updateInputFileFace(this);
        jForm.delete("import"+name);
        jForm.append("import"+name, file);
    });

    $(document).on("dragenter", "#import"+name, function() {
        $("#file-wrap"+name).css("border", "2px dashed #3377CB");
        
        return false;
    });
        
    $(document).on("dragover", "#import"+name, function(e){
        e.preventDefault();
        e.stopPropagation();
        $("#file-wrap"+name).css("border", "2px dashed #3377CB");
        
        return false;
    });
        
    $(document).on("dragleave", "#import"+name, function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#file-wrap"+name).css("border", "2px dashed #ccc");
        
        return false;
    });

    $(document).on("drop", "#import"+name, function(e) {
        e.preventDefault(); // Prevent Chrome from opening the file
        e.stopPropagation();
        var firstFile = e.originalEvent.dataTransfer.files[0];
        jForm.delete("import"+name);
        jForm.append("import"+name, firstFile);
        let input = document.getElementById("import"+name); 
        input.files = e.originalEvent.dataTransfer.files;
        
        updateInputFileFace(input);
        $("#file-wrap"+name).css("border", "2px dashed #ccc");
        return false; 
    });

    function updateInputFileFace(input) {
        let file = input.files[0];

        let error = null;
        if (file.size > fileSizeMax) {
            error = window.oxaproc.trad['FileSizeMax']
                .replace('@1@', Math.ceil(fileSizeMax / 1000000)/* Convert byte to Mb */);
        }
        input.closest('.file-wrap').querySelector('p').innerHTML = 
            file.name 
            + (error ? 
                '<br><span class="error">'+error+'</span>' : ''
            );
    }
}


jQuery(function(){
    $(function () {
        $(window).scroll(function () { //Fonction appelée quand on descend la page
            if ($(this).scrollTop() > 200 ) {  // Quand on est à 200pixels du haut de page,
                $('#scrollUp').css('right','10px'); // Replace à 10pixels de la droite l'image
            } else { 
                $('#scrollUp').removeAttr( 'style' ); // Enlève les attributs CSS affectés par javascript
            }
        });
    });
});


//_____________________________________________________________________________
// Zoom dependecy revalidate

document.addEventListener('change', function (event) {
    const name = event.target.name;

    Array.from(document.querySelectorAll('[data-zoom-dependency]'))
    .filter((el) => {
        return el.getAttribute('data-zoom-dependency')
            .split(',')
            .includes(name);
    })
    .forEach(el => {
        // Force revalidation using change event
        el.dispatchEvent(new Event('change'));
    });
});
//_____________________________________________________________________________
// SimplePaginator

function pagination(el, paginator, fnAction) {
    $el = $(el ?? '#pagination');
    if (paginator.pageCount <= 1) {
        $el.addClass('d-none');
        return;
    }
    $el.removeClass('d-none');
    $(el ?? '#pagination').twbsPagination({
        totalPages: paginator.pageCount,
        visiblePages: 5,
        startPage: paginator.page,
        next: '>',
        prev: '<',
        last: '>>',
        first: '<<',
        initiateStartPageClick: false,
        onInit: function () {
            // fire first page loading
        },
        onPageClick: fnAction, //function (event, page) {}
    });

}
/**
 * 
 * @param HTMLElement|string el 
 * @param HTMLElement|string elRefresh 
 * @param {postKey?:string, path: string, pageCount: int, page: int} paginator 
 */
function ajaxPagination(el, elRefresh, paginator, fnGetFormData) {
    pagination(el, paginator, function (event, page) {
        let formData = fnGetFormData();
        formData.append(paginator.postKey, page);

        $.ajax({
            url: paginator.path,
            type: 'POST',
            contentType: false,
            processData: false,
            data: formData,
            success: function (htmlData) {
                var $elrefresh = $(elRefresh);
                var $result = $('<div/>').append(htmlData).find('#' + $elrefresh[0].id);
                $elrefresh.replaceWith($result);
                $result.find('.table')[0].scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                });
            }
        })
    });
}
//_____________________________________________________________________________
// Simple Templater

function getJsTemplate(id) {
    return window.template[ id ];
}

function renderJsTemplate(tpl, mapReplace) {
    for (const k in mapReplace) {
        tpl = tpl.replaceAll('%'+k+'%', mapReplace[ k ]);
    }
    return tpl;
}

// function stringToElement(holder = 'div') {
//     let tmp = document.createElement(root);
//     tmp.innerHTML = renderJsTemplate(tpl, mapReplace);
//     return tmp.;
// }
