{% macro render_field(field) %}
  {%- set css_class = kwargs.pop('class', '') %}
  {%- set error_css = '' %}
  {%- if field.flags.required %}
    {% set css_class = '{} required'.format(css_class) %}
  {%- endif %}
  {%- if field.errors %}
    {% set css_class = '{} has_error'.format(css_class) %}
    {%- set error_css = 'error' %}
  {%- endif %}
  <div class="control-group {{ error_css }}">
    {{ field.label(class="control-label"+error_css) }}
    <div class="controls">
        {{ field(class=css_class, **kwargs) }}
        {%- if field.errors %}
          <span class="help-inline">{% for error in field.errors %}{{ error|e }}. {% endfor %}</span>
        {%- endif %}
    </div>
  </div>
{% endmacro %}

<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 %}
        {{ render_field(form[field_name], widget_options=options.get(field_name, {})) }}
      {%- 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 cancel" 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 %}
