{% extends "newman/change_form.html" %}
{% load newman_modify cache i18n %}

{% block content %}

<form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="." method="post" id="{{ opts.module_name }}_form" class="change-form">{% block form_top %}{% endblock %}
<div>
    <div class="js-textarea-toolbar"></div>
{% if errors %}
    <p class="errornote">
    {% blocktrans count errors|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
    </p>
    <ul class="errorlist">{% for error in adminform.form.non_field_errors %}<li>{{ error }}</li>{% endfor %}</ul>
{% endif %}

{% block fieldsets %}
{% for fieldset in adminform %}
  {% include "newman/includes/fieldset.html" %}
{% endfor %}
{% endblock %}


<div class="submit-row">
    <a id="start-upload" class="js-submit icn btn save def default-button-ok" name="_save">{% trans "Upload photos" %}</a>
</div>

</div>

</form>

{% endblock %}

{% block content_js %}
    <script type="text/javascript">
        function initialize_mass_upload() {
            var $uploadifyTarget = $('#id_image_file');
            var originalObjectId = null;
            var index = 1;
            
            function getFormData() {
                var formData = $('form').serializeObject();
                formData.title = formData.title + ' ' + index ;
                formData.slug = formData.slug + '-' + index; 
                console.log('Appending data to send along with upload:' + JSON.stringify(formData));
                $uploadifyTarget.uploadifySettings('scriptData', formData, true);
            }
            
            $uploadifyTarget.data('photos', [])
            $uploadifyTarget.uploadify({
                'uploader'       : '{{ NEWMAN_MEDIA_URL }}swf/uploadify.swf',
                'script'         : '{% url newman:photo-mass-upload-file %}',
                'cancelImg'      : '{{ NEWMAN_MEDIA_URL }}img/cancel.png',
                'buttonText'     : '{% trans "Choose images" %}',
                'fileExt'        : '*.png;*.jpg;*.jpeg',
                'fileDesc'       : '{% trans "Image files (*.png, *.jpg, *.jpeg)" %}',
                'fileDataName'   : 'image_file',
                'multi'          : true,
                'onError'        : function (event, ID, fileObj, errorObj) {
                    $uploadifyTarget.uploadifyClearQueue();
                    console.log(ID);
                    console.log(fileObj);
                    console.log(errorObj);
                    console.log(event);
                    show_err('{% trans "Photo upload failed. Check for form errors." %}');
                },
                'onComplete': function (event, ID, fileObj, raw_response, data) {
                    index++;
                    try {
                        response = JSON.parse(raw_response);
                        $uploadifyTarget.data('photos').push({
                            id:   response.data.object_id,
                            title: response.data.object_title
                        });
                    } catch(e) {
                        console.log("Failed to parse object_id and object_title from response:", raw_response, e);
                    }
                    $uploadifyTarget.uploadifySettings('scriptData', getFormData(), true);
                },
                'onAllComplete': function (event, data) {
                    show_ok('{% trans "All images have been uploaded." %}');
                    // This is a custom form, thus default newman callbacks are not called.
                    // Call save callback of ajax form action table as if handling a normal
                    // newman save button to return to proper page.
                    // The photos' IDs and titles (superfluous atm) are passed so the
                    // photos can be automatically added to gallery, as done in
                    // related_lookup.js.
                    new PostsaveActionTable({
                        photos: $uploadifyTarget.data('photos')
                    }).run('_save');
                }
            });
            
            function startUpload () {
                AjaxFormLib.clean_inputs_with_files($('form'));
                $uploadifyTarget.uploadifySettings('scriptData', getFormData(), true);
                $uploadifyTarget.uploadifyUpload();                
            }
            
            $('#start-upload').unbind('click').click(startUpload);
        }

        function trigger_changelist_shown() {
            $(document).trigger('changeform_shown'); // bound in inlines.js
        }

        request_media(MEDIA_URL + 'js/markitup/skins/markitup/style.css');
        request_media(MEDIA_URL + 'js/markitup/sets/markdown/style.css');
        request_media(MEDIA_URL + 'jquery/jquery-ui-smoothness.css');
        request_media(MEDIA_URL + 'css/fuckitup_extensions/markdown_tables.css');
        request_media(MEDIA_URL + 'css/generic.suggest.css');
        request_media(MEDIA_URL + 'css/uploadify.css');
        request_media(MEDIA_URL + 'js/fuckitup.js');
        request_media(MEDIA_URL + 'js/fuckitup_install.js');
        request_media(MEDIA_URL + 'jquery/jquery-ui.js');
        request_media(MEDIA_URL + 'jquery/jquery-fieldselection.js');
        request_media(MEDIA_URL + 'jquery/jquery.autogrow.js');
        request_media(MEDIA_URL + 'js/fuckitup_extensions/markdown_extras_tables.js');
        request_media(MEDIA_URL + 'js/related_lookup.js');
        request_media(MEDIA_URL + 'js/generic.suggest.js');
        request_media(MEDIA_URL + 'js/swfobject.js');
        request_media(MEDIA_URL + 'js/jquery.uploadify.min.js');

        $(document).one('media_loaded', trigger_changelist_shown);
        $(document).one('media_loaded', initialize_mass_upload);
    </script>
{% endblock %}
