{% 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">
  {{ form.csrf_token }}

  {%- set options = form._widgets_options|default({}) %}
  {%- for label, field_names in form._groups %}
    {%- if label %}<legend>{{ label }}</legend>{%- endif %}
    <fieldset>
      {%- for field_name in field_names %}
        {{ m_field(form[field_name], horizontal=True, label_width=3, field_width=6) }}
      {%- endfor %}
    </fieldset>
  {% endfor %}

  <div class="form-actions">
    {%- if for_new %}
      <button type="submit" class="btn btn-primary" name="_action" value="add">{{ _("Add new") }}</button>
      {%- if has_save_and_add_new %}
        <button type="submit" class="btn btn-info" name="_action" value="save_and_add_new">{{ _("Save and add new") }}</button>
      {%- endif %}
    {%- else %}
      <button type="submit" class="btn btn-primary" name="_action" value="save">{{ _("Save changes") }}</button>
    {%- endif %}
    <button type="submit" class="btn btn-default" name="_action" value="cancel">{{ _("Cancel") }}</button>    
  </div>

</form>

{% 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");
      }
    });

    // Activate valitation plugin
    $("#edit-form").validate({
      /* debug: true, */
      rules: rules,
      highlight: function(label) {
        $(label).closest('.control-group').addClass('error');
      },
      unhighlight: function(label) {
        $(label).closest('.control-group').removeClass('error');
      }
    });
  });
</script>
{% endif %}

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