{% extends "wagtailadmin/base.html" %}
{% load wagtailimages_tags %}
{% load i18n %}
{% block titletag %}{% trans "Add an image" %}{% endblock %}

{% block extra_js %}
    {{ block.super }}

    {{ form.media.js }}

    {% url 'wagtailadmin_tag_autocomplete' as autocomplete_url %}
    <script>
        $(function() {
            $('#id_file').on(
                'change',
                function() {
                    var $titleField = $('#id_title');

                    // do not override a title that already exists (from manual editing or previous upload)
                    if ($titleField.val()) return;

                    // file widget value example: `C:\fakepath\image.jpg` - convert to just the filename part
                    var filename = $(this).val().split('\\').slice(-1)[0];
                    var data = { title: filename.replace(/\.[^.]+$/, '') };
                    var maxTitleLength = parseInt($titleField.attr('maxLength') || '0', 10) || null;

                    // allow an event handler to customise data or call event.preventDefault to stop any title pre-filling
                    var form = $(this).closest('form').get(0);
                    var event = form.dispatchEvent(new CustomEvent(
                        'wagtail:images-upload',
                        { bubbles: true, cancelable: true, detail: { data: data, filename: filename, maxTitleLength: maxTitleLength } }
                    ));

                    if (!event) return; // do not set a title if event.preventDefault(); is called by handler

                    $titleField.val(data.title);
                }
            );
            $('#id_tags').tagit({
                autocomplete: {source: "{{ autocomplete_url|addslashes }}"}
            });
        });
    </script>
{% endblock %}

{% block extra_css %}
    {{ block.super }}
    {{ form.media.css }}
{% endblock %}

{% block content %}
    {% trans "Add image" as add_str %}
    {% include "wagtailadmin/shared/header.html" with title=add_str icon="image" %}

    <div class="nice-padding">
        {% include "wagtailadmin/shared/non_field_errors.html" %}

        <form action="{% url 'wagtailimages:add' %}" method="POST" enctype="multipart/form-data" novalidate>
            {% csrf_token %}
            <ul class="fields">
                {% for field in form %}
                    {% if field.is_hidden %}
                        {{ field }}
                    {% else %}
                        {% include "wagtailadmin/shared/field_as_li.html" with field=field %}
                    {% endif %}
                {% endfor %}
                <li><input type="submit" value="{% trans 'Save' %}" class="button" /></li>
            </ul>
        </form>
    </div>
{% endblock %}
