var fileobj, change_bg_flag;
 
function file_explorer() {
    document.getElementById('selectfile').click();
    document.getElementById('selectfile').onchange = function() {
        fileobj = document.getElementById('selectfile').files[0];
        editor_file_upload(fileobj);
    };
}
 
function editor_file_upload(file_obj) {
    blobToBase64(fileobj).then(res => {
        if(change_bg_flag){
            editor_obj.change_source(res);                   
        }
        else{
            editor_obj.add_image(res);                    
        }
    });
}
function blobToBase64(blob) {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
        return new Promise(resolve => {
        reader.onloadend = () => {
            resolve(reader.result);
        };
    });
};
function sendData(form_data, address, resolve) { 
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", address, true);

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var response = this.responseText;
            if(typeof resolve != "undefined"){
                resolve(response);          
            }
        }
    };
    xhttp.send(form_data);
}
function source_file_upload() {
    var totalfiles = document.getElementById('files').files.length;
    if(totalfiles > 0 ){
        var form_data = new FormData();
        for (var i in photos_array) {
          form_data.append("files[]", photos_array[i]);
        }
        refreshFilesGallery(form_data);
    }else{
        alert("Файлы не выбраны");
    }
}
function refreshFilesGallery(form_data, address="save_source_files.php"){
    const promise = new Promise((resolve, reject) => {
        sendData(form_data, address, resolve);
    });
    promise.then((response) => {
        if(change_bg_flag){
            editor_obj.change_source(response);                   
        }
        else{
            // console.log(response);
            document.querySelector(".gallery-container").innerHTML = response; 
            thumb_gallery_container.innerHTML = ""; 
            button_prev.style.display = "none";
            button_next.style.display = "none"; 
            photos_array = [];             
        }
    })
}