jQuery(() => {

    var token = jQuery("#token").attr("name");
    let category = null;
    let markersFetch = null;
    let categories = null;
    let departements = null;
    let activites = null;

    let articleAfterActivate = null;
    var active = [];
    let group = null;
    var listeProjets = L.control();
    var geom_temp = null;

    let markersExperience = null;
    let markersSIAE = null;
    let markersDT = null;

    // INIT MAP
    var map = L.map('mapid').setView([44.032156, 1.634136], 7.5);


    L.tileLayer('https://api.mapbox.com/styles/v1/dgtnarmelle/cl6vzlpvx000f14upjewi4mfl/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        maxZoom: 20,
        minZoom: 7,
        tileSize: 512,
        zoomOffset: -1,
        accessToken: accessToken,
    }).addTo(map);

    // INIT SIDEBAR
    var sidebar = L.control.sidebar('sidebar', {
        position: 'right',
        closeButton: 'true',
        autoPan: 'false'
    });
    map.addControl(sidebar);


    //Bloque le zoom de la carte lors du scroll
    map.scrollWheelZoom.disable();
    map.on('click', () => {
        map.scrollWheelZoom.enable();
    });
    map.on('mouseout', () => {
        map.scrollWheelZoom.disable();
    });


    // FETCH DATA
    jQuery.ajax({
        data: { [token]: "1", task: "initData", format: "json", type: "categories" },
        async: false,
        success: function (result) {
            //category est un tableau contenant les 3 ids dont nous nous servons pour récupérer les projets par type
            category = result.data;

            // GET markers

            //Markers Expériences
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "markers", catId: category[0] },
                async: false,
                success: function (result) {
                    //On garde la liste de côté pour pouvoir l'afficher lors du clic sur un marker DT*/

                    markersDT = result.data;

                },
                error: function () { console.log('ajax call failed'); },
            });

            //Markers SIAE
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "markers", catId: category[1] },
                async: false,
                success: function (result) {
                    if (markersDT) {
                        markersExperience = markersDT.concat(result.data);
                    } else {
                        markersExperience = result.data;
                    }
                },
                error: function () { console.log('ajax call failed'); },
            });

            //Markers DT
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "markers", catId: category[2] },
                async: false,
                success: function (result) {
                    //On ajoute tout dans le tableau final unique que l'on appelle markersFetch par soucis de comptabilité avec l'ancien code
                    markersFetch = markersExperience.concat(result.data);
                    //Maintenant qu'on a tous nos projets on peut les ajouter a la carte
                    //onAdd: C'est la fonction d'initialisation qui est appelée lorsqu'on ajoute cet objet à la carte. 
                    //Elle permet de construire le div HTML qui contiendra la légende. Ce div est associé à la classe CSS info.
                    listeProjets.onAdd = function () {
                        addListOfArticles(markersFetch);
                        return _div;
                    }
                    listeProjets.addTo(map);

                },
                error: function () { console.log('ajax call failed'); },
            });

            // GET departements
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "departement" },
                async: false,
                success: function (result) {
                    departements = Object.values(JSON.parse(result.data.fieldparams).options);
                },
                error: function () { console.log('ajax call failed'); },
            });
            // GET categorie
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "categorie" },
                async: false,
                success: function (result) {
                    categories = Object.values(JSON.parse(result.data.fieldparams).options);
                },
                error: function () { console.log('ajax call failed'); },
            });
            // GET activite
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "activite" },
                async: false,
                success: function (result) {
                    activites = Object.values(JSON.parse(result.data.fieldparams).options);
                },
                error: function () { console.log('ajax call failed'); },
            });
        },
        error: function () { console.log('ajax call failed'); },
    });

    // ajout ou retrait dynamique de classe
    $(document).ready(() => {
        $(".departements h6").click((event) => {
            showHide(".departements img", ".departements > h6 > span.unview", ".departements > h6 > span.view");
        });
        $(".categorie h6").click((event) => {
            showHide(".categorie img", ".categorie > h6 > span.unview", ".categorie > h6 > span.view");
        });
        $(".activite h6").click((event) => {
            showHide(".activite img", ".activite > h6 > span.unview", ".activite > h6 > span.view");
        });
        $(".leaflet-control img").click((event) => {
            var current = $(event.currentTarget);
            if (current.hasClass("active") == true) {
                current.removeClass('active');
            } else {
                current.addClass('active');
            }
        });
    });
    //---EOF ajout ou retrait dynamique de classe

    $(".listeArticles").click((event) => {
        if ($(".listeProjets p").css("display") == 'none') {
            $(".listeProjets p").show();
        } else {
            $(".listeProjets p").hide();
        };
    });

    //---Affichage des panels departements / categories / activites / reset
    var departementsLists = L.control({ position: 'topleft' });
    departementsLists.onAdd = function () {
        var icons = [];
        var departement = "departement";
        iconsTheme(departements, departement, icons);
        var div = L.DomUtil.create('div', 'departements'), icons;
        div.innerHTML += '<h6><span class="view">+ </span><span class="unview" >&ndash; </span>Départements</h6>';
        for (var i = 0; i < icons.length; i++) {
            div.appendChild(icons[i]);
        }
        return div;
    };

    var categoriesLists = L.control({ position: 'topleft' });
    categoriesLists.onAdd = function () {
        var icons = [];
        var categorie = "categorie";
        iconsTheme(categories, categorie, icons);
        var div = L.DomUtil.create('div', 'categorie'), icons;
        div.innerHTML += '<h6><span class="view">+ </span><span class="unview" >&ndash; </span> Catégorie</h6>';
        for (var i = 0; i < icons.length; i++) {
            div.appendChild(icons[i]);
        }
        return div;
    };

    var activiteLists = L.control({ position: 'topleft' });
    activiteLists.onAdd = function () {
        var icons = [];
        var activite = "activite";
        iconsTheme(activites, activite, icons);
        var div = L.DomUtil.create('div', 'activite'), icons;
        div.innerHTML += '<h6><span class="view">+ </span><span class="unview" >&ndash; </span>activite</h6>';
        for (var i = 0; i < icons.length; i++) {
            div.appendChild(icons[i]);
        }
        return div;
    };

    var resetButton = L.control({ position: 'topleft' });
    resetButton.onAdd = function () {
        var div = L.DomUtil.create('div', 'reset');
        div.innerHTML += '<input class="uk-button uk-button-secondary" type="button" value="Reset" >';
        return div;
    };
    departementsLists.addTo(map);
    categoriesLists.addTo(map);
    activiteLists.addTo(map);
    resetButton.addTo(map);
    //---EOF Affichage des panels departements / categories / activites / reset

    //Stop propagation pour les drag'n'drop et les doubles clics. 
    $('.leaflet-control').mouseover(function () {
        map.dragging.disable();
        map.doubleClickZoom.disable()
        map.scrollWheelZoom.disable();
    })
    $('.leaflet-control').mouseout(function () {
        map.dragging.enable();
        map.doubleClickZoom.enable()
    })

    map.scrollWheelZoom.disable();


    function showHide(test, testunview, testview) {
        if ($(test).css("display") == 'none') {
            $(test).show();
            $(testunview).show();
            $(testview).hide();
        } else {
            $(test).hide();
            $(testunview).hide();
            $(testview).show();
        };
    }

    $(".reset").click((event) => {
        $(".leaflet-control img").removeClass('active');
        map.removeLayer(group);
        sidebar.hide();
        reg_tile_temp.clearLayers();
        initMarkersAndGroup(markersFetch);
        listeProjets.onAdd = function () {
            addListOfArticles(markersFetch);
            return _div;
        }
        map.addLayer(group);
        listeProjets.addTo(map);
        $(".listeArticles").click((event) => {
            if ($(".listeProjets p").css("display") == 'none') {
                $(".listeProjets p").show();
            } else {
                $(".listeProjets p").hide();
            };
        });
    });

    dpt_active = []
    $(".leaflet-control:not(.reset , .listeProjets)").click((event) => {
        var arrayActiveDpt = $('.departements img').hasClass('active');
        var arrayActiveCtg = $('.categorie img').hasClass('active');
        var arrayActiveAct = $('.activite img').hasClass('active');
        active = []

        var activeDepartement = document.getElementsByClassName("active");
        for (i = 0; i < activeDepartement.length; i++) {
            active.push(activeDepartement[i].id);
        };
        if (active.length == 0) {
            map.removeLayer(group);
            sidebar.hide();
            reg_tile_temp.clearLayers();
            initMarkersAndGroup(markersFetch);
            listeProjets.onAdd = function () {
                addListOfArticles(markersFetch);
                return _div;
            }
            map.addLayer(group);
            listeProjets.addTo(map);
        } else {
            reg_tile_temp.clearLayers();
            var articlesByDepartement = [];
            var articlesByCategories = [];
            var articlesByActivites = [];
            var arrayOfArticlesByDepartement = [];
            var arrayOfArticlesByCategories = [];
            var arrayOfArticlesByActivites = [];
            var departements = "departement";
            var categories = "categorie";
            var activites = "activite";

            //--- articles en fonction theme
            for (article = 0; article < markersFetch.length; article++) {
                articlesByTheme(articlesByDepartement, departements, arrayOfArticlesByDepartement);
                articlesByTheme(articlesByCategories, categories, arrayOfArticlesByCategories);
                articlesByTheme(articlesByActivites, activites, arrayOfArticlesByActivites);
            }
            //---EOF articles en fonction theme

            //--- comparaison des tableaux et logique OU au sein d'un meme catégorie et ET entre les catégories
            articleAfterActivate = [];

            if ((arrayActiveAct == false && arrayActiveCtg == false) || (arrayActiveDpt == false && arrayActiveAct == false) || (arrayActiveDpt == false && arrayActiveCtg == false)) {
                articleAfterActivate = arrayOfArticlesByDepartement.concat(arrayOfArticlesByCategories).concat(arrayOfArticlesByActivites);
            }
            // ABD for articleByDepartement - ABC for articleByaCategories - ABA for articleByActivites                
            if (arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByCategories.length != 0) {
                for (let ABD in arrayOfArticlesByDepartement) {
                    for (let ABC in arrayOfArticlesByCategories) {
                        if (arrayOfArticlesByDepartement[ABD].id == arrayOfArticlesByCategories[ABC].id) {
                            articleAfterActivate.push(arrayOfArticlesByDepartement[ABD]);
                        }
                    }
                }
            }
            if (arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByActivites.length != 0) {
                for (let ABD in arrayOfArticlesByDepartement) {
                    for (let ABA in arrayOfArticlesByActivites) {
                        if (arrayOfArticlesByDepartement[ABD].id == arrayOfArticlesByActivites[ABA].id) {
                            articleAfterActivate.push(arrayOfArticlesByDepartement[ABD]);
                        }
                    }
                }
            }
            if (arrayOfArticlesByActivites.length != 0 && arrayOfArticlesByCategories.length != 0) {
                for (let ABA in arrayOfArticlesByActivites) {
                    for (let ABC in arrayOfArticlesByCategories) {
                        if (arrayOfArticlesByActivites[ABA].id == arrayOfArticlesByCategories[ABC].id) {
                            articleAfterActivate.push(arrayOfArticlesByActivites[ABA]);
                        }
                    }
                }
            }
            if ((arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByActivites.length != 0 && arrayActiveCtg == true && arrayOfArticlesByCategories.length == 0) || (arrayOfArticlesByDepartement.length == 0 && arrayActiveDpt == true && arrayOfArticlesByActivites.length != 0 && arrayOfArticlesByCategories.length != 0) || (arrayOfArticlesByDepartement.length != 0 && arrayActiveAct == true && arrayOfArticlesByActivites.length == 0 && arrayOfArticlesByCategories.length != 0)) {
                articleAfterActivate = [];
            }
            if (arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByActivites.length != 0 && arrayOfArticlesByCategories.length != 0) {
                var temporaryArticle = [];
                function ObjCompare(obj1, obj2, obj3) {
                    if (obj1.id === obj2.id && obj2.id === obj3.id && obj1.id === obj3.id) {
                        return true;
                    };
                }
                for (let ABD in arrayOfArticlesByDepartement) {
                    for (let ABA in arrayOfArticlesByActivites) {
                        for (let ABC in arrayOfArticlesByCategories) {
                            if (ObjCompare(arrayOfArticlesByDepartement[ABD], arrayOfArticlesByActivites[ABA], arrayOfArticlesByCategories[ABC]) == true) {
                                temporaryArticle.push(arrayOfArticlesByDepartement[ABD]);
                            }
                        }
                    }
                }
                articleAfterActivate = temporaryArticle;
            }
            //---EOF comparaison des tableaux et logique OU au sein d'un meme catégorie et ET entre les catégories       

            //---Markers et clusters articles actif
            if (articleAfterActivate != markersFetch || articleAfterActivate.length != 0) {
                map.removeLayer(group);
                sidebar.hide();
                initMarkersAndGroup(articleAfterActivate);
                map.addLayer(group);
            }
            if (articleAfterActivate.length == 0) {
                map.removeLayer(group);
                sidebar.hide();
                initMarkersAndGroup(articleAfterActivate);
                map.addLayer(group);
            }
            //---EOF Markers et clusters articles actif

            //---Affichage liste des projets dynamiquee
            if (Object.keys(listeProjets).length > 2) {
                listeProjets.remove(map);
                if (articleAfterActivate.length == 0 && (arrayActiveCtg == true || arrayActiveDpt == true || arrayActiveAct == true)) {
                    listeProjets.onAdd = function () {
                        addListOfArticles(articleAfterActivate);
                        return _div;
                    }
                }
                else if (articleAfterActivate.length == 0) {
                    listeProjets.onAdd = function () {
                        addListOfArticles(markersFetch);
                        return _div;
                    }
                } else {
                    listeProjets.onAdd = function () {
                        addListOfArticles(articleAfterActivate);
                        return _div;
                    }
                }
                listeProjets.addTo(map);
            }
            //--- EOF Affichage liste des projets dynamique
        };

        $(".listeArticles").click(() => {
            if ($(".listeProjets p").css("display") == "none") {
                $(".listeProjets p").show();
            } else {
                $(".listeProjets p").hide();
            };
        });

        $(".close").click(() => {
            displayListOfArticles();
        });

    });

    //création d'une couche temporaire pour WKT et permettre le retrait de la zone seule
    reg_tile_temp = new L.layerGroup().addTo(map);

    //---Markers and Cluster
    const enedisMarkerIcon = L.icon({
        iconSize: [25, 41],
        iconAnchor: [10, 41],
        popupAnchor: [2, -40],
        iconUrl: '/components/com_leaflet/assets/css/images/marqueur-enedis.png',
        shadowUrl: '/components/com_leaflet/assets/css/images/marker-shadow.png'
    });

    const cooraceMarkerIcon = L.icon({
        iconSize: [25, 41],
        iconAnchor: [10, 41],
        popupAnchor: [2, -40],
        iconUrl: '/components/com_leaflet/assets/css/images/marqueur-coorace.png',
        shadowUrl: '/components/com_leaflet/assets/css/images/marker-shadow.png'
    });

    const expMarkerIcon = L.icon({
        iconSize: [25, 41],
        iconAnchor: [10, 41],
        popupAnchor: [2, -40],
        iconUrl: '/components/com_leaflet/assets/css/images/marqueur-commun.png',
        shadowUrl: '/components/com_leaflet/assets/css/images/marker-shadow.png'
    });

    var LeafIcon = L.Icon.extend({
        options: {
            shadowUrl: '/components/com_leaflet/assets/css/images/marker-shadow.png',
            iconSize: [25, 41],
            iconAnchor: [10, 41],
            popupAnchor: [2, -40]
        }
    });
    var selectedIcon = new LeafIcon({ iconUrl: '/components/com_leaflet/assets/css/images/marqueur-selected.png' });


    initMarkersAndGroup(markersFetch);
    map.addLayer(group);
    //---EOF Markers and Cluster

    /* A remettre et retravailler pour images filtres departements */
    function iconsTheme(dataOfTheme, nameOfTheme, icons) {
        dataOfTheme.forEach((theme) => {
            var img = document.createElement("IMG");
            img.setAttribute("src", `${window.location.origin}/images/cartographie/${nameOfTheme}/${theme.value}.png`);
            img.setAttribute("width", "60px");
            img.setAttribute("height", "60px");
            img.setAttribute("style", "margin-right: 10px;margin-top: 10px;");
            img.setAttribute("id", theme.value);
            img.setAttribute("title", theme.name);
            icons.push(img);
        })
    }

    function addListOfArticles(article) {
        _div = L.DomUtil.create('div', 'listeProjets'), article;
        _div.innerHTML = `<div class=listeArticles><h3><span uk-icon="menu"></span> Liste (<span class="nombreProjetsAffiches">` + article.length + `</span>)</h3></div>`;
        for (var i = 0; i < article.length; i++) {
            if(article[i].catid == 18){
            _div.innerHTML += `<p style="display: none;"><a href="${window.location.origin}/actions-partenariales/${article[i].alias}" target="_blank">` + article[i].title + `</a></p>`;
            }else if (article[i].catid == 19){
                _div.innerHTML += `<p style="display: none;"><a href="${window.location.origin}/fiche-savoir-faire/${article[i].alias}" target="_blank">` + article[i].title + `</a></p>`;
            }else if (article[i].catid == 20){
                _div.innerHTML += `<p style="display: none;"><a href="${window.location.origin}/fiche-appel-a-projet/${article[i].alias}" target="_blank">` + article[i].title + `</a></p>`;s
            }
        }
    }

    function articlesByTheme(articlesBy, nameOfTheme, arrayOfArticleBy) {
        if (markersFetch[article][nameOfTheme] != null) {
            articlesBy.push(markersFetch[article]);
            for (let article in articlesBy) {
                for (let a in active) {
                    for (let test in articlesBy[article][nameOfTheme]) {
                        if (articlesBy[article][nameOfTheme][test] == (active[a])) {
                            if (arrayOfArticleBy.includes(articlesBy[article]) == false) {
                                arrayOfArticleBy.push(articlesBy[article]);
                            }
                        }
                    }
                }
            }
        }
    }
    function displayListOfArticlesOnSidebarClosed() {
        $(".close").click(() => {
            displayListOfArticles();
        });

    }

    function displayListOfArticles() {
        $(".listeProjets p").hide();
        $(".listeProjets").show();
    }

    //Fonction qui vérifie si l'état du champs contenant la chaîne WKT de la zone d'intérêt des projets. 
    function checkInterestZone(zone) {
        if (zone == null) {
            return false;
        } else {
            return true;
        }
    }

    //Détecte les niveaux de zoom et gère le comportement du marker sélectionné selon le niveau
    var zoomInZone = document.getElementsByClassName('leaflet-control-zoom-in');
    var zoomOutZone = document.getElementsByClassName('leaflet-control-zoom-out');
    for (i = 0; i < zoomInZone.length; i++) {
        zoomInZone[i].addEventListener('click', function () {
            if (map.getZoom() < 9) {
                reg_tile_temp.clearLayers();
                sidebar.hide();
                displayListOfArticles();
            }
        })
    }
    for (i = 0; i < zoomOutZone.length; i++) {
        zoomOutZone[i].addEventListener('click', function () {
            if (map.getZoom() < 9) {
                reg_tile_temp.clearLayers();
                sidebar.hide();
                displayListOfArticles();
            }
        })
    }
    //EOF Fonction gestion sélection zoom

    function getDepartementName(departementValue) {

        if (departementValue == "ariege") {
            return "Ariège";
        } else if (departementValue == "aude") {
            return "Aude";
        } else if (departementValue == "aveyron") {
            return "Aveyron";
        } else if (departementValue == "gard") {
            return "Gard";
        } else if (departementValue == "haute-garonne") {
            return "Haute-Garonne";
        } else if (departementValue == "gers") {
            return "Gers";
        } else if (departementValue == "herault") {
            return "Hérault";
        } else if (departementValue == "lot") {
            return "Lot";
        } else if (departementValue == "lozere") {
            return "Lozere";
        } else if (departementValue == "pyrenees-orientales") {
            return "Pyrenees-Orientales";
        } else if (departementValue == "tarn") {
            return "Tarn";
        } else if (departementValue == "tarn-garonne") {
            return "Tarn et Garonne";
        }
    }

    function initMarkersAndGroup(items) {
        group = new L.markerClusterGroup({ showCoverageOnHover: false, zoomToBoundsOnClick: true, spiderfyOnMaxZoom: false, disableClusteringAtZoom: 8 });

        for (let article = 0; article < items.length; article++) {
            var articleMarker = items[article].localisation;
            // mise au format des coordonnées pour affichage avec L.marker
            var coordArticleMarker = articleMarker.split(',');
            let lat = coordArticleMarker[0];
            let long = coordArticleMarker[1];
            let title = items[article].title;

            var _mar;
            var idOfCategory = items[article].catid;
            if (idOfCategory == 18) {
                _mar = L.marker(new L.LatLng(lat, long), {
                    icon: expMarkerIcon
                });
            } else if (idOfCategory == 19) {
                _mar = L.marker(new L.LatLng(lat, long), {
                    icon: cooraceMarkerIcon
                });
            } else if (idOfCategory == 20) {
                _mar = L.marker(new L.LatLng(lat, long), {
                    icon: enedisMarkerIcon
                });
            }

            _mar.bindPopup(title);
            _mar.on('click', function clicMarker() {
                reg_tile_temp.clearLayers();
                $(".listeProjets").hide();
                const _marActive = L.marker(new L.LatLng(lat, long), {
                    icon: selectedIcon
                });

                //Récupérer les coordonnées du point, stocker dans une variable (appelée dans la sidebar.setContent plus bas)                    
                sidebar.show();

                //Vérifier si marqueur est de type DT ou autres
                //On se base sur nomdelasiae car le champ n'est pas présent sur les projets DT mais est présent sur les autres
                if (items[article].catid == 20) {
                    dpt = getDepartementName(items[article].departement);
                    content = `<div class="listeProjetsDT">
                            <div class=listeArticles>
                            <h3 class="uk-heading-small uk-margin-top">
                            <span uk-icon="icon: menu; ratio: 2" class="uk-icon"></span> Liste des Appels à projet du département : `+ dpt +
                        `</h3>
                            </div>`;
                    for (var i = 0; i < markersDT.length; i++) {
                        if (markersDT[i].departement == items[article].departement) {
                            content += `<p>
                                    <a href="${window.location.origin}/fiche-appel-a-projet/${markersDT[i].alias}" target="_blank">` + markersDT[i].title + `</a>
                                    </p>`;
                        }
                    }
                    content += `</div>`;
                } else if (items[article].catid == 18) {
                    content = `<h3 class="uk-heading-small uk-margin-top">${title}</h3> <br/>
                    <div class="uk-text-lead uk-margin-bottom">${items[article].introtext} </div>
                    <a class="uk-button uk-button-primary" href="${window.location.origin}/actions-partenariales/${items[article].alias}" target="_blank"><span uk-icon="table"></span>Voir l'article complet</a>`;

                } else if (items[article].catid == 19) {
                    actName = getActiviteName(items[article].activite);
                    content = `<h3 class="uk-heading-small uk-margin-top">${title}</h3> <br/>
                            <div class="uk-text-lead uk-margin-bottom">Domaine d'activité : <ul>`;
                    for (var i = 0; i < actName.length; i++) {
                        content += `<li>` + actName[i] + `</li>`;
                    }
                    content += `</ul><br/>Adresse : ${items[article].adresse}</div>`;
                    if (items[article].zonedintervention != null) {
                        content += `<div class="uk-text-lead uk-margin-bottom">Zone d'intervention : ${items[article].zonedintervention}</div>`;
                    }
                    content += `<a class="uk-button uk-button-primary" href="${window.location.origin}/fiche-savoir-faire/${items[article].alias}" target="_blank"><span uk-icon="table"></span>Voir l'article complet</a>`;
                }
                sidebar.setContent(content);
                sidebar.on('close', displayListOfArticlesOnSidebarClosed());

                //Remet reg_tile_temp à 0 avant d'y intégrer geom_temp si le champs contenant le WKT de la zone d'intérêt est complété 
                reg_tile_temp.clearLayers();
                var zoneDefined = checkInterestZone(items[article].jce);
                if (zoneDefined) {
                    geom_temp = omnivore.wkt(items[article].jce);
                    geom_temp.addTo(reg_tile_temp);
                }
                _marActive.addTo(reg_tile_temp);

            });
            if (map.getZoom() > 15 && map.hasLayer(_mar)) {
                map.closePopup();
            }

            group.addLayer(_mar);
        }
    }

    function getActiviteName(act) {
        actList = activites;
        var actOfArticle = [];
        for (var i = 0; i < actList.length; i++) {
            for (var j = 0; j < act.length; j++) {
                if (actList[i].value == act[j]) {
                    actOfArticle.push(actList[i].name);
                }
            }
        }
        return actOfArticle;
    }
});
