/*
    Copyright AneonTech
    aneontech.help@gmail.com
*/

"use strict";

var myDropzone;
var totalFiles = 0;
var currentFile = 0;
var queuedFiles = [];

if (
    document.querySelector('[name="g-recaptcha-response"]') !== null
    && document.querySelector('.upload-files') !== null
) {
    grecaptcha.ready(function() {
        document.querySelector('.upload-files').classList.remove('disabled');
    });
}

// Listen for clicks
document.addEventListener("click", function (event) {

    // Start dropzone
    if (event.target.matches("#upload-files")) {
        queuedFiles = myDropzone.getQueuedFiles();
        if (queuedFiles.length > 0) {
            totalFiles = queuedFiles.length;
            currentFile = 0;

            if (document.querySelectorAll('.dz-remove') !== null) {
                document.querySelectorAll('.dz-remove').forEach(dzRemove => {
                    dzRemove.remove();
                });
            }

            if (document.querySelector('#upload-file [name="g-recaptcha-response"]') !== null) {
                grecaptcha.ready(function() {
                    grecaptcha.execute(`${sysVars.recaptcha_site_key}`, {
                        action: 'upload_file'
                    }).then(function(token) {
                        document
                            .querySelector('#upload-file [name="g-recaptcha-response"]')
                            .value = token;
                            setTimeout(function () {
                                myDropzone.processFile(queuedFiles[currentFile]);
                            }, 250);
                    });
                });
            } else {
                setTimeout(function () {
                    myDropzone.processFile(queuedFiles[currentFile]);
                }, 250);
            }
        } else {
            toaster(langVars.no_file_selected, 0); 
        }
    }

    // Start dropzone (Upload via link version)
    if (event.target.matches("#upload-files-url")) {
        uploadFileByUrl();
    }

    // Open uploader settings modals      
    if (event.target.matches("[data-modal]")) {
    
        var target = event.target.getAttribute("data-modal");
        const myModal = new bootstrap.Modal(`#${target}`, {
            keyboard: false,
            backdrop: "static"
        });
        myModal.toggle();
    }

    // Close and reset uploader settings modals    
    if (event.target.matches(".modal-cancel")) {
        if (event.target.getAttribute('data-modal-id') !== null) {
            var modalId = event.target.getAttribute('data-modal-id');
            var modal = document.querySelector(`#${modalId}`);
            modal.querySelectorAll('input').forEach(input => {
                input.value = '';
            });
            modal.querySelectorAll('select').forEach(select => {
                select.selectedIndex = 0;
            });
            modal.querySelectorAll('input[type=range]').forEach(range => {
                if (range.getAttribute('data-default') !== null) {
                    var val = range.getAttribute('data-default');
                    range.value = val;
                }
            });
            modal.querySelectorAll('input[type=checkbox]').forEach(checkbox => {
                if (checkbox.getAttribute('data-default') == "false") {
                    checkbox.checked = false;
                } else {
                    checkbox.checked = true;
                }
            });
        }
    }

});

document.addEventListener("change", function (event) {

    // Open uploader settings modals buttons
    if (event.target.matches("[data-advanced-options]")) {
        if (event.target.checked) {
            document.querySelectorAll('[data-options]').forEach(el => {
                el.classList.add('show');
            });
        } else {
            document.querySelectorAll('[data-options]').forEach(el => {
                el.classList.remove('show');
            });
        }
    }
    
});

document.addEventListener("submit", function (event) {

    // Prevent default submit func. for dropzone
    if (event.target.matches("#file-upload-form")) {
        event.preventDefault();
    }

});

document.addEventListener("paste", function (event) {

    // Copy-paste a file to dropzone
    if (document.querySelector('[data-bs-target="#upload-file"]') !== null) {
        var uploadTab = document.querySelector('[data-bs-target="#upload-file"]');
        if (uploadTab.classList.contains('active')) {
            const items = (event.clipboardData || event.originalEvent.clipboardData).items;
            for (const item of Object.values(items)) {
                if (item.kind === 'file') {
                    // adds the file to your dropzone instance
                    myDropzone.addFile(item.getAsFile())
                }
            }
        }
    }

});

// Listen for Bootstrap tab changes
document.addEventListener("show.bs.tab", function (event) {

    // Change dropzone id based on upload methods
    if (event.target.matches(".upload-methods > a")) {
        var type = event.target.getAttribute('data-bs-target');
        
        if (type == '#upload-file') {
            document.querySelector('.upload-files').id = 'upload-files';
        } else if (type == '#upload-url') {
            document.querySelector('.upload-files').classList.add('disabled');
            document.querySelector('.upload-files').id = 'upload-files-url';
            if (document.querySelector('[name="g-recaptcha-response"]') !== null) {
                grecaptcha.ready(function() {
                    document.querySelector('.upload-files').classList.remove('disabled');
                });
            } else {
                document.querySelector('.upload-files').classList.remove('disabled');
            }
        }
        
    }
});

Dropzone.autoDiscover = false;
function dropzoneInit() {
    if (sysVars.accepted_files !== null) {
        var acceptedTypes = '';
        for (let [index, type] of sysVars.accepted_files.entries()) {
            if (index === sysVars.accepted_files.length - 1) {
                acceptedTypes += `.${type}`;
            } else {
                acceptedTypes += `.${type},`;
            }
        }
    }
    myDropzone = new Dropzone(".dropzone-uploader", {
        url: sysVars.upload_url,
        paramName: "file",
        addRemoveLinks: true,
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 1,
        acceptedFiles: acceptedTypes !== null && acceptedTypes
            ? acceptedTypes
            : null,
        maxFiles: 10,
        maxFilesize: sysVars.max_file_size,
        withCredentials: true,
        previewsContainer: '.dropzone-previews',
        clickable: ['#upload-file > .dropzone', '.dropzone-previews-inner'],
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="token"]').content
        },
        init: function() {
            this.on("sending", function(file, xhr, formData) {

                if (file.previewElement.querySelector('.dz-remove')) {
                    file.previewElement.querySelector('.dz-remove').remove();
                }
                var progressBar = file.previewElement
                    .querySelector('.dz-progress');
                progressBar.style.opacity = ".25";

                document.querySelector('#upload-files').classList.add('disabled');
                document.querySelector('#upload-files').disabled = true;
                document.querySelector('#upload-files > .spinner-border').classList.remove('d-none');
                document.querySelector('#upload-files > .upload-button-text').classList.add('d-none');

                if (document.querySelector('[name="type"]') !== null) {
                    var type = document.querySelector('[name="type"]');
                    formData.append(
                        'type',
                        type.value
                    );
                }
                if (document.querySelector('[name="compress"]') !== null) {
                    var compress = document.querySelector('[name="compress"]');
                    formData.append(
                        'compress',
                        compress.value > 0 ? compress.value : ''
                    );
                }
                if (document.querySelector('[name="size[width]"]') !== null) {
                    var sizeWidth = document.querySelector('[name="size[width]"]');
                    formData.append(
                        'size[width]',
                        sizeWidth.value
                    );
                }
                if (document.querySelector('[name="size[height]"]') !== null) {
                    var sizeHeight = document.querySelector('[name="size[height]"]');
                    formData.append(
                        'size[height]',
                        sizeHeight.value
                    );
                }
                if (document.querySelector('[name="rotation-reflect"]') !== null) {
                    var rotationReflect = document.querySelector('[name="rotation-reflect"]');
                    formData.append(
                        'rotation-reflect',
                        rotationReflect.value
                    );
                }
                if (document.querySelector('[name="watermark"]') !== null) {
                    var watermark = document.querySelector('[name="watermark"]');
                    formData.append(
                        'watermark',
                        watermark.value
                    );
                }
                if (document.querySelector('[name="preferences[brightness]"]') !== null) {
                    var preferencesBrightness = document
                        .querySelector('[name="preferences[brightness]"]');
                    formData.append(
                        'preferences[brightness]',
                        preferencesBrightness.value != 0 ? preferencesBrightness.value : ''
                    );
                }
                if (document.querySelector('[name="preferences[contrast]"]') !== null) {
                    var preferencesContrast = document
                        .querySelector('[name="preferences[contrast]"]');
                    formData.append(
                        'preferences[contrast]',
                        preferencesContrast.value != 0 ? preferencesContrast.value : ''
                    );
                }
                if (document.querySelector('[name="preferences[gamma]"]') !== null) {
                    var preferencesGamma = document
                        .querySelector('[name="preferences[gamma]"]');
                    formData.append(
                        'preferences[gamma]',
                        preferencesGamma.value != 1 ? preferencesGamma.value : ''
                    );
                }
                if (document.querySelector('[name="preferences[red]"]') !== null) {
                    var preferencesRed = document
                        .querySelector('[name="preferences[red]"]');
                    formData.append(
                        'preferences[red]',
                        preferencesRed.value != 0 ? preferencesRed.value : ''
                    );
                }
                if (document.querySelector('[name="preferences[green]"]') !== null) {
                    var preferencesGreen = document
                        .querySelector('[name="preferences[green]"]');
                    formData.append(
                        'preferences[green]',
                        preferencesGreen.value != 0 ? preferencesGreen.value : ''
                    );
                }
                if (document.querySelector('[name="preferences[blue]"]') !== null) {
                    var preferencesBlue = document
                        .querySelector('[name="preferences[blue]"]');
                    formData.append(
                        'preferences[blue]',
                        preferencesBlue.value != 0 ? preferencesBlue.value : ''
                    );
                }
                if (document.querySelector('[name="effects[grayscale]"]') !== null) {
                    var effectsGrayscale = document
                        .querySelector('[name="effects[grayscale]"]');
                    formData.append(
                        'effects[grayscale]',
                        effectsGrayscale.checked ? 1 : ''
                    );
                }
                if (document.querySelector('[name="effects[blur]"]') !== null) {
                    var effectsBlur = document
                        .querySelector('[name="effects[blur]"]');
                    formData.append(
                        'effects[blur]',
                        effectsBlur.checked ? 1 : ''
                    );
                }
                if (document.querySelector('[name="effects[invert]"]') !== null) {
                    var effectsInvert = document
                        .querySelector('[name="effects[invert]"]');
                    formData.append(
                        'effects[invert]',
                        effectsInvert.checked ? 1 : ''
                    );
                }
                if (document.querySelector('[name="effects[pixelation]"]') !== null) {
                    var effectsPixelation = document
                        .querySelector('[name="effects[pixelation]"]');
                    formData.append(
                        'effects[pixelation]',
                        effectsPixelation.checked ? 1 : ''
                    );
                }
                if (document.querySelector('[name="effects[reduce]"]') !== null) {
                    var effectsReduce = document
                        .querySelector('[name="effects[reduce]"]');
                    formData.append(
                        'effects[reduce]',
                        effectsReduce.checked ? 1 : ''
                    );
                }
                if (document.querySelector('[name="auto-remove"]') !== null) {
                    var autoRemove = document
                        .querySelector('[name="auto-remove"]');
                    formData.append(
                        'auto-remove',
                        autoRemove.value.length > 0 ? autoRemove.value : ''
                    );
                }
                if (document.querySelector('[name="password"]') !== null) {
                    var password = document.querySelector('[name="password"]');
                    formData.append(
                        'password',
                        password.value.length > 0 ? password.value : ''
                    );
                }
                if (document.querySelector('[name="exif[basic]"]') !== null) {
                    var exifBasic = document.querySelector('[name="exif[basic]"]');
                    formData.append(
                        'exif[basic]',
                        exifBasic.checked ? 1 : ''
                    );
                }
                if (document.querySelector('[name="exif[deep]"]') !== null) {
                    var exifDeep = document.querySelector('[name="exif[deep]"]');
                    formData.append(
                        'exif[deep]',
                        exifDeep.checked ? 1 : ''
                    );
                }
                if (document.querySelector('#upload-file [name="g-recaptcha-response"]') !== null) {
                    var recaptchaEl = document
                        .querySelector('#upload-file [name="g-recaptcha-response"]');
                    formData.append(
                        'g-recaptcha-response',
                        recaptchaEl.value
                    );
                }
            });
            this.on("addedfile", function(file) {
                var userScreen = getViewport();
                if (userScreen == 'xs') {
                    var scrollBreak = 4;
                } else if (userScreen == 'sm') {
                    var scrollBreak = 6;
                } else if (userScreen == 'md') {
                    var scrollBreak = 8;
                } else if (userScreen == 'lg') {
                    var scrollBreak = 6;
                } else if (userScreen == 'xl') {
                    var scrollBreak = 8; 
                } else if (userScreen == 'xxl') {
                    var scrollBreak = 8;
                } else {
                    var scrollBreak = 8;
                }

                var count = myDropzone.files.length;
                document.querySelector('#upload-file > .dropzone')
                    .classList.remove('d-flex');
                if (count > 0) {
                    document.querySelector('#upload-file > .dropzone')
                        .classList.add('dz-started');
                }
                if (count > scrollBreak) {
                    document.querySelector('.dropzone-previews')
                        .style.maxHeight = "16.5rem";
                    document.querySelector('.dropzone-previews')
                        .style.overflowY = "scroll";
                }
                if (file.type.match(/image.*/)) {
                    file.previewElement.querySelector('.dz-details').style.setProperty("opacity", "0", "important");
                    file.previewElement.querySelector('.dz-filename').style.setProperty("display", "none", "important");
                    file.previewElement.querySelector('.dz-size').style.setProperty("display", "none", "important");
                } else {
                    file.previewElement.querySelector('.dz-details').style.setProperty("opacity", "1", "important");
                    file.previewElement.querySelector('.dz-filename').style.setProperty("display", "block", "important");
                    file.previewElement.querySelector('.dz-size').style.setProperty("display", "block", "important");
                }

                var count = myDropzone.files.length;
                if (count > this.options.maxFiles) {
                    this.removeFile(file);
                    toaster(`${langVars.file_max}`,0);
                    return false;
                }
            });
            this.on("removedfile", function(file) {
                var userScreen = getViewport();
                if (userScreen == 'xs') {
                    var scrollBreak = 4;
                } else if (userScreen == 'sm') {
                    var scrollBreak = 6;
                } else if (userScreen == 'md') {
                    var scrollBreak = 8;
                } else if (userScreen == 'lg') {
                    var scrollBreak = 6;
                } else if (userScreen == 'xl') {
                    var scrollBreak = 8; 
                } else if (userScreen == 'xxl') {
                    var scrollBreak = 8;
                } else {
                    var scrollBreak = 8;
                }
                var count = myDropzone.files.length;
                if (count == 0) {
                    document.querySelector('#upload-file > .dropzone')
                        .classList.add('d-flex');
                    document.querySelector('#upload-file > .dropzone')
                        .classList.remove('dz-started');
                }
                if (count < scrollBreak) {
                    document.querySelector('.dropzone-previews')
                        .style.maxHeight = "unset";
                    document.querySelector('.dropzone-previews')
                        .style.overflowY = "unset"; 
                }
                file.previewElement.remove();
            });
            this.on("uploadprogress", function(file, progress) {
                var progressBar = file.previewElement
                    .querySelector('.dz-progress');
                progressBar.style.width = progress + "%";
            });
            this.on("complete", async function(file) {
                if (file.previewElement.querySelector('.dz-remove')) {
                    file.previewElement.querySelector('.dz-remove').remove();
                }
                if (totalFiles > currentFile + 1) {
                    if (document.querySelector('#upload-file [name="g-recaptcha-response"]') !== null) {
                        grecaptcha.ready(function() {
                            grecaptcha.execute(`${sysVars.recaptcha_site_key}`, {
                                action: 'upload_file'
                            }).then(function(token) {
                                document
                                    .querySelector('#upload-file [name="g-recaptcha-response"]')
                                    .value = token;
                                    setTimeout(function () {
                                        currentFile = currentFile + 1;
                                        myDropzone.processFile(queuedFiles[currentFile]);
                                    }, 250);
                            });
                        });
                    } else {
                        currentFile = currentFile + 1;
                        myDropzone.processFile(queuedFiles[currentFile]);
                    }
                } else {
                    totalFiles = 0;
                    currentFile = 0;
                    queuedFiles = [];
                }
            });
            this.on("queuecomplete", function(file, result) {
                document.querySelector('#upload-files > .spinner-border').classList.add('d-none');
                document.querySelector('#upload-files > .upload-button-text').classList.remove('d-none');
                document.querySelector('#upload-files').classList.remove('disabled');
                document.querySelector('#upload-files').disabled = false;
            });
            this.on("success", function(file, result) {
                try {
                    if (result.result) {
                        file.previewElement.querySelector('.dz-details').style.setProperty("opacity", "0", "important");
                        file.previewElement.querySelector('.dz-filename').style.setProperty("display", "none", "important");
                        file.previewElement.querySelector('.dz-size').style.setProperty("display", "none", "important");
                        var previewImg = file.previewElement.querySelector('img');
                        previewImg.src = `data:image/jpg;base64,${result.thumb}`;
                        addImageOpener(file.previewElement, result.url);
                    } else {
                        file.previewElement.classList.remove("dz-success");
                        file.previewElement.classList.add("dz-error");
                        if (result.errors) {
                            var errors = Object.values(result.errors);
                            errors.forEach(error => {
                                toaster(error, 0);  
                            });
                        } else {
                            toaster(result.data, 0); 
                        }
                    }
                } catch (e) {
                    toaster(langVars.error, 0); 
                }
            });
            this.on("error", function(file, result, xhr) {
                this.removeFile(file);
                if (file.size > this.options.maxFilesize * 1024 * 1024) {
                    toaster(`${langVars.file_max_size}`,0);
                }
            });
        }
    });
}

var passiveDropzone = false;
function uploadFileByUrl() {
    document.querySelector('#upload-files-url').classList.add('disabled');
    document.querySelector('#upload-files-url').disabled = true;
    document.querySelector('#upload-files-url > .spinner-border').classList.remove('d-none');
    document.querySelector('#upload-files-url > .upload-button-text').classList.add('d-none');

    const xhr = new XMLHttpRequest();
    xhr.open("POST", sysVars.upload_link_url, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader(
        "X-CSRF-TOKEN",
        document.querySelector('meta[name="token"]').content
    );
    xhr.addEventListener("error", () => {
        toaster(langVars.error, 0);
    });
    xhr.addEventListener("abort", () => {
        toaster(langVars.cancelled, 0);
    });
    xhr.addEventListener("load", () => {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            var result = JSON.parse(xhr.responseText);
            if (result.result) {

                document.querySelector('#upload-url [name="file-url"]').value = '';
                
                if (!passiveDropzone) {
                    passiveDropzone = new Dropzone(".dropzone-passive", {
                        url: '/',
                        paramName: "file",
                        maxFiles: 10,
                        maxFilesize: 10, // MB
                        addRemoveLinks: false,
                        autoProcessQueue: false,
                        uploadMultiple: true,
                        parallelUploads: 1,
                        withCredentials: true,
                        clickable: false,
                        previewsContainer: '.dropzone-links',
                    });
                }
                
                passiveDropzone.on("accept", file => {
                    var reader = new FileReader();
                    var dz = this;
                    reader.addEventListener("loadend", function(event) {
                        console.log(event.target.result);
                        file.status = Dropzone.SUCCESS;
                        dz.emit("success", file);
                        dz.emit("complete", file);
                    });
                    reader.readAsText(file);
                });
                passiveDropzone.on("addedfile", file => {
                    var userScreen = getViewport();
                    if (userScreen == 'xs') {
                        var scrollBreak = 4;
                    } else if (userScreen == 'sm') {
                        var scrollBreak = 6;
                    } else if (userScreen == 'md') {
                        var scrollBreak = 8;
                    } else if (userScreen == 'lg') {
                        var scrollBreak = 6;
                    } else if (userScreen == 'xl') {
                        var scrollBreak = 8; 
                    } else if (userScreen == 'xxl') {
                        var scrollBreak = 8;
                    } else {
                        var scrollBreak = 8;
                    }
                    var count = passiveDropzone.files.length;
                    document.querySelector('.dropzone-passive').classList.remove('d-flex');
                    if (count > 0) {
                        document.querySelector('.dropzone-passive').classList.add('dz-started');
                    }
                    if (count > scrollBreak) {
                        document.querySelector('.dropzone-links')
                            .style.maxHeight = "16.5rem";
                        document.querySelector('.dropzone-links')
                            .style.overflowY = "scroll";
                    }
                    addImageOpener(file.previewElement, result.url);
                    var progressBar = file.previewElement.querySelector('.dz-progress');
                    progressBar.style.opacity = ".25";
                    progressBar.style.width = "100%";
                    file.previewElement.classList.add('dz-success');
                });

                document.querySelector('.dropzone-results').classList.add('show');

                let mockFile = { name: "Filename", accepted: false };
                let callback = null;
                let crossOrigin = "Anonymous";
                let resizeThumbnail = true;
                passiveDropzone.files.push(mockFile);
                passiveDropzone.displayExistingFile(mockFile, `data:image/jpg;base64,${result.thumb}`, callback, crossOrigin, resizeThumbnail);
                
            } else {
                if (result.errors) {
                    var errors = Object.values(result.errors);
                    errors.forEach(error => {
                        toaster(error, 0);  
                    });
                }
                if (result.data) {
                    toaster(result.data, 0);
                }
            }
        } else {
            var result = JSON.parse(xhr.responseText);
            if (result.errors) {
                var errors = Object.values(result.errors);
                errors.forEach(error => {
                    toaster(error, 0);  
                });
            } else {
                toaster(langVars.error, 0);
            }
        }
        if (document.querySelector('#upload-url [name="g-recaptcha-response"]') !== null) {
            grecaptcha.ready(function() {
                grecaptcha.execute(`${sysVars.recaptcha_site_key}`, {
                    action: 'upload_url'
                }).then(function(token) {
                    document
                        .querySelector('#upload-url [name="g-recaptcha-response"]')
                        .value = token;
                });
            });
        }
        document.querySelector('#upload-files-url > .spinner-border').classList.add('d-none');
        document.querySelector('#upload-files-url > .upload-button-text').classList.remove('d-none');
        document.querySelector('#upload-files-url').classList.remove('disabled');
        document.querySelector('#upload-files-url').disabled = false;
    });
    
    const formData = new FormData();

    if (document.querySelector('[name="file-url"]') !== null) {
        var fileUrl = document.querySelector('[name="file-url"]');
        formData.append(
            'file-url',
            fileUrl.value
        );
    }
    if (document.querySelector('[name="type"]') !== null) {
        var type = document.querySelector('[name="type"]');
        formData.append(
            'type',
            type.value
        );
    }
    if (document.querySelector('[name="compress"]') !== null) {
        var compress = document.querySelector('[name="compress"]');
        formData.append(
            'compress',
            compress.value > 0 ? compress.value : ''
        );
    }
    if (document.querySelector('[name="size[width]"]') !== null) {
        var sizeWidth = document.querySelector('[name="size[width]"]');
        formData.append(
            'size[width]',
            sizeWidth.value
        );
    }
    if (document.querySelector('[name="size[height]"]') !== null) {
        var sizeHeight = document.querySelector('[name="size[height]"]');
        formData.append(
            'size[height]',
            sizeHeight.value
        );
    }
    if (document.querySelector('[name="rotation-reflect"]') !== null) {
        var rotationReflect = document.querySelector('[name="rotation-reflect"]');
        formData.append(
            'rotation-reflect',
            rotationReflect.value
        );
    }
    if (document.querySelector('[name="watermark"]') !== null) {
        var watermark = document.querySelector('[name="watermark"]');
        formData.append(
            'watermark',
            watermark.value
        );
    }
    if (document.querySelector('[name="preferences[brightness]"]') !== null) {
        var preferencesBrightness = document
            .querySelector('[name="preferences[brightness]"]');
        formData.append(
            'preferences[brightness]',
            preferencesBrightness.value != 0 ? preferencesBrightness.value : ''
        );
    }
    if (document.querySelector('[name="preferences[contrast]"]') !== null) {
        var preferencesContrast = document
            .querySelector('[name="preferences[contrast]"]');
        formData.append(
            'preferences[contrast]',
            preferencesContrast.value != 0 ? preferencesContrast.value : ''
        );
    }
    if (document.querySelector('[name="preferences[gamma]"]') !== null) {
        var preferencesGamma = document
            .querySelector('[name="preferences[gamma]"]');
        formData.append(
            'preferences[gamma]',
            preferencesGamma.value != 1 ? preferencesGamma.value : ''
        );
    }
    if (document.querySelector('[name="preferences[red]"]') !== null) {
        var preferencesRed = document
            .querySelector('[name="preferences[red]"]');
        formData.append(
            'preferences[red]',
            preferencesRed.value != 0 ? preferencesRed.value : ''
        );
    }
    if (document.querySelector('[name="preferences[green]"]') !== null) {
        var preferencesGreen = document
            .querySelector('[name="preferences[green]"]');
        formData.append(
            'preferences[green]',
            preferencesGreen.value != 0 ? preferencesGreen.value : ''
        );
    }
    if (document.querySelector('[name="preferences[blue]"]') !== null) {
        var preferencesBlue = document
            .querySelector('[name="preferences[blue]"]');
        formData.append(
            'preferences[blue]',
            preferencesBlue.value != 0 ? preferencesBlue.value : ''
        );
    }
    if (document.querySelector('[name="effects[grayscale]"]') !== null) {
        var effectsGrayscale = document
            .querySelector('[name="effects[grayscale]"]');
        formData.append(
            'effects[grayscale]',
            effectsGrayscale.checked ? 1 : ''
        );
    }
    if (document.querySelector('[name="effects[blur]"]') !== null) {
        var effectsBlur = document.querySelector('[name="effects[blur]"]');
        formData.append(
            'effects[blur]',
            effectsBlur.checked ? 1 : ''
        );
    }
    if (document.querySelector('[name="effects[invert]"]') !== null) {
        var effectsInvert = document.querySelector('[name="effects[invert]"]');
        formData.append(
            'effects[invert]',
            effectsInvert.checked ? 1 : ''
        );
    }
    if (document.querySelector('[name="effects[pixelation]"]') !== null) {
        var effectsPixelation = document
            .querySelector('[name="effects[pixelation]"]');
        formData.append(
            'effects[pixelation]',
            effectsPixelation.checked ? 1 : ''
        );
    }
    if (document.querySelector('[name="effects[reduce]"]') !== null) {
        var effectsReduce = document.querySelector('[name="effects[reduce]"]');
        formData.append(
            'effects[reduce]',
            effectsReduce.checked ? 1 : ''
        );
    }
    if (document.querySelector('[name="auto-remove"]') !== null) {
        var autoRemove = document.querySelector('[name="auto-remove"]');
        formData.append(
            'auto-remove',
            autoRemove.value.length > 0 ? autoRemove.value : ''
        );
    }
    if (document.querySelector('[name="password"]') !== null) {
        var password = document.querySelector('[name="password"]');
        formData.append(
            'password',
            password.value.length > 0 ? password.value : ''
        );
    }
    if (document.querySelector('[name="exif[basic]"]') !== null) {
        var exifBasic = document.querySelector('[name="exif[basic]"]');
        formData.append(
            'exif[basic]',
            exifBasic.checked ? 1 : ''
        );
    }
    if (document.querySelector('[name="exif[deep]"]') !== null) {
        var exifDeep = document.querySelector('[name="exif[deep]"]');
        formData.append(
            'exif[deep]',
            exifDeep.checked ? 1 : ''
        );
    }
    if (document.querySelector('#upload-file [name="g-recaptcha-response"]') !== null) {
        var recaptchaEl = document
            .querySelector('#upload-url [name="g-recaptcha-response"]');
        formData.append(
            'g-recaptcha-response',
            recaptchaEl.value
        );
    }

    xhr.send(formData);
}

// Add image opener button to dropzone elements
function addImageOpener(file, fileUrl) {
    var anchor = document.createElement("a");
    anchor.classList.add(
        'image-opener',
        'd-flex',
        'justify-content-center',
        'align-items-center'
    );
    anchor.href = fileUrl;
    anchor.setAttribute('target', '_blank');
    var icon = document.createElement("i");
    icon.classList.add('fa-solid','fa-link','fa-fw','fa-lg','pe-none');
    anchor.appendChild(icon);
    file.appendChild(anchor);
}

// Get user screen resolution as bootstrap 5 type
function getViewport() {
    const width = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    )

    // xs - size less than or 575.98
    if (width <= 575.98) return 'xs'
    // sm - size between 576 - 767.98
    if (width >= 576 && width <= 767.98) return 'sm'
    // md - size between 768 - 991.98
    if (width >= 768 && width <= 991.98) return 'md'
    // lg - size between 992 - 1199.98
    if (width >= 992 && width <= 1199.98) return 'lg'
    // xl - size between 1200 - 1399.98
    if (width >= 1200 && width <= 1399.98) return 'xl'

    // xxl- size greater than 1399.98
    return 'xxl'
}