{# Renders field for bootstrap 3 standards.

    Params:
        field - WTForm field
        kwargs - pass any arguments you want in order to put them into the html attributes.
        There are few exceptions: for - for_, class - class_, class__ - class_

    Example usage:
        {{ macros.render_field(form.email, placeholder='Input email', type='email') }}
#}
{% macro render_field(field, label_visible=true) -%}

    <div class="form-group {% if field.errors %}has-error{% endif %} {{ kwargs.pop('class_', '') }}">
        {% if (field.id != 'csrf_token' or field.type != 'HiddenField') %}
            <label for="{{ field.id }}" class="control-label">{{ field.label }}</label>
        {% endif %}
        {{ field(class_='form-control', **kwargs) }}
        {% if field.errors %}
            {% for e in field.errors %}
                <p class="help-block">{{ e }}</p>
            {% endfor %}
        {% endif %}
    </div>
{%- endmacro %}

{# Renders checkbox fields since they are represented differently in bootstrap
    Params:
        field - WTForm field (there are no check, but you should put here only BooleanField.
        kwargs - pass any arguments you want in order to put them into the html attributes.
        There are few exceptions: for - for_, class - class_, class__ - class_

    Example usage:
        {{ macros.render_checkbox_field(form.remember_me) }}
 #}
{% macro render_checkbox_field(field) -%}
    <div class="checkbox">
        <label>
            {{ field(type='checkbox', **kwargs) }} {{ field.label }}
        </label>
    </div>
{%- endmacro %}

{# Renders radio field
    Params:
        field - WTForm field (there are no check, but you should put here only BooleanField.
        kwargs - pass any arguments you want in order to put them into the html attributes.
        There are few exceptions: for - for_, class - class_, class__ - class_

    Example usage:
        {{ macros.render_radio_field(form.answers) }}
 #}
{% macro render_radio_field(field) -%}
    {% for value, label, _ in field.iter_choices() %}
        <div class="radio">
            <label>
                <input type="radio" name="{{ field.id }}" id="{{ field.id }}" value="{{ value }}">{{ label }}
            </label>
        </div>
    {% endfor %}
{%- endmacro %}

{# Renders WTForm in bootstrap way. There are two ways to call function:
     - as macros: it will render all field forms using cycle to iterate over them
     - as call: it will insert form fields as you specify:
     e.g. {% call macros.render_form(form, action_url=url_for('view.login_view'), action_text='Login',
                                        class_='login-form') %}
                {{ macros.render_field(form.email, placeholder='Input email', type='email') }}
                {{ macros.render_field(form.password, placeholder='Input password', type='password') }}
                {{ macros.render_checkbox_field(form.remember_me, type='checkbox') }}
            {% endcall %}

     Params:
        form - WTForm class
        action_url - url where to submit this form
        action_text - text of submit button
        class_ - sets a class for form
    #}
{% macro render_form(form, action_url='', action_text='Submit', class_='', btn_class='btn btn-success') -%}

    <form method="POST" action="{{ action_url }}" role="form" class="{{ class_ }}">
        {{ form.hidden_tag() if form.hidden_tag }}
        {% if caller %}
            {{ caller() }}
        {% else %}
            {% for f in form %}
                {% if f.type == 'BooleanField' %}
                    {{ render_checkbox_field(f) }}
                {% elif f.type == 'RadioField' %}
                    {{ render_radio_field(f) }}
                {% elif f.type == 'SelectField' %}
                    {{ render_select_field(f) }}
                {% else %}
                    {{ render_field(f) }}
                {% endif %}
            {% endfor %}
        {% endif %}
        <button type="submit" class="{{ btn_class }}">{{ action_text }} </button>
    </form>
{%- endmacro %}

{% macro smooth_scrolling() -%}
// Add a smooth scrolling to anchor
$(document).ready(function() {
	$('a.scroll').click(function() {
		var target = $(this.hash);
		if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
		if (target.length == 0) target = $('html');
		$('html, body').animate({ scrollTop: target.offset().top }, 500);
		return false;
	});
	$(".dropdown-menu label, .dropdown-menu input, .dropdown-menu li").click(function(e) {
		e.stopPropagation();
	});
});
{%- endmacro %}

{# Loads the datatable translation if needed #}
{% macro translate_datatable() -%}
  language: {
  {% if g.locale and g.locale != 'en' -%}
    url: '{{ url_for("static", filename="extra/i18n/datatable-{}.json".format(g.locale)) }}',
  {% endif -%}
    select: {
      rows: {
        _: '{{ _("You have selected %%d rows") }}',
        0: '<br />{{ _("Click a row to select it (hold ctrl to select several)") }}',
        1: '{{ _("You have selected 1 row") }}'
      },
    },
    buttons: {
      'selectAll': '{{ _("Select all") }}&nbsp;<i class="fa fa-check-square-o" aria-hidden="true"></i>',
      'selectNone': '{{ _("Deselect all") }}&nbsp;<i class="fa fa-square-o" aria-hidden="true"></i>',
    }
  },
{%- endmacro %}

{# Enables the calendar translation if needed #}
{% macro translate_calendar() -%}
  {% if g.locale and g.locale != 'en' -%}
  locale: {{ g.locale|tojson }},
  {% endif -%}
{%- endmacro %}

{# Record number of elements to display #}
{% macro page_length(selector) -%}
$('{{ selector }}').on('length.dt', function(e, settings, len) {
  $.post( '{{ url_for("api.prefs_ui") }}', {pageLength: len} );
});
{%- endmacro %}

{# Set number of elements to display #}
{% macro get_page_length() -%}
  {% if session.pageLength -%}
  pageLength: {{ session.pageLength }},
  {% endif -%}
{%- endmacro %}

{# Register a new filter for datatables dates #}
{% macro timestamp_filter() -%}
// extends DataTables sorting
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
  "timestamp-pre": function ( a ) {
    var $obj = $(a);
    var title = $obj.attr('title');
    if (typeof title !== typeof undefined && title !== false)
      return moment(title, moment.ISO_8601).valueOf();
    return moment().valueOf();
  },
  "timestamp-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },
  "timestamp-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
} );
{%- endmacro %}
