const bs40PopupInit = (event) => {

    document.querySelectorAll('input[data-role="media-popup-search"]').forEach((inputElement) => {
        console.log('ccdev 004 attach input', inputElement);
        inputElement.addEventListener('keyup', bs40MediaSearchEvent);
    });
}
const bs40MediaSearchEvent = (event) =>{
    event.preventDefault();
    event.stopImmediatePropagation();
    event.stopPropagation();
    
    var txt = event.target.value.trim();
    
    if(txt=='')
        return;

    if(event.keyCode==13) //enter key
    {   bs40PopupSearch(event, txt);
    } else if( event.key!='Meta' && ((event.keyCode>=32) || (event.keyCode==8)) ) //an actual character or backspace
    {   
        console.log('ccdev 0025 keyup event ',event);

        setTimeout(function(event, txt)
        {   var newtxt = event.target.value;
            if(txt==newtxt)
            {   //text has not changed after the timeout, so stopped typing
                //do your action, such as search()
                bs40PopupSearch(event, txt);
            }
        },750, event, txt);
    }

    return false;
};
const bs40PopupSearch = (event, txt) =>{
    bs4.bell(0.01,900);

    // set the select folder option to empty
    const mediaLibrary = event.target.closest('div[class="media__library"]');
    const selector = mediaLibrary.querySelector('select#uploadDirectory');
    selector.value='';

    const libraryitems = mediaLibrary.querySelector('div[data-role=media-items]');

    if(libraryitems!=null)
    {
        libraryitems.innerHTML = "<div style='text-align:center;font-size:200%;'>Loading...</div>";
    
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
            if (xhr.status === 200) {
            // console.bs4log('ccdev 43 Ajax200:',  xhr.status, xhr.responseText);
            // console.bs4log('ccdev 46', xhr);
            libraryitems.innerHTML = xhr.response;
            } else
            {
                console.bs4log('ccdev 051 AjaxFail:',  xhr.response)
            }
        }
    
        var formData = new FormData();
        formData.append("q", txt);
        formData.append("popup", 1);
    
        xhr.open("POST", "/adminBS4/ajax/media-search-images", true);
        //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content);
        xhr.send(formData);
    }
};
document.addEventListener('DOMContentLoaded', bs40PopupInit);