/**
 * Created by Vladimir on 25.03.2018.
 */

function initImageUpload(box) {
    let uploadField = box.querySelector('.image-upload');

    uploadField.addEventListener('change', getFile);

    function getFile(e) {
        let file = e.currentTarget.files[0];
        checkType(file);
    }

    function previewImage(file) {
        let thumb = box.querySelector('.js--image-preview'),
            reader = new FileReader();

        reader.onload = function () {
            box.querySelector('.js--image-preview span').style.display = 'none';
            thumb.style.backgroundImage = 'url(' + reader.result + ')';
            box.querySelector('.required-field-block').style.display = null;
        };
        reader.readAsDataURL(file);
        thumb.className += ' js--no-default';
    }

    function checkType(file) {
        let imageType = /image.*/;
        if (!file.type.match(imageType)) {
            throw 'Файл не правильного формата';
        } else if (!file) {
            throw 'Отсутствует файл';
        } else {
            previewImage(file);
        }
    }

}

function clearInputFile(element){
    box = element.parentElement;
    box.querySelector('.image-upload').value = null;
    box.querySelector('.js--image-preview').style.backgroundImage = 'url("")';
    box.querySelector('.js--image-preview').className = 'js--image-preview';
    $(box.querySelector('.required-field-block')).hide();
    $(box.querySelector('.js--image-preview span')).show();
}

var boxes = document.querySelectorAll('.box');
for (let i = 0; i < boxes.length; i++) {
    let box = boxes[i];
    initImageUpload(box);
}