/*

const mosaiqueContainer=document.getElementById("mosaique-container")

var viewingMode=body.getAttribute("data-viewing-mode")

const searchField=document.querySelector("[name='item-search']")

*/
var body = document.body
const mainContainer=document.getElementById("main-grid")
const viewerInner=document.getElementById("viewer-inner")
var yc_timer
var yc_toolbar_viewstate=true
let viewertools= {
    toolbar_viewstate: true,
    y: 0,
    timer: null
}

const viewerMain=document.getElementById("viewer-main")
let sortable=null

let settings= {
    listingtype:body.getAttribute("data-listingtype"), // ms,liste
    tri: body.getAttribute("data-tri"),
    selectmode: "single", // single|multi
    viewertype: body.getAttribute("data-viewertype"), // lateral|fullscreen|
    viewershow: "hide", // hide|show
    viewerwarning: false,
    viewershowinfo: true,
    viewerloop: body.getAttribute("data-viewerloop"), // outer|inner|both
    forcedview: false,
    formopen: false,
}

const searchField=document.getElementById("live-search")
searchField.addEventListener('keyup', function(e) {
    if(e.keyCode == '27') {
        searchField.value=""
    }
    yc_search_items()
})

yc_init_load_vignettes()
yc_init_tri()
yc_init_mosaique_listing()
yc_init_infos()
yc_init_keys()

yc_count_items()

// faire le focus sur le champ de recherche 
const searchfield=document.querySelector("[data-toggle-button='rechercher']")
if(searchField){
    searchfield.addEventListener("click",function(){
        window.setTimeout(function() {
            document.getElementById("live-search").focus();
        }, 0)


    })
}

/*
Fonction de sous-routine utilisées
*/

function yc_clicItem(elem){
    // attention, un formulaire est peut-être ouvert
    if(settings.viewerwarning != false && settings.selectmode=="single"){
        if(promptIt("Attention\nUn formulaire est affiché. Êtes-vous sûr de vouloir le fermer ?") == false){
            return
        }
    }
    switch(settings.selectmode){
        case "single":
            yc_disableforcedview()
            yc_showItem(elem)
            break;
        case "multi":
            elem.classList.toggle("selected")
            break;
        case "drag":
            // do nothing
            break;
        case "collection":
            elem.classList.toggle("selected")
            yc_collectionmanageitem(elem)
            break;
    }
}

function yc_deselect_allitems(){
    mainContainer.querySelectorAll(".actuel, .selected")
        .forEach(function(e){
        e.classList.remove("actuel", "selected")
    }) 
}
function yc_settingSync(set, val){
    settings.set=val
    body.setAttribute(data+"set",value)
}
function yc_forceView(wich){
    settings.forcedview=true;
    body.setAttribute("data-viewertype",wich)
}
function yc_disableforcedview(){
    settings.forcedview=false
    body.setAttribute("data-viewertype",settings.viewertype)
}
function yc_openViewer(){
    body.setAttribute("data-viewershow","show")
    settings.viewershow="show"
    viewerInner.setAttribute("data-toolbar","show")
}
function yc_closeViewer(){
    switch (settings.viewerwarning){
        case "savebeforeclose":
            if(promptIt("Attention\nVous avez apporté des mofifications à ce formulaire! Voulez-vous fermer la fenêtre et perdre les modifications?") == true){
            } else {
                return
            }
            break;
        case "warning":
            if(promptIt("Fermer la fenêtre (et perdre les modifications) ?") == false){
                return
            }
            break;
    }
    body.setAttribute("data-viewershow","hide")
    yc_exitMultimode() // fermer le multimode si ouvert
    if(mainContainer.classList.contains("draggingitems")){
        destroy_orderItems()
    }
    yc_deselect_allitems() // retirer les classes
    settings.viewerwarning=false // retirer la sécurité
    settings.formopen=false // libérer
    yc_closeFullscreen() // quitter le mode fullscreen si nécessaire
    // retirer le forçage lateral
    yc_disableforcedview()
    yc_stop_multimedia()

}

function yc_viewerTypechange(viewtype,type,source){
    body.setAttribute("data-viewertype",viewtype)
    settings.viewertype=viewtype
    // recharger avec le bon snippet
    if(type="item"){
        let elem=mainContainer.querySelector(".actuel")
        elem.click()
    }
}

function yc_initMultimode(){
    settings.selectmode="multiple"
}
function yc_exitMultimode(){
    mainContainer.querySelectorAll("selected")
        .forEach(function(el){
        el.classList.remove("selected")
    })
    settings.selectmode="single"
}

function yc_itemPrev(){
    let ai=mainContainer.querySelector(".actuel")
    if(mainContainer.getAttribute("data-filtercollection")){
        let order=parseInt(mainContainer.querySelector(".actuel").style.order)
        order--
        ai=mainContainer.querySelector(".item[style='order: "+order+";']")
    } else {
        ai=ai.previousElementSibling
    }
    
    if(ai){ 
        while (ai!==null) {
            let itt=ai.getAttribute("data-filter") // tags
            let its=ai.getAttribute("data-search") // live search
            let itc=ai.getAttribute("data-collection") // collection
            let show=true
            if(itt && itt=='hide'){
                show=false
            }
            if(its && its=='hide'){
                show=false
            }
            if(itc && itc=='hide'){
                show=false
            }
            if(show==false) {
                ai = ai.previousElementSibling;
            } else {
                yc_clicItem(ai)
                //yc_showItem(ai)
                return true
            }
        }
    }
    console.log("debut")
    return false
    // éventuellement aller au dernier
}

function yc_itemNext(){
    let ai=mainContainer.querySelector(".actuel")
    if(mainContainer.getAttribute("data-filtercollection")){
        let order=parseInt(mainContainer.querySelector(".actuel").style.order)
        order++
        ai=mainContainer.querySelector(".item[style='order: "+order+";']")
    } else {
        ai=ai.nextElementSibling
    }

    if(ai){ 
        while (ai!==null) {
            let itt=ai.getAttribute("data-filter") // tags
            let its=ai.getAttribute("data-search") // live search
            let itc=ai.getAttribute("data-collection") // collection
            let show=true
            if(itt && itt=='hide'){
                show=false
            }
            if(its && its=='hide'){
                show=false
            }
            if(itc && itc=='hide'){
                show=false
            }
            if(show==false) {
                ai = ai.nextElementSibling;
            } else {

                if(itc){ // collection utilise order

                }

                yc_clicItem(ai)
                return true
            }
        }
    }
    console.log("fin")
    return false



    // éventuellement aller au premier
}
function promptIt(text){
    if (confirm(text) == true) {
        return true
    } else {
        return false
    }
}
/*

Core functions  pour les chargements ajax

"source" est le fichier .yaml demandé (page, item, collection)
"type" est le type de fichier (page|item|collection|config|admin) items?
"destination" est le html dans lequel verser
"url" url ajax eventuelle (app/async/async_start.php si pas spécifié)
"action" est le type d'action: gethtml|loadform|submitform
"callback" action en fin de traitement
"endaction" pour l'action en toute fin de traitement
"snippet" (item only) est le type de viewer pour le code de gethtml 


*/
function yc_showItem(elem){ 
    // tagguer l'item
    yc_deselect_allitems()
    elem.classList.add("actuel")
    var file=elem.getAttribute("data-source")
    var args=new FormData()
    args.append("source", file)
    args.append("type", "item")
    args.append("action", "gethtml")
    args.append("callback","yc_filldestination")
    args.append("snippet", settings.viewertype)
    args.append("endaction","yc_openViewer yc_inititemscript")
    yc_loadFile(args)
}
function yc_deleteElem(file, filetype){
    if(!promptIt("Êtes-vous sûr de vouloir supprimer cet element?")){ return false }

    var args=new FormData();
    args.append("source", file)
    args.append("type", filetype)
    if(filetype=="item"){
        args.append("callback","yc_deleteGriditems")
    }
    if(filetype=="page"){
        args.append('destination', '#menu-pages')
        args.append('callback', 'yc_filldestination')
    }
    if(filetype=="collection"){
        args.append('destination', '#collections-container')
        args.append('callback', 'yc_filldestination')
    } 
    args.append("action", "deleteelem")
    args.append("endaction", "yc_closeViewer")
    yc_loadFile(args)    

}
function yc_showPage(file){
    var args=new FormData()
    args.append("source", file)
    args.append("type", "page")
    args.append("action", "gethtml")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")    
    yc_loadFile(args)
}
function yc_loadModulecontent(file, action){
    var args=new FormData()
    args.append("source", file)
    args.append("type", "module")
    args.append("action", action)
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")    
    yc_loadFile(args)
}
function yc_emptyCache(lequel){
    if(!promptIt("Êtes-vous sûr de vouloir vider le cache?")){ return false }
    var args=new FormData()
    args.append("type", "admin")
    args.append("action", "vidercache"+lequel)
    args.append("callback","yc_reloadpage")
    yc_loadFile(args)

}
function yc_logout(){
    var args=new FormData()
    args.append("type", "admin")
    args.append("action", "logout")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    yc_loadFile(args)
    body.setAttribute("data-adminstatus","false")
}
function yc_editItem(file){
    if(!yc_isadmin()){ return false } // check admin minimal
    var args=new FormData();
    args.append("source", file)
    args.append("type", "item")
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("snippet", settings.viewertype)
    args.append("endaction","yc_openViewer")    
    yc_loadFile(args)
}
function yc_editPage(file){
    var args=new FormData();
    args.append("source", file)
    args.append("type", "page")
    args.append("action", "loadform")  
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")    
    yc_loadFile(args)
}
function yc_editCollection(e,file){
    e.stopPropagation()
    yc_collectionclose()
    var args=new FormData();
    args.append("source", file)
    args.append("type", "collection")
    args.append("action", "loadform")  
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer yc_initeditcollection")
    yc_forceView("lateral")
    settings.selectmode="collection"
    yc_loadFile(args)

}
function yc_editTheme(){
    var args=new FormData();
    args.append("type", "theme")
    args.append("action", "loadform")  
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer yc_init_theme_options")
    yc_forceView("lateral")
    yc_loadFile(args)
}

function yc_loadform(wichtype){
    var args=new FormData()
    args.append("type", wichtype)
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    yc_forceView("lateral")
    yc_loadFile(args) 
}

/* ITEMS */
function yc_modifyitems(){
    var args=new FormData()
    args.append("type", "items_modify")
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    yc_forceView("lateral")
    settings.selectmode="multi"
    yc_loadFile(args)
}
function yc_deleteitems(){
    var args=new FormData()
    args.append("type", "items_delete")
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    yc_forceView("lateral")
    settings.selectmode="multi"
    yc_loadFile(args)
}
function yc_orderItems(){
    var args=new FormData()
    args.append("type", "items_order")
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    settings.selectmode="drag"
    init_orderItems()
    yc_loadFile(args)
}
function yc_exportItems(){
    var args=new FormData()
    args.append("type", "items_export")
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    yc_forceView("lateral")
    settings.selectmode="multi"
    yc_loadFile(args)
}

function yc_showCollection(elem,idcol){
    var args=new FormData()
    args.append("type", "collection")
    args.append("action", "loadcollection")
    args.append("callback","yc_displaycollection")
    args.append("source",idcol)
    //args.append("endaction","yc_openViewer")
    yc_loadFile(args)
    yc_displaycollectionbutton(args.get("source"))

}

function yc_imageedit(file,item){
    var args=new FormData()
    args.append("type", "image")
    args.append("action", "loadform")
    args.append("callback","yc_filldestination")
    args.append("source",file)
    args.append("item",item)
    args.append("endaction","yc_initimage")
    args.append("viewershow", "show")
    yc_forceView("fullwindow")
    yc_loadFile(args)
}

/*  MODULES  */
function yc_adminModules(){
    var args=new FormData()
    args.append("type", "module")
    args.append("action", "modules_list")
    args.append("callback","yc_filldestination")
    args.append("endaction","yc_openViewer")
    yc_loadFile(args)
}

function yc_initForm(){
    // init form for page, item, collection, settings
    let form=document.querySelector("#yc-form:not(.initialised)")
    if(!form){ 
        settings.formopen=false
        settings.viewerwarning=false
        return false 

    }
    form.classList.add("initialised")
    settings.formopen=true
    yc_init_uploadform()
    form.addEventListener('submit', (event) => {
        yc_submitForm()
        // stop form submission
        event.preventDefault()
    })
    // editeur pour les champs textarea
    let editors=document.querySelectorAll("[data-editor]").forEach(function(el){
        var ed=el.querySelector(".quill_editor")
        var te=el.querySelector("textarea")
        te.classList.add("d-none")


        var quill = new Quill(ed, {
            theme: 'snow'
        })
        })

    // dechecker les radio et checkbox des form multiples
    if(settings.selectmode=="multi"){
        document.querySelectorAll("#yc-form input[type='radio'], #yc-form input[type='checkbox']").forEach(function(el){
            el.checked = false
        })
    }

    settings.viewerwarning="savebeforeclose"
    settings.formopen=true
}

function yc_submitForm(){
    let form=document.querySelector("#yc-form")
    if(form==null){
        alert("formulaire absent")
        return false;
    }

    // quill editors: updater le input
    let editors=document.querySelectorAll("[data-editor]").forEach(function(el){
        var ed=el.querySelector(".quill_editor .ql-editor")
        var te=el.querySelector("textarea")

        te.value = ed.innerHTML
    })

    // contrôler les champs obligatoires
    /*
    var emptyrequired=0
    form.querySelectorAll("[data-required='true']").forEach(function(el){
        // input text, textarea, file, checkbox, select
        // chercher le premier element qui a un attribut "name"
        checkel=el.querySelector("[name]")
        alert("contenu est -"+checkel.value+"-")

    })
    if(emptyrequired > 0){
        alert("Veuillez compléter les champs obligatoires")
        return false
    }
*/
    settings.viewerwarning=false

    let formData = new FormData(form)

    if(formData.get("type")=="items_order"){
        var els=mainContainer.querySelectorAll("article")
        els.forEach(function(el){
            formData.append('sources[]', el.getAttribute("data-source"))
        })
    }
    if(settings.selectmode=="multi"){
        yc_forceView("lateral")
        var els=mainContainer.querySelectorAll(".selected")
        if(els.length == 0){
            alert("Cliquez au moins un élément")
            return false
        }
        els.forEach(function(el){
            formData.append('sources[]', el.getAttribute("data-source"))
        })
    }  
    if(settings.selectmode=="collection"){
        var els=mainContainer.querySelectorAll(".selected")
        if(els.length == 0){
            alert("Cliquez au moins un élément")
            return false
        }
    }

    //console.log(formData)

    yc_loadFile(formData)
}


/*
machinerie centrale
    args
    "type"
    détermine le fichier async chargé et le type d'item
    important pour page, item et selection

    "action"
    "gethtml", "submitform"
    important car indique le type d'action au fichier async

    "callback"
    que faire du retour
    "filldestination" envoie dans la destination
    "updateitems" pour updater la mosaique suivant le json de retour
    "deleteitems" pour supprimer des éléments de mosaique

    "destination"
    important si le callback est "filldestination"

    "endaction"
    détermine quoi faire après avoir géré le retour
    "reloadhtml" pourcharger la version statique item,page, etc

    "viewershow"
    que faire du viewer: "open" / "close"

*/

function yc_loadFile(args){
    let http = new XMLHttpRequest()
    if(!args.get("url")){ args.append('url', 'app/async/async_start.php') }

    // Destination: si on en reçoit pas, ça peut être une action silencieuse
    if(!args.get("destination")){ 
        args.append("destination", "#viewer-inner") 
    }

    let destination=document.querySelector(args.get("destination"))
    destination.classList.add("wait")

    http.open("POST", args.get("url"), true)

    http.send(args);

    http.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

            // les formulaires arrivent avec des infos manquantes, les rajouter
            if(args.get('callback')){
                var reponse=this.responseText

                var actions=args.get("callback").split(' ')
                actions.forEach(function(el){
                    console.log("callback is "+el)
                    window[el](reponse, destination);
                })
            }
            if(args.get('endaction')){
                var actions=args.get("endaction").split(' ')
                actions.forEach(function(el){
                    console.log("appel de endaction "+el)
                    window[el]();
                })
            }
        }
    }

    http.onloadend = function(){
        destination.classList.remove("wait")
    }

}

/*

FONCTIONS DE CALLBACK

*/
function yc_filldestination(response, destination){
    console.log("Filldestination called")
    //alert(response)
    destination.innerHTML = response
    //init_fwgalerie()
    yc_initForm()
} 


function yc_updategriditems(response, destination){
    const retour = JSON.parse(response)
    for (let x in retour) {
        let id=retour[x].id
        let itemtoupgrade=mainContainer.querySelector("[data-source='"+id+"']")
        if(itemtoupgrade){
            //update
            itemtoupgrade.outerHTML=retour[x].html
        } else {
            // nouvel item
            mainContainer.innerHTML +=retour[x].html
        }
    }
    yc_load_vignettes()
}

function yc_deleteGriditems(response, destination){
    const r = JSON.parse(response)
    for (let x in r) {
        let id=r[x].id
        let itemtodelete=mainContainer.querySelector("[data-source='"+id+"']")
        if(itemtodelete){
            //update
            itemtodelete.remove()
        } 
    }
}

function yc_displaycollection(response, destination){
    // afficher la collection
    // apparition/disparition des items et réordonnation
    mainContainer.setAttribute("data-filtercollection","true") 
    const rc = JSON.parse(response)

    let itemslist=mainContainer.querySelectorAll(".item")
    itemslist.forEach(function(it){
        it.setAttribute("data-collection","hide")
    })

    let compteur=1
    for (let x in rc) {
        let id=rc[x].id
        let itemtoshow=mainContainer.querySelector("[data-source='"+id+"']")
        itemtoshow.setAttribute("data-collection","show")
        //itemtoshow.classList.add("filtered")
        itemtoshow.style.order=compteur
        compteur++
    }
}


/* 

FONCTIONS DE ENDACTION

*/

function yc_reloadadmin(){
    console.log("Appel de reloadadmin")

    if( body.querySelector("[data-adminaccess='true']")){
        body.setAttribute("data-adminstatus","true")
    }
    yc_loadform('admin') 
}
function yc_reloadpage(){
    console.log("Appel de reloadpage")
    location.reload()
}
function yc_inititemscript(){
    console.log("Appel de inititemscript")
    yc_initviewer()
}
function yc_destroyOrderitems(){
    mainContainer.classList.remove("draggingitems")
    sortable.destroy()
}
function yc_initeditcollection(){
    console.log("appel de init edit collection")
    // détecter les images présentes dans la collection
    var ic=document.querySelectorAll("#items-container .collectionitem")
    ic.forEach(function(el){
        var source=el.getAttribute("data-source")
        mainContainer.querySelector("[data-source='"+source+"']").classList.add("selected")
    })
    sortable = new Sortable(document.getElementById("items-container"), {
        animation: 150,
        ghostClass: 'blue-background-class'
    })
}
/*

fonctions secondaires: cache item et vignette, etc

*/
/* 

tools ! 

*/
function yc_tooltab(elem){
    let tabname=elem.getAttribute("data-toggle-button")
    if(elem.classList.contains('show')){
        elem.classList.remove('show')
        yc_closeAllTools()
        return
    }
    yc_closeAllTools()
    elem.classList.add("show")
    let dest=document.querySelector("[data-toggle-content='"+tabname+"']")
    dest.classList.toggle("show")
    const inf=dest.querySelector("input")
    if(inf) { inf.focus() }
}

function yc_closeAllTools(){
    let tabs=document.querySelectorAll("[data-toggle-content],[data-toggle-button]")
    tabs.forEach(function(elem){
        elem.classList.remove("show")
    })
}

function yc_init_filter(){
    document.querySelectorAll("[data-toggle-content='filtrer'] input").forEach(function(el){
        el.addEventListener("click",function(){
            yc_filtre_items()
        })
    })


    /*
    var filtres=document.querySelectorAll("[data-filtre]")
    filtres.forEach(function(el){
        var cle=el.getAttribute("data-filtre")
        alert(cle)
    })
    */
}

// reset pour les bouton radio

function yc_filter_select(elem){
    let check=elem.getAttribute("data-check")
    let value=elem.getAttribute("data-value")
    let cle=elem.getAttribute("data-key")

    let groupe=document.querySelector("#filter-selectors [data-filter-key='"+cle+"']")

    if(check=="false"){
        elem.setAttribute("data-check","true")
        const clone = elem.cloneNode(true);
        document.getElementById("filter-container").prepend(clone);
        yc_activate_group(groupe)
    } else {
        document.querySelector("#filter-container [data-value='"+value+"'][data-key='"+cle+"']").remove()
        document.querySelector("#filter-selectors [data-value='"+value+"'][data-key='"+cle+"']").setAttribute("data-check","false")
        // si le groupe est vide de sélection, le désactiver
        if(document.querySelectorAll(".filter-body [data-key='"+cle+"'][data-check='true']").length==0){
            yc_desactivate_group(groupe)
        }
    }
    yc_filter_items()
}

function yc_filter_activategroup(groupe){
    let cle=groupe.getAttribute("data-filter-key")
    let active=groupe.getAttribute("data-active")
    if(active =="false"){
        yc_activate_group(groupe)
    } else {
        yc_desactivate_group(groupe)
    }
}

function yc_activate_group(groupe){
    groupe.setAttribute("data-active","true")
    let cle= groupe.getAttribute("data-filter-key")
    document.querySelectorAll("#filter-container [data-key='"+cle+"']").forEach((elem) => {
        elem.setAttribute("data-check","true")
    })
    yc_filter_items()
}

function yc_desactivate_group(groupe){
    groupe.setAttribute("data-active","false")
    let cle= groupe.getAttribute("data-filter-key")
    document.querySelectorAll("#filter-container [data-key='"+cle+"']").forEach((elem) => {
        elem.setAttribute("data-check","idle")
    })
    yc_filter_items()
}

function yc_filter_removeall(){
    document.querySelectorAll("#filter-container [data-key]").forEach((elem) => {
        let cle=elem.getAttribute("data-key")
        let value=elem.getAttribute("data-value")
        document.querySelector("#filter-container [data-value='"+value+"'][data-key='"+cle+"']").remove()
        document.querySelector("#filter-selectors [data-value='"+value+"'][data-key='"+cle+"']").setAttribute("data-check","false")
    })
    // désactiver les groupes
    document.querySelectorAll("#filter-selectors .filter-header").forEach((groupe) => {
        yc_desactivate_group(groupe)
    })
    // montrer tous les items
    mainContainer.querySelectorAll(".item").forEach(function(ele){
        ele.setAttribute("data-filtre","show")
    })
}

function yc_filter_items(){
    groupes=document.querySelectorAll("#filter-selectors .filter-header[data-active='true']")
    // si pas de groupes actifs, ne rien faire
    if(groupes.length < 1){
        mainContainer.querySelectorAll(".item").forEach(function(ele){
            ele.removeAttribute("data-filter")
        })
        mainContainer.removeAttribute("data-filtertags")
        return false
    }
    // Passer les groupes en revue, crééer la liste des items qui correspondent (en OU, additif)
    // pour chaque groupe ensuite, ne garder que les items déjà présent dans la liste
    // a la fin, afficher ce qui reste

    mainContainer.setAttribute("data-filtertags","true") // passer en mode filter
    var elems=mainContainer.querySelectorAll(".item")

    elems.forEach(function(ele){
        ele.setAttribute("data-filter","hide")
    })

    // prendre le premier groupe, récolter les items concernés
    let firstgroup=groupes[0]
    let cle=firstgroup.getAttribute("data-filter-key")
    let values=[]
    firstgroup.nextSibling.querySelectorAll("[data-check='true']").forEach((tag)=>{
        values.push(tag.textContent)
    })
    let selection = yc_filter_getitems(elems,cle,values)

    for(var i=1; i<groupes.length;i++ ){
        let cle=groupes[i].getAttribute("data-filter-key")
        let values=[]
        groupes[i].nextSibling.querySelectorAll("[data-check='true']").forEach((tag)=>{
            values.push(tag.textContent)
        })
        let selection2 = yc_filter_getitems(elems,cle,values)
        // comparer les listes, ne garder que ce qui est en commun
        for (let i = selection.length - 1; i >= 0; i--) {
            if (!selection2.includes(selection[i])) {
                selection.splice(i, 1);
            }
        }
    }

    //Afficher les résultats
    selection.forEach(function(source){
        mainContainer.querySelector(".item[data-source='"+source+"']").setAttribute("data-filter","show")
    })
}

function yc_filter_getitems(elems,cle,values){ // constituer la liste des items concernés
    let result=[]
    elems.forEach(function(elem){
        var str=elem.querySelector("[data-contenu='"+cle+"']")
        if(!str){ return }
        // cette procédure peut probablement être simplifiée: si on trouve une fois c'estok
        let add=false
        values.forEach((tag)=>{
            if(str.textContent.includes(tag)){
                add=true
            }
        })
        if(add){
            result.push(elem.getAttribute("data-source"))
        }
    })
    return result
}

function empty_filtre(valeur){ // valeur est true ou false
    document.querySelectorAll("[data-toggle-content='filtrer'] [data-filter]").forEach(function(eli){
        if(eli.getAttribute("data-type")=="radio"){
            eli.querySelector("input").checked = valeur
        } else {
            eli.querySelectorAll("input").forEach(function(elis){
                elis.checked = valeur
            })
        }
    })
    yc_filtre_items()
}

function yc_search_items(){
    var elems=mainContainer.querySelectorAll(".item")
    var val = searchField.value.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')

    if(val.length > 1){
        mainContainer.setAttribute("data-filtersearch","true")
        elems.forEach(function(el){
            var texte
            for (const child of el.children) {
                texte+=child.textContent.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')+" ";
            }
            if(texte.includes(val)) {
                el.setAttribute("data-search","show")
            } else {
                el.setAttribute("data-search","hide")
            }
        })
    } else {
        mainContainer.removeAttribute("data-filtersearch")
        elems.forEach(function(el){
            el.removeAttribute("data-search")
        })
    }
} 

function init_orderItems(){
    mainContainer.classList.add("draggingitems")
    // sortable = Sortable.create(mainContainer);
    sortable = new Sortable(mainContainer, {
        animation: 150,
        ghostClass: 'blue-background-class'
    })
}

/* mosaique */
function yc_init_mosaique_listing(){
    document.querySelectorAll("#tool-mosaique input").forEach(function(radio){
        radio.addEventListener('click', function () {

            settings.listingtype = radio.value;
            body.setAttribute("data-listingtype",radio.value)
            yc_init_mosaique_display()
        });
    })
    yc_init_mosaique_display()
}

function yc_init_mosaique_display(){
    switch(settings.listingtype){
        case "hdisplay":
            var elems=mainContainer.querySelectorAll(".item")
            var totalw=window.innerWidth
            var r=0.4
            if(totalw < 992){ r= 1}
            mainContainer.style.width=((totalw*r)*elems.length)+"px"
            break;
        default:
            mainContainer.style.width="auto"
    }
}

/* infos */
function yc_init_infos(){
    document.querySelectorAll("#tool-infos input").forEach(function(box){
        box.addEventListener('click', function () {
            let critere=box.getAttribute("data-critere")
            mainContainer.querySelectorAll("[data-contenu='"+critere+"']").forEach(function(el){
                el.classList.toggle("d-none")
            })
        });
    })
}

/* tri */
function yc_init_tri(){ 
    if(!settings.tri){ return }
    document.querySelectorAll("#tool-tri input").forEach(function(radio){
        radio.addEventListener('click', function () {
            settings.tri = radio.value;
            yc_trie_items()
        });
    })

    document.querySelector("#tool-tri input[value='"+settings.tri+"']").click() // clicker le type en cours
}
function yc_trie_items(){
    if(!settings.tri){ return }
    sortliste=[]
    var criteres = settings.tri.split('|')
    var champ=criteres[0]
    var sens=criteres[1]

    let itemslist=mainContainer.querySelectorAll(".item")
    itemslist.forEach(function(it){
        var i=it.getAttribute("data-source")
        var t
        if(champ=="id"){
            t=it.getAttribute("data-id") // tri sur l'id
        } else if(champ=="date"){
            t=it.getAttribute("data-date") // tri sur la date
        } else {
            var selectchamp=it.querySelector("[data-contenu='"+champ+"']")
            if(!selectchamp){ return }
            if(selectchamp.hasAttribute("data-rawvalue")){
                t=selectchamp.getAttribute("data-rawvalue")
            } else {
                t=selectchamp.innerHTML.toLowerCase()
            }
        }
        sortliste.push({id: i, valeur: t})
    })

    if(sens=="asc"){
        sortliste.sort(function(a,b) {
            if(a.valeur.toLowerCase() > b.valeur.toLowerCase()){
                return 1
            } else if(b.valeur.toLowerCase() > a.valeur.toLowerCase()){
                return -1
            } else {
                return 0
            }
        });
    } else {
        sortliste.sort(function(a,b) {
            if(a.valeur.toLowerCase() < b.valeur.toLowerCase()){
                return 1
            } else if(b.valeur.toLowerCase() < a.valeur.toLowerCase()){
                return -1
            } else {
                return 0
            }
        }); 
    }
    // replacer les éléments dans l'ordre demandé
    sortliste.forEach(function(item){
        mainContainer.append(mainContainer.querySelector(".item[data-source='"+item.id+"']"))
    })
    console.log("tri de "+champ+", sens "+sens+" terminé")

}

function fw_docinfotoggle(){
    if(viewerInner.getAttribute("data-show-info")=="show"){
        viewerInner.setAttribute("data-show-info","hide")
        settings.viewershowinfo=false
    } else {
        viewerInner.setAttribute("data-show-info","show")
        settings.viewershowinfo=true
    }
}
function yc_initviewer(){
    if(settings.viewertype!="fullwindow"){
        return  
    }

    // montrer/cacher la toolbar
    yc_toolbar_activate()
    viewerInner.addEventListener("mousemove", yc_toolbartest)

    let li=viewerInner.querySelectorAll("[data-slideshow]")
    if(li.length > 0){
        li[0].setAttribute("data-slideshow","actuel")
        // activer le zzom
        var imgzoom=document.querySelector("#fw-image img")
        imgzoom.addEventListener('click',function(e){
            if(imgzoom.classList.contains('active')){
                imgzoom.classList.remove("active")
                imgzoom.removeAttribute('style') 
                imgzoom.removeEventListener('mousemove', handlerzoom)
            } else {
                imgzoom.classList.add("active")
                imgzoom.addEventListener('mousemove', handlerzoom)                                                           
            }
        })
    }
    if(li.length<2){
        viewerInner.querySelectorAll(".fw-nav").forEach(function(el){
            el.remove()
        })
        // enlever l'image dans les infos
        if(li.length==1){
            li[0].remove()
        }
    }
    yc_init_audios()
    yc_init_videos()
}

// zoom sur l'image
var handlerzoom = function(e) {
    var zoomer = e.currentTarget;
    e.offsetX ? offsetX = e.offsetX : offsetX = e.touches[0].pageX
    e.offsetY ? offsetY = e.offsetY : offsetX = e.touches[0].pageX
    x = offsetX/zoomer.offsetWidth*100
    y = offsetY/zoomer.offsetHeight*100
    zoomer.style.objectPosition = x + '% ' + y + '%';
}



// montrer ou cacher la toolbar
function yc_toolbar_activate(){
    if(viewertools.y > 100){ return }

    viewerInner.setAttribute("data-toolbar","show")
    viewertools.timer = setTimeout(yc_toolbarhide, 3000)
    viewertools.toolbar_viewstate=true
}

function yc_toolbarhide(){
    if(viewertools.y < 100){ return }
    viewerInner.setAttribute("data-toolbar","hide")
    viewertools.toolbar_viewstate=false
    clearTimeout(viewertools.timer)

}
function yc_toolbartest(event){
    viewertools.y=event.clientY

    yc_toolbar_activate()
}

// afficher l'image
function yc_vieweshowimage(num){
    let li=viewerInner.querySelectorAll("[data-slideshow]")
    if(li.length <= 1) { return false }
    let ac=0
    for (let i=0; i<li.length; i++) {
        if(li[i].getAttribute("data-slideshow")=="actuel"){
            li[i].setAttribute("data-slideshow","")
            ac=i
        } 
    }
    ac=ac+num
    if(ac < 0 ) {
        if(settings.viewerloop=="both"){
            yc_itemPrev()
            return "loop"
        }
        ac=li.length-1
    } else if(ac > li.length-1) {
        if(settings.viewerloop=="both"){
            yc_itemNext()
            return "loop"
        }
        ac=0
    }
    let ni=li[ac].getAttribute("data-slideshowsrc")
    let de=li[ac].getAttribute("title")

    li[ac].setAttribute("data-slideshow","actuel")
    let vi=viewerInner.querySelector("#fw-image img")
    vi.setAttribute("src",ni)
    vi.setAttribute("alt",de)
    if(de){
        de="<span>"+de+"</span>"
    } 
    viewerInner.querySelector("#fw-image .fw-description").innerHTML= de
    return true
}
function yc_vieweshowclickimage(elem){
    if(settings.viewertype!="fullwindow"){
        return  
    }
    viewerInner.querySelectorAll("[data-slideshow]").forEach(function(el){
        el.setAttribute("data-slideshow","") 
    })
    elem.setAttribute("data-slideshow","actuel")
    let ni=elem.getAttribute("data-slideshowsrc")
    viewerInner.querySelector("#fw-image img").setAttribute("src",ni)
}

function yc_togglefullscreen(e){
    let elem = document.querySelector(e)
    if(elem.classList.contains("fullscreen")){
        yc_closeFullscreen()
    } else {
        yc_openFullscreen(elem)
    }
}
function yc_openFullscreen(elem) {
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) { /* Firefox */
        elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
        elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { /* IE/Edge */
        elem.msRequestFullscreen();
    }
    elem.classList.add("fullscreen")
}
function yc_closeFullscreen(){
    let elem=document.querySelector(".fullscreen")
    if(elem){
        elem.classList.remove("fullscreen")
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        elem.classList.remove("fullscreen")
    }   
}


function yc_stop_multimedia(){
    const l=viewerInner.querySelectorAll("audio, video").forEach(function(el){
        el.pause()
    })
    }
function yc_init_keys(){
    // depend de la situation
    // si on est en fullscreen, alors juste fermer

    document.onkeydown = function(event) {
        if(settings.formopen==true){
            return
        }
        switch (event.keyCode) {
            case 37:
                switch (settings.viewerloop) {
                    case "outer":
                        yc_itemPrev()
                        break;
                    case "inner":
                        yc_vieweshowimage(-1)
                        break;
                    case "both":
                        switch (yc_vieweshowimage(-1)) {
                            case false:
                                yc_itemPrev()
                                break;
                            case true:
                                break;
                            case "loop":
                                yc_itemPrev()
                                break;
                        }
                        break;
                }
                console.log('Flèche gauche');
                break;
            case 39:
                switch (settings.viewerloop) {
                    case "outer":
                        yc_itemNext()
                        break;
                    case "inner":
                        yc_vieweshowimage(1)
                        break;
                    case "both":
                        switch (yc_vieweshowimage(1)) {
                            case false:
                                yc_itemNext()
                                break;
                            case true:
                                break;
                            case "loop":
                                yc_itemNext()
                                break;
                        }
                        break;
                }
                console.log('Flèche droite');
                break;
            case 27:
                // escape
                if(document.querySelector(".fullscreen")){
                    yc_closeFullscreen()
                } else if(settings.viewershow == "show"){
                    yc_closeViewer()
                }
                console.log(settings.viewershow)
                console.log('escape key');
                break;
        }
    }
}

/* edition d'image */
function yc_initimage() {
    const cropperimage = document.getElementById('cropper-image')
    const cropper = new Cropper(cropperimage, {
        viewMode: 1,
        ready: function(){
            var contData = cropper.getContainerData(); //Get container data
            cropper.setCropBoxData({ height: contData.height, width: contData.width  }) 
        },
        crop(event) {
        },
    })

    document.querySelectorAll(".cropper-rotate").forEach(function(e){
        e.addEventListener('click', function () {
            var angle=e.getAttribute("data-angle")
            cropper.rotate(angle)
        })
    })

    document.querySelector("#cropper-submit").addEventListener("click", function(event) {
        leform=document.querySelector("#yc-form")
        var args = new FormData(leform)
        var source = args.get("source")
        var extension=args.get("extension")
        var mime=""
        var qualite=""
        switch(extension){
            case "jpg":
            case "jpeg":
                mime="image/jpeg"
                qualite="0.75"
                break;
            case "webp":
                mime="image/webp"
                qualite="0.75"
                break;
            case "png":
                mime="image/png"
                break;
            case "gif":
                mime="image/gif"
                break;
        }
        cropper.getCroppedCanvas().toBlob(function (blob) {
            args.append("modifiedImage", blob)
            args.append("action", "submitform")  
            args.append("callback","updategriditems")
            args.append("endaction", "reloadform")  
            args.append("viewershow", "show")
            yc_loadFile(args)
        },mime,qualite)

        event.preventDefault();
    })
    console.log("appel de yc_initimage")
}

/* 

collections 

*/
function yc_displaycollectionbutton(source){
    document.getElementById("collections-container").setAttribute("data-filtered","true")
    let cactu=document.querySelector("#collections-container [data-source='"+source+"']")
    cactu.parentNode.classList.add("filtered")
    let ctitle=cactu.querySelector("[data-contenu='titre']").innerHTML

    let bcol=yc_getIdAnyway("collection-actuel","toolbar")
    bcol.innerHTML = "&gt; "+ctitle+ " <span class='v-icon'><img src='app/images/x-lg.svg' title='Fermer la collection'></span>"
    bcol.setAttribute("onclick","yc_collectionclose()")
    bcol.setAttribute("class","link-behavior show collection-actuel")

}

function yc_collectionmanageitem(elem){
    var ic=document.getElementById("items-container")
    var item=elem.getAttribute("data-source")
    var illu=elem.querySelector("img").getAttribute("src")
    var titre=elem.querySelector("[data-contenu]").innerHTML // premier élément avec un attribut data-contenu
    if(elem.classList.contains('selected')){
        // ajouter
        yc_addcollectionitem(ic,titre,illu,item)
    } else {
        // retirer
        ic.querySelector("[data-source='"+item+"']").remove()
    }
}

function yc_addcollectionitem(ic,titre,illu,item){
    const colitem = document.createElement("div")
    colitem.setAttribute("data-source",item)
    colitem.setAttribute("class","collectionitem fs-small")
    const colitemim = document.createElement("img")
    colitemim.setAttribute("src",illu)
    colitemim.setAttribute("class","img-object-fit aspectratio-21")
    const colitemtitle = document.createElement("div")
    colitemtitle.innerHTML = titre
    colitemhid=document.createElement("input")
    colitemhid.setAttribute("name","items[]")
    colitemhid.setAttribute("type","hidden")
    colitemhid.setAttribute("value",item)

    colitem.appendChild(colitemhid)
    colitem.appendChild(colitemim)
    colitem.appendChild(colitemtitle) 

    ic.appendChild(colitem)
}

function yc_collectionclose(){
    /*
    fermer la collection
    */
    document.getElementById("collections-container").removeAttribute("data-filtered")
    mainContainer.removeAttribute("data-filtercollection")
    const actual=document.querySelector(".collection-actuel")
    if(actual){ actual.remove() }
    document.querySelectorAll("#main-grid [data-collection]").forEach(function(el){
        //itemtoshow.setAttribute("data-collection","show")
        el.removeAttribute("data-collection")
        //el.classList.remove("filtered")
        //el.removeAttribute("style")
    }) 
    let filt=document.querySelector("#collections-container .filtered")
    if(filt){
        filt.classList.remove("filtered")
    }
}

function yc_init_theme_options(){
    let theme_selector=document.querySelector(".field-theme select")
    theme_selector.onchange=function(){
        yc_change_theme_option()
    }
    yc_change_theme_option()
}

function yc_change_theme_option(){
    let theme_actuel=document.querySelector("#select_theme").value
    document.querySelectorAll('fieldset[class*="field-options"]').forEach(function(el){
        el.style.display = 'none'
    })
    document.querySelector("fieldset.field-options_"+theme_actuel).style.display="block"
}

/* 

vignettes 

*/
function yc_init_load_vignettes(){
    setTimeout(function(){
        yc_load_vignettes() 
    }, 500);
}[]

function yc_load_vignettes(){
    let lv=document.querySelectorAll("#main-grid article:not(.loaded)")
    if(lv.length == 0){ return false }
    nb_vignettes=20
    if(lv.length < nb_vignettes){ nb_vignettes=lv.length }
    // charger 20 vignettes
    for(let i=0;i<nb_vignettes;i++){
        let il=lv[i].querySelector(".item-illu")
        if(!il){ continue }
        il.setAttribute("src",il.getAttribute("data-source"))
        lv[i].classList.add("loaded")
    }
    setTimeout(function(){
        yc_load_vignettes() 
    }, 200);
}

function yc_getIdAnyway(elem,ou){
    let lieu=document.getElementById(ou)
    if(!lieu){ return false }
    let nelem=lieu.querySelector("#"+elem)
    if(nelem==null){
        nelem=document.createElement("div")
        nelem.setAttribute("id",elem)
        lieu.appendChild(nelem)
    } 
    return nelem
}
function yc_count_items(){
    document.getElementById("items_total").innerHTML = mainContainer.querySelectorAll("article").length
}

function yc_isadmin(){
    let status=body.getAttribute("data-adminstatus")
    if(status=="false") {
        return false
    }
    return true
}