/*

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,
}

yc_init_filter()

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()

/*
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")
    .previousElementSibling
    if(ai){ 
        while (ai!==null) {
            if(ai.style.display === "none") {
                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").nextElementSibling
    if(ai){ 
        while (ai!==null) {
            if(ai.style.display === "none") {
                ai = ai.nextElementSibling;
            } else {
                yc_clicItem(ai)
                //yc_showItem(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)
}
function yc_editItem(file){
    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(".yscontent")
        var te=el.querySelector("input")
        te.classList.add("d-none")

        var yse = new ysEditor({
            toolbar: [
                "bold","italic","underline","h1","h2","undo", "redo","removeformat"
            ],
            wrapper: ed,
            footer: false
        })

        })

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

    // yseditor: updater le input
    let editors=document.querySelectorAll("[data-editor]").forEach(function(el){
        var ed=el.querySelector(".yseditor-content")
        var te=el.querySelector("input")
        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
        }
    }

    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-filtered","true") 
    const rc = JSON.parse(response)

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

}


/* 

FONCTIONS DE ENDACTION

*/

function yc_reloadadmin(){
    console.log("Appel de reloadadmin")
    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)
    })
    */
}

/*
tout cacher
montrer tout ce qui comporte un des checkbox/radio
cacher tout ce qui ne correspond pas à la searchbox

*/
function yc_filtre_items(){
    var elems=mainContainer.querySelectorAll(".item")
    var filtres=document.querySelectorAll("[data-toggle-content='filtrer'] [data-filtre]")

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

    filtres.forEach(function(elf){
        var cate=elf.getAttribute("data-filtre")

        elf.querySelectorAll("[data-toggle-content='filtrer'] input, [data-toggle-content='filtrer'] select option:checked").forEach(function(eli){
            var elcont=eli.value
            var eltag=eli.tagName.toLowerCase()

            if(eltag == "option"){
                elcont=eli.text
            } else {
                if(!eli.checked || !elcont){ return } 
            }

            elems.forEach(function(it){
                var st=it.querySelector("[data-contenu='"+cate+"']")
                if(!st){ return }
                if(st.textContent.includes(elcont)){
                    it.setAttribute("data-filtre","show")
                }
            })

        })

    })
}

function empty_filtre(valeur){ // valeur est true ou false
    document.querySelectorAll("[data-toggle-content='filtrer'] [data-filtre]").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){
        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 {
        elems.forEach(function(el){
            el.setAttribute("data-search","show")
        })
    }
} 

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")
    document.getElementById("main-grid").removeAttribute("data-filtered")
    const actual=document.querySelector(".collection-actuel")
    if(actual){ actual.remove() }
    document.querySelectorAll("#collections-container .filtered, #main-grid .filtered").forEach(function(el){
        el.classList.remove("filtered")
        el.removeAttribute("style")
    }) 
}

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
}