{% extends "base.html" %}

{% block stylesheets %}
  {{ super() }}
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-datetimepicker.min.css') }}" />
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-select.min.css') }}" />
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-tagsinput.css') }}" />
{% endblock %}

{% block scripts %}
  {{ super() }}
  <script src="{{ url_for('static', filename='js/moment-with-locales.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/bootstrap-datetimepicker.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/bootstrap-select.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/bootstrap-tagsinput.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/typeahead.bundle.min.js') }}"></script>
{% if config['LOAD_OBJECTS_IN_BACKGROUND'] %}
  <script src="{{ url_for('static', filename='js/sampledb-load-objects.js') }}"></script>
{% endif %}
<script type="text/javascript">
    $(function () {
        $('.input-group.date').each(function() {
          $(this).datetimepicker({
            format: 'YYYY-MM-DD HH:mm:ss',
            date: $(this).attr('data-datetime')
          });
        });
    });

  var tags = new Bloodhound({
    initialize: true,
    local: {{ tags | tojson }},
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace
  });
  $('input[name^=\'object__\'][name$=\'__tags\']').each(function() {
    var tagsinput = $(this);
    tagsinput.tagsinput({
      trimValue: true,
      typeaheadjs: {
        name: 'Tags',
        valueKey: 'name',
        displayKey: 'name',
        source: tags.ttAdapter(),
        templates: {
          'suggestion': function(item) {return '<div>' + item.name + ' (×' + item.uses + ')' + '</div>'}
        }
      }
    });
    tagsinput.on('beforeItemAdd', function(event) {
      var sanitized_tag = event.item.toLowerCase().replace(/\s/g,'').replace(/[^a-z0-9_\-äüöß]/g,'');
      if (event.item !== sanitized_tag) {
        if (!event.options || !event.options.fromHandler) {
          event.cancel = true;
          $(this).tagsinput('add', sanitized_tag, {fromHandler: true});
        }
      }
    });
    $(tagsinput.tagsinput('input')).on('blur', function() {
      var item = $(this).tagsinput('input').val();
      $(this).tagsinput('input').val('');
      item = item.trim();
      if (item) {
        $(this).tagsinput('add', item);
      }
    }.bind(tagsinput));
  });

</script>
{% endblock %}
