{% from "macros/form.html" import  m_field with context %}

<form action="{{ request.path }}" method="POST" enctype="multipart/form-data" class="form-horizontal" id="edit-form" role="form">
  {{ form.csrf_token }}

  <div class="row">
    {%- set options = form._widgets_options|default({}) %}
    <div class="col-sm-3">
      <ul class="nav nav-pills nav-stacked" role="tablist">
        {%- for label, field_names in form._groups.items() %}
          {%- set label_id = label | toslug %}
          {%- set has_required = form._has_required
                                 and form._has_required(fields=field_names) %}
            {%- set error_count = form._count_errors
                                  and form._count_errors(fields=field_names) %}
          <li role="presentation" {%- if loop.first %} class="active"{%- endif %}>
            <a href="#{{ label_id }}" role="tab" data-toggle="tab">
              <span{% if has_required %} class="required"{%- endif %}>{{ label }}</span>
              {%- if error_count %}<span class="label label-danger pull-right">{{ error_count  }}</span>{%- endif %}
            </a>
          </li>
        {%- endfor %}
      </ul>
    </div>

    <div class="tab-content col-sm-9" id="form-panel">
      {%- for label, field_names in form._groups.items() %}
        {%- set label_id = label | toslug %}
        {%- set collapsed_state = 'active' if loop.first else '' %}
        <div id="{{ label_id }}" class="tab-pane {{ collapsed_state }}" role="tabpanel">
          <legend>{{ label }}</legend>
          {%- for field_name in field_names %}
            {%- set field = form[field_name] %}
            {%- if field.is_hidden %}
              {{ field() }}
            {%- else %}
              {{ m_field(form[field_name], horizontal=True, label_width=3, field_width=9) }}
            {%- endif %}
          {%- endfor %}
        </div>
      {% endfor %}
    </div>
  </div>

  <div class="row">
    <div class="form-actions col-sm-9 col-sm-push-3">
      <div class="row">
        <div class="col-sm-9 col-sm-push-3">
          {%- for button in g.view.buttons %}
            {{ button.render() }}
          {%- endfor %}
        </div>
      </div>
    </div>
  </div>

</form>

{%- deferJS %}
{%- if rules %}
  <script>
   $(document).ready(function() {
     var rules = {{ rules }};

     // Make bold labels for required fields
     $("label").each(function(i, e) {
       var for_ = $(e).attr("for");
       if (rules[for_] && rules[for_].required) {
         $(e).addClass("required");
       }
     });
   });
  </script>
{%- endif %}

{%- if form.js %}
  <script>
   $(document).ready(function() { {{ form.js|safe }} });
  </script>
{%- endif %}
{%- enddeferJS %}
