{% extends "base.html" %}
{% load sekizai_tags i18n %}

{% block base_content %}

  <div class="jumbotron">
    <h1 class="display-3 text-center">{% block page_title %}{% endblock %}</h1>
  </div>

  <div class="container">
    {% if messages %}
      <div class="messages">
        {% for message in messages %}
          <div class="alert{% if message.tags %} alert-{{ message.tags }}{% endif %}">{{ message }}</li>
        {% endfor %}
      </div>
    {% endif %}

    {% block content %}{% endblock %}
  </div>

  {% addtoblock "js" %}
    <script>

      // Helpers to display or remove form errors using jQuery.
      var removeFormErrors = function ($form) {
        $form.find('.non-field-errors,.form-control-feedback').remove();
        $form.find('.has-danger').removeClass('has-danger');
      }

      var displayFormErrors = function ($form, errors) {
        removeFormErrors($form);

        $.each(errors, function (name, errorlist) {
          if (name === 'non_field_errors') {
            $form.prepend('<div class="non-field-errors alert alert-danger">'+ errorlist.join('<br>') +'</div>');
          } else {
            var $field = $form.find('#id_'+ name);
            var type = $field.attr('type');

            if (type === 'checkbox') {
              $field.parent().parent().addClass('has-danger');
            } else {
              $field.parent().addClass('has-danger');
              $field.after('<div class="form-control-feedback">'+ errorlist.join('<br>') +'</div>');
            }
          }
        });
      };

      (function ($) {
        'use strict';

        $(document).ready(function () {

          // Handle ajax forms.
          $('form[data-ajax-success]').each(function () {
            var $form = $(this);
            var $formButton = $form.find('button');
            var successUrl = $form.attr('data-ajax-success');

            $form.on('submit', function (event) {
              event.preventDefault();
              $formButton.prop('disabled', true);

              $.ajax({
                url: $form.attr('action'),
                method: $form.attr('method'),
                data: $form.serialize(),
                dataType: 'json',
                cache: false,
                success: function (data) { window.location.href = successUrl; },
                error: function (jqXHR) {
                  $formButton.prop('disabled', false);
                  displayFormErrors($form, jqXHR.responseJSON);
                },
              });
            });
          });

        });
      })(jQuery);
    </script>
  {% endaddtoblock %}
{% endblock %}
