(function () {
    function showFilePreview(input) {
        var file = input.files && input.files[0];
        if (!file || !file.type.startsWith('image/')) {
            return;
        }

        var row = input.closest('.inline-related') || input.closest('.form-row');
        if (!row) {
            return;
        }

        var box = row.querySelector('.fk-evidence-preview-live');
        if (!box) {
            box = document.createElement('div');
            box.className = 'fk-evidence-preview-live';
            input.parentNode.appendChild(box);
        }

        var reader = new FileReader();
        reader.onload = function (event) {
            box.innerHTML = '<img src="' + event.target.result + '" alt="Vorschau">';
        };
        reader.readAsDataURL(file);
    }

    document.addEventListener('change', function (event) {
        if (event.target.type === 'file' && event.target.name && event.target.name.indexOf('evidence_files') !== -1) {
            showFilePreview(event.target);
        }
    });
})();
