{% extends "colorbox/popup_form_base.html" %}
{% load i18n %}

{% block title %}{% trans "Edit fragments" %}{% endblock %}

{% block extra_head %}
    <script type="text/javascript">
    $(function() {
        $(document).bind('cbox_complete', function() {
            var extra_ids = {};
            parent.$(".coop-fragment-type").each(function (idx, elt) {
                $("select#fragment-types").append(
                  '<option value="' + $(elt).attr("rel") + '">' + $(elt).text() + '</option>'
                );
                extra_ids[$(elt).attr('rel')] = $(elt).attr('data-filter');
            });
            $("select#fragment-types").change(function () {
                var type_id = $(this).val();
                var extra_id = extra_ids[type_id];
                $("tr.field-row").hide();
                $("tr td.ft-id").each(function (idx, elt) {
                    var ff_id = $(elt).closest("tr").find("td.ff-id input").val();
                    if (extra_id && extra_id != '0') {
                        if ($(elt).find("input").val() == type_id && (extra_id == ff_id)) {
                            $(elt).closest("tr").show();
                            console.log('>', ff_id, extra_id)
                        }
                    } else {
                        if ($(elt).find("input").val() == type_id) {
                            $(elt).closest("tr").show();
                        }
                    }
                });
                parent.$.colorbox.resize();
            });
            $("select#fragment-types").change();

            $("select[multiple]").chosen();
            $(".chosen-container").css({width: '140px'});
            //$(".chosen-container input").css({width: '140px'});
        });
    });
    </script>
{% endblock %}

{% block form_url %}{% url "coop_cms_edit_fragments" %}{% endblock %}


{% block form_fields %}
<table class="popup_form">
    <select id="fragment-types">
        
    </select>
    {% for sub_form in form %}
        {% if forloop.counter0 == 0 %}
        <tr>
            {% for field in sub_form %}
                <th>{% if not field.is_hidden %}{{ field.label }}{% endif %}</th>
            {% endfor %}
        </tr>
        {% endif %}
        <tr class="field-row">
        {%  if sub_form.non_field_errors %}{{ sub_form.non_field_errors }}{% endif %}
        {% for field in sub_form %}
            <td class="{% if forloop.counter0 == 0 %}ft-id{% endif %}{% if forloop.counter0 == 1 %}ff-id{% endif %}">
                {{ field }}{{ field.errors }}
            </td>
        {% endfor %}
        </tr>
    {% endfor %}
    {{ form.management_form }}
</table>
{% endblock %}