{% load i18n %}

<div class="inline-group clearfix" id="{{ inline_admin_formset.formset.prefix }}-group">
  <h2>{{ inline_admin_formset.opts.verbose_name_plural|title }}</h2>
{{ inline_admin_formset.formset.management_form }}
{{ inline_admin_formset.formset.non_form_errors }}
<div id="sort-container">
{% for inline_admin_form in inline_admin_formset %}<div class="inline-related gallery-image{% if forloop.last %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
      {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<p class="delete absolute">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</p>{% endif %}

  {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %}

      {% for fieldset in inline_admin_form %}
        {% include "admin/gallery/gallery/fieldset.html" %}
      {% endfor %}
      {% if inline_admin_form.pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
      {{ inline_admin_form.fk_field.field }}

  </div>{% endfor %}
  <div class="clear"></div>
</div>
</div>

<script type="text/javascript">

$ = django.jQuery;

(function($) {
    $(document).ready(function() {
        $( "#sort-container" ).sortable({
                containment: $('#sort-container'),
                stop: function() {
                    $(this).find('div.inline-related').each(function(i) {
                        if ($(this).find('.vIntegerField').val()) {    
                            $(this).find('input[id$=ordering]').val(i+1);
                        }
                    });
               }
            });
        $( "#gallery_mediafile_set-group" ).disableSelection();
        var rows = "#{{ inline_admin_formset.formset.prefix }}-group .inline-related";
        var updateInlineLabel = function(row) {
            $(rows).find(".inline_label").each(function(i) {
                var count = i + 1;
                $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
            });
        }
        var reinitDateTimeShortCuts = function() {
            // Reinitialize the calendar and clock widgets by force, yuck.
            if (typeof DateTimeShortcuts != "undefined") {
                $(".datetimeshortcuts").remove();
                DateTimeShortcuts.init();
            }
        }
        var updateSelectFilter = function() {
            // If any SelectFilter widgets were added, instantiate a new instance.
            if (typeof SelectFilter != "undefined"){
                $(".selectfilter").each(function(index, value){
                  var namearr = value.name.split('-');
                  SelectFilter.init(value.id, namearr[namearr.length-1], false, "{{ STATIC_URL }}admin/");
                })
                $(".selectfilterstacked").each(function(index, value){
                  var namearr = value.name.split('-');
                  SelectFilter.init(value.id, namearr[namearr.length-1], true, "{{ STATIC_URL }}admin/");
                })
            }
        }
        var initPrepopulatedFields = function(row) {
            row.find('.prepopulated_field').each(function() {
                var field = $(this);
                var input = field.find('input, select, textarea');
                var dependency_list = input.data('dependency_list') || [];
                var dependencies = [];
                $.each(dependency_list, function(i, field_name) {
                  dependencies.push('#' + row.find(field_name).find('input, select, textarea').attr('id'));
                });
                if (dependencies.length) {
                    input.prepopulate(dependencies, input.attr('maxlength'));
                }
            });
        }
		// fix span ID due to Django bug.
		var fixId = function(row){
			if(row.find('.lupe.mediafile').prev('input').attr('id') != row.find('.lupe.mediafile').attr('id').substr(7)) {
				var wrongId = row.find('.lupe.mediafile').attr('id');
				var correctId = wrongId.replace(/(\d+)/, function(a,n){return (+n-1);});
				row.find('.lupe.mediafile').attr('id', correctId);
			}
		}
		var chooseImage = function(row){
			row.find('span.lupe.mediafile').trigger('click');
		}
        $(rows).formset({
            prefix: "{{ inline_admin_formset.formset.prefix }}",
            addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}",
            formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}",
            deleteCssClass: "inline-deletelink",
            deleteText: "{% trans "Remove" %}",
            emptyCssClass: "empty-form",
            removed: updateInlineLabel,
            added: (function(row) {
				fixId(row);
                initPrepopulatedFields(row);
                reinitDateTimeShortCuts();
                updateSelectFilter();
                updateInlineLabel(row);
				chooseImage(row);
            })
        });
    });
})(django.jQuery);
</script>
