{% load i18n admin_urls static bootstrapped_goodies_tags %}
<div class="_inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
    <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2>
    {{ inline_admin_formset.formset.management_form }}
    {% if inline_admin_formset.formset.non_form_errors %}
        <div class="alert alert-danger">
            {{ inline_admin_formset.formset.non_form_errors }}
        </div>
    {% endif %}

    <div class="items">
        {% for inline_admin_form in inline_admin_formset %}
            <div class="well well-small inline-related{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}{% if forloop.last %} empty-form last-related{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
                <legend>
                    {% if not forloop.last %}
                        <a data-toggle="collapse" data-target="#{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %} > .collapse">
                    {% endif %}
                    {% if inline_admin_form.original %}{{ inline_admin_form.original }}{% if inline_admin_form.model_admin.show_change_link and inline_admin_form.model_admin.has_registered_model %} <a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="inlinechangelink">{% trans "Change" %}</a>{% endif %}{% else %}#{{ forloop.counter }}{% endif %} <small class="inline_label">({{ inline_admin_formset.opts.verbose_name|capfirst }})</small>
                    {% if not forloop.last %}
                        <span class="btn btn-default btn-xs"><i class="glyphicon glyphicon-resize-full"></i></span>
                        {% if inline_admin_formset.opts.sortable_field_name %}
                            <span class="btn btn-default btn-xs drag-handler"><i class="glyphicon glyphicon-move"></i></span>
                        {% endif %}
                        </a>
                    {% endif %}
                    {% if inline_admin_form.show_url %}<a href="{{ inline_admin_form.absolute_url }}">{% trans "View on site" %}</a>{% endif %}
                    <div class="pull-right">
                        {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<div class="delete control-group"><div class="checkbox">{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}</div></div>{% endif %}
                    </div>
                </legend>
                {% for fieldset in inline_admin_form %}{% for line in fieldset %}
                    {% if line.errors %}
                        {% for field in line %}
                            <div class="alert alert-danger"><strong>{{ field.field.label }}:</strong> {{ field.errors|striptags }}</div>
                        {% endfor %}
                    {% endif %}
                {% endfor %}{% endfor %}

                <div class="{% if not forloop.last %}collapse{% endif %}{% if not inline_admin_formset.opts.start_collapsed %} in{% endif %}">
                    {% if inline_admin_form.form.non_field_errors %}
                        <div class="alert alert-danger">
                            {{ inline_admin_form.form.non_field_errors }}
                        </div>
                    {% endif %}
                    {% with stacked_prefix=forloop.counter %}
                        {% for fieldset in inline_admin_form %}
                            {% include "admin/includes/fieldset.html" with group_column_width=fieldset|fieldset_column_width %}
                        {% endfor %}
                    {% endwith %}
                    {% if inline_admin_form.needs_explicit_pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
                    {{ inline_admin_form.fk_field.field }}
                </div>
            </div>
        {% endfor %}
    </div>
</div>

<script type="text/javascript">
    window.addEventListener("load", function() {
        (function($) {
            $(document).ready(function() {
                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 "admin/" %}");
                        });
                        $(".selectfilterstacked").each(function(index, value){
                            var namearr = value.name.split('-');
                            SelectFilter.init(value.id, namearr[namearr.length-1], true, "{% static "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('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
                        });
                        if (dependencies.length) {
                            input.prepopulate(dependencies, input.attr('maxlength'));
                        }
                    });
                };
                $(rows).formset({
                    prefix: "{{ inline_admin_formset.formset.prefix }}",
                    addText: "<span class='btn'><i class='glyphicon glyphicon-plus'></i> {% blocktrans with verbose_name=inline_admin_formset.opts.verbose_name|capfirst %}Add another {{ verbose_name }}{% endblocktrans %}</span>",
                    formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}",
                    deleteCssClass: "inline-deletelink",
                    deleteText: "{% trans "Remove" %}",
                    emptyCssClass: "empty-form",
                    removed: updateInlineLabel,
                    added: (function(row) {
                        initPrepopulatedFields(row);
                        reinitDateTimeShortCuts();
                        updateSelectFilter();
                        updateInlineLabel(row);
                    })
                });


            });
        })($);
    });

// listener for jquery 1.7.2
    (function($) {
        {% if inline_admin_formset.opts.sortable_field_name %}
            $('.items').sortable({
                handle: '.drag-handler',
                items: ".dynamic-{{ inline_admin_formset.formset.prefix }}:not(:last:visible)"
            });
            $("#{{ opts.model_name }}_form").submit(function(e) {
                var sortable_field_name = "{{ inline_admin_formset.opts.sortable_field_name }}",
                    i = 0;
                var initial_form_count = $('#id_{{ inline_admin_formset.formset.prefix }}-INITIAL_FORMS').val();

                $('#{{ inline_admin_formset.formset.prefix }}-group > .items').find(".dynamic-{{ inline_admin_formset.formset.prefix }}").each(function(i, e) {
            // make sure we don't assign a position unless extra has been moved
                    if ($(this).find("input[name$='" + sortable_field_name + "']").val() || (i <= initial_form_count - 1 )) {
                        $(this).find("input[name$='" + sortable_field_name + "']").val(i);
                        i++;
                    }
                });
            });
        {% endif %}
    })(jQuery);
</script>
