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

// test MSA

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;

}


//_____________________________________________________________________________
// Autocomplete (fourniss)

// TODO : remove ?
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 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);
    }   
    $('#mainAriane .ariane-icon-close:not(:last)').hide();
    
    $('.hiddenAriane').show();
}

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

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

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

//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;
}
}


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 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 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);
    }
        
}

/** 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 ************/




/* 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 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;
}






/* 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
                    {
                        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 */

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

        }
    });
}




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

}

// TODO : remove ?
// 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));
}

// TODO : remove ?
/* 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();
//         }
//     }
// }



// TODO : remove ?
function showDatepicker(id,calendarJPG, paramDateFormat)
{	

    $(id).datepicker({
        showOn: "button",
        changeYear: true,
        changeMonth: true,
        buttonImage: calendarJPG,
        buttonImageOnly: true,
        showAnim: "fade", 
        dateFormat: paramDateFormat
    });
}


//_____________________________________________________________________________

// TODO : remove ?
function init()
{
    // 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();
    //         }
    //     };
    // })();
        
    
    
    
}

$(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 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();
        },
    });
}








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) {
            window.location = window.location.href;/* reload page without POST warning*/
            return;
        }
        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;
    },
});

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) );
})


//_____________________________________________________________________________
// 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();
		} 
	}); 
}

//______________________________________________________________________________

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
            }
        });
    });
});

//_____________________________________________________________________________
// Form Branch (prototype)

// TODO : move into InputBranch
// Boot
$(function() {
    InputBranch.initAll();

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

// TODO : only activate one listener per branch
document.addEventListener('change', (event) => {

    const branch = document.querySelector(
        '[data-form-branch-dependency="'+event.target.name+'"]'
    );

    if (! branch) return;

    InputBranch.setBranch(branch, getInputValue(event.target));
});

//_____________________________________________________________________________

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

// Cache && CacheStorage API
// https://developer.mozilla.org/fr/docs/Web/API/CacheStorage
async function deleteAllCaches() {
    // liste des caches à ne pas supprimer garder
    const cacheWhitelist = [""];
    caches.keys().then(function (keyList) {
        return Promise.all(
            keyList.map(function (key) {
                if (cacheWhitelist.indexOf(key) === -1) {
                    return caches.delete(key);
                }
            })
        );
    });
}

// Permet de gérer la gestion de déclenchement de fonction tierce,comme activeLoader();
async function createWindowCacheFetching() {
    if (!window.cacheFetching) {
        window.cacheFetching = {};
    }
}

async function getFromCache(cacheName, requestUrl) {
    createWindowCacheFetching();
    window.cacheFetching[requestUrl] = false;
    const cache = await caches.open(cacheName);

    const cachedResponse = await cache.match(requestUrl);
    if (cachedResponse) {
        return cachedResponse;
    } else {
        window.cacheFetching[requestUrl] = true;

        const freshResponse = await fetch(requestUrl);
        if (freshResponse.ok) {
            await cache.put(requestUrl, freshResponse.clone());
            window.cacheFetching[requestUrl] = false;
            return freshResponse;
        }
    }

    throw new Error("Impossible de charger : " + requestUrl);
}