export default () => {
    $('.image-picker').each(function () {
        let input = $(this);
        input.attr('placeholder', LOCALE.IMAGE_PICKER__INPUT);

        let imageType = input.attr('data-image-type') || 'image';

        let wrapper = input.parent('p');
        if (wrapper.length > 0) {
            wrapper.addClass('image-picker-wrapper');
        } else {
            input.wrap('<p class="image-picker-wrapper"></p>');
            wrapper = input.parent();
        }

        let picker = $(`
            <span class="input-group-append">
                <a href="#" class="btn btn-default btn-change-image">${ LOCALE.IMAGE_PICKER__BTN }</a>
            </span>
        `);
        picker.on('click', function (e) {
            e.preventDefault();

            let w = 800;
            let h = 600;
            let left = (screen.width / 2) - (w / 2);
            let top = (screen.height / 2) - (h / 2);

            window.imageSelectorInput = input;
            window.imageSelectorWindow = window.open(
                `/image?type=${imageType}&iframe`,
                '',
                `width=${w}, height=${h}, top=${top}, left=${left}`
            );
        });

        wrapper.addClass('input-group');
        wrapper.append(picker);
    });

    window.onSelectImage = (url) => {
        if (window.imageSelectorInput) {
            let urlPath;
            if (window.imageSelectorInput.attr('data-relative-url')) {
                urlPath = url;
            } else {
                urlPath = `${location.protocol}//${location.host}${url}`;
            }

            window.imageSelectorInput.val(urlPath).trigger('change');
        }

        if (window.imageSelectorWindow) {
            window.imageSelectorWindow.close();
        }

        window.imageSelectorInput = null;
        window.imageSelectorWindow = null;
    };
};
