{% extends "base.html" %}

{% block title %}{{ _('Instrument') }} #{{ instrument.id }}: {{ single_instrument_translation.name }} — {{ service_name }}{% endblock %}

{% block content %}
  <h1>{{ _('Instrument') }} #{{ instrument.id }}: {{ single_instrument_translation.name }}</h1>
  {% if instrument.is_hidden %}
  <p class="text-muted"><i class="fa fa-eye-slash" aria-hidden="true"></i> {{ _('This instrument has been hidden from instrument lists.')}}</p>
  {% endif %}
  {% if single_instrument_translation.description %}
    <div class="instrument-user-content">
      {% if instrument.description_is_markdown %}{{ single_instrument_translation.description | markdown_to_safe_html(anchor_prefix='instrument-description') | safe }}{% else %}<p>{{ single_instrument_translation.description }}</p>{% endif %}
    </div>
  {% endif %}
  {% include "instruments/instrument_scientists.html" %}
  {% if not current_user.is_readonly %}
    {% if current_user.is_admin or current_user in instrument.responsible_users %}
      <a href="{{ url_for('.edit_instrument', instrument_id=instrument.id) }}" class="btn btn-default">{{ _('Edit Instrument') }}</a>
    {% endif %}
  {% endif %}
  {% if instrument.actions %}
  <h2>{{ _('Actions') }}</h2>
  {% for action in instrument.actions %}
    {% if not action.is_hidden or current_user.is_admin %}
      <h3><a href="{{ url_for('.action', action_id=action.id) }}" title="{{ action_translations[action.id].name }}"> {{ action_translations[action.id].name }}</a></h3>
      {% if action_translations[action.id].short_description %}
        <div class="action-user-content">
          {% if action.short_description_is_markdown %}{{ action_translations[action.id].short_description | markdown_to_safe_html(anchor_prefix='action-short-description') | safe }}{% else %}<p>{{ action_translations[action.id].short_description }}</p>{% endif %}
        </div>
      {% endif %}
      <a href="{{ url_for('.objects', action=action.id) }}" class="btn btn-default">{{ get_action_type_translation_for_action_type_in_language(action.type_id, get_user_language(current_user).id, True).view_text }}</a>
      {% if not current_user.is_readonly %}
        <a href="{{ url_for('.new_object', action_id=action.id) }}" class="btn btn-primary">{{ get_action_type_translation_for_action_type_in_language(action.type_id, get_user_language(current_user).id, True).perform_text}}</a>
      {% endif %}
    {% endif %}
  {% endfor %}
  {% endif %}
  {% if is_instrument_responsible_user %}
  <h2>{{ _('Instrument Scientist Notes')}}</h2>
    <p class="text-muted">
      {{ _('These notes are only visible to the instrument scientists.')}}
      <a href="https://scientific-it-systems.iffgit.fz-juelich.de/SampleDB/user_guide/instruments.html#instrument-scientist-notes">{{ _('Read more.')}}</a>
    </p>
  {% with ns = namespace() %}
  {% set ns.has_notes = False %}
  {% for translation in instrument_translations %}
    {% if translation.notes %}
      {% set ns.has_notes = True %}
      <div class="instrument-user-content">
      <h2>{{ translation.language.names | get_translated_text }}</h2>
      {% if instrument.notes_is_markdown %}{{ translation.notes | markdown_to_safe_html(anchor_prefix='instrument-notes') | safe }}{% else %}<p>{{ translation.notes }}</p>{% endif %}
      </div>
    {% endif %}
  {% endfor %}
  {% if not ns.has_notes %}
    &mdash;
  {% endif %}
  {% endwith %}
  {% endif %}
  {% if is_instrument_responsible_user or instrument.users_can_create_log_entries or instrument.users_can_view_log_entries %}
    <h2>{{ _('Instrument Log')}}</h2>
    <p class="text-muted">
      {% if is_instrument_responsible_user %}
        {{ _('Instrument scientists can use the instrument log to keep track of problems, maintenance or other events.') }}
        {{ _('Instrument scientists can <a href="%(edit_url)s">edit the instrument settings</a> to configure whether users can create or view log entries.', edit_url=url_for('.edit_instrument', instrument_id=instrument.id)) }}
        {% if instrument.users_can_view_log_entries and instrument.users_can_create_log_entries %}
          {{ _('Currently, users can create and view log entries.') }}
        {% elif instrument.users_can_create_log_entries %}
          {{ _('Currently, users cannot view log entries, but they can create new entries.') }}
        {% elif instrument.users_can_view_log_entries %}
          {{ _('Currently, users can view log entries, but they cannot create new entries.') }}
        {% else %}
          {{ _('Currently, users can neither create nor view log entries.') }}
        {% endif %}
      {% else %}
        {% if instrument.users_can_view_log_entries %}
          {{ _('Instrument scientists can use the instrument log to keep track of problems, maintenance or other events.') }}
        {% endif %}
        {% if instrument.users_can_create_log_entries %}
          {{ _('Users can create entries in the instrument log to notify instrument scientists about any issues they encounter.') }}
        {% endif %}
      {% endif %}
      <a href="https://scientific-it-systems.iffgit.fz-juelich.de/SampleDB/user_guide/instruments.html#instrument-log">{{ _('Read more.')}}</a>
    </p>
    {% if is_instrument_responsible_user or instrument.users_can_view_log_entries %}
      {% if instrument_log_entries %}
        <div style="margin-bottom: 10px;">
          {% if not current_user.is_readonly and (is_instrument_responsible_user or instrument.users_can_create_log_entries) %}
            <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#newLogEntryModal" style="height:32px">
              <i class="fa fa-comment-o fa-fw"></i> {{ _('Create Log Entry') }}
            </button>
            <button type="button" class="btn btn-sm btn-default" data-toggle="modal" data-target="#mobileFileLinkModal" style="height:32px">
              <i class="fa fa-mobile-phone fa-fw"></i> {{ _('Smartphone Upload as Log Entry') }}
            </button>
          {% endif %}
        </div>
          <div class="text-right instrument-log-control-buttons">
          <button type="button" class="btn btn-sm btn-primary button-show-instrument-log-list" style="height:32px" disabled="disabled">
            {{ _('View as list') }}
          </button>
          <button type="button" class="btn btn-sm btn-primary button-show-instrument-log-tree-date-author" style="height:32px">
            {{ _('View as tree (Date, Author)') }}
          </button>
          <button type="button" class="btn btn-sm btn-primary button-show-instrument-log-tree-author-date" style="height:32px">
            {{ _('View as tree (Author, Date)') }}
          </button>
          <button type="button" class="btn btn-sm btn-primary button-switch-instrument-log-order" style="height:32px" id="button-switch-instrument-log-order-date">
            {{ _('Sort by date') }}
            <i class="fa {% if instrument_log_order_ascending %}fa-sort-asc{% else %}fa-sort-desc{% endif %}" style="{% if instrument_log_order_attribute != "datetime" %}visibility: hidden{% endif %}"></i>
          </button>
          <button type="button" class="btn btn-sm btn-primary button-switch-instrument-log-order" style="height:32px" id="button-switch-instrument-log-order-user-name">
            {{ _('Sort by author') }}
            <i class="fa {% if instrument_log_order_ascending %}fa-sort-asc{% else %}fa-sort-desc{% endif %}" style="{% if instrument_log_order_attribute != "username" %}visibility: hidden{% endif %}"></i>
          </button>
          <form class="hidden" id="form-instrument-log-order">
            {{ instrument_log_order_form.hidden_tag() }}
            <input type="checkbox" name="{{ instrument_log_order_form.ascending.name }}" />
            <input type="text" name="{{ instrument_log_order_form.attribute.name }}" />
          </form>
          <button type="button" id="button-instrument-log-list-filter" class="btn btn-sm btn-primary" style="height:32px" data-container="body" data-toggle="popover" data-placement="left" data-html="true" data-content="
            {% for category in instrument_log_categories %}
              <label style='font-weight:400'><input type='checkbox' id='instrument_log_filter_{{ category.id }}' onclick='update_instrument_log_filter_states();'/> {{ category.title }}</label><br />
            {% endfor %}
              <label style='font-weight:400'><input type='checkbox' id='instrument_log_filter_none' onclick='update_instrument_log_filter_states();'/> {{ _('Uncategorized') }}</label><br />
              <hr />
              <div class='input-group date'>
                  <input type='text' class='form-control' id='input-instrument-log-filter-date'/>
                  <span class='input-group-addon'>
                      <span class='glyphicon glyphicon-calendar'></span>
                  </span>
              </div>
              <hr />
              <div class='form-group'>
              <select class='selectpicker' id='input-instrument-log-filter-user' data-width='100%'>
              <option value='' selected='selected'>{{ _('All users') }}</option>
              {% for user in instrument_log_users %}
                <option value='{{ user.id }}'>{{ user.name }} (#{{ user.id }})</option>
              {% endfor %}
              </select>
              </div>
              <script>
                setup_instrument_log_filter_states();
              </script>
            ">
              <i class="fa fa-filter" style="font-size: 1.5rem"></i> <span class="badge" id="instrument_log_counter"></span>
            </button>
          </div>
        <div id="instrument-log-container">
        {% for log_entry in instrument_log_entries %}
          <div>
          <input type="checkbox" id="instrument-log-show-versions-{{ log_entry.id }}" class="instrument-log-show-versions"/>
          <div class="well instrument-log-entry {% if log_entry.versions[-1].categories %}instrument-log-entry-{{ log_entry.versions[-1].categories[-1].theme.name.lower() }}{% endif %}" {% if log_entry.versions[-1].categories %}{% for category in log_entry.versions[-1].categories %}data-instrument-log-category-{{ category.id }}="yes" {% endfor %}{% else %}data-instrument-log-category-none="yes"{% endif %} id="log_entry-{{ log_entry.id }}" data-instrument-log-date="{{ (log_entry.versions[-1].event_utc_datetime or log_entry.versions[0].utc_datetime).strftime("%Y-%m") }}" data-instrument-log-datetime="{{ (log_entry.versions[-1].event_utc_datetime or log_entry.versions[0].utc_datetime).isoformat() }}" data-instrument-log-user-id="{{ log_entry.author.id }}" data-instrument-log-user-name="{{ log_entry.author.name }} (#{{ log_entry.author.id }})" style="position: relative">
            <div class="instrument-log-categories">
              {% for category in log_entry.versions[-1].categories %}
                  <span class="instrument-log-category-{{ category.theme.name.lower() }}">{{ category.title }}</span>
              {% endfor %}
            </div>
            {% if log_entry.versions[-1].event_utc_datetime %}
              <div class="text-right"><span data-toggle="tooltip" data-placement="bottom" title="{{ _('This log entry refers to an event that occurred at this date and time.') }}"><i class="fa fa-calendar" aria-hidden="true" ></i> {{ log_entry.versions[-1].event_utc_datetime | babel_format_datetime }}</span></div>
            {% endif %}
            {% if log_entry.versions[-1].content %}
              {% if log_entry.versions[-1].content_is_markdown %}
                <div class="instrument-user-content" style="padding-left: 0; border: 0">{{ log_entry.versions[-1].content | markdown_to_safe_html(anchor_prefix='log-entry-' + (log_entry.id | string)) | safe  }}</div>
              {% else %}
                <pre class="comment">{{ log_entry.versions[-1].content }}</pre>
              {% endif %}
            {% else %}
              &mdash;
            {% endif %}
            <div class="text-right">&mdash; <a href="{{ url_for('frontend.user_profile', user_id=log_entry.author.id) }}">{{ log_entry.author.name }}</a>, {% if log_entry.versions | length > 1 %}<span data-toggle="tooltip" data-placement="bottom" title="{{ _('This log entry was originally written at this date and time.') }}">{{ log_entry.versions[0].utc_datetime | babel_format_datetime }}</span> &ndash; <span data-toggle="tooltip" data-placement="bottom" title="{{ _('This log entry was last edited at this date and time.') }}">{{ log_entry.versions[-1].utc_datetime | babel_format_datetime }}</span>{% else %}<span data-toggle="tooltip" data-placement="bottom" title="This log entry was written at this date and time.">{{ log_entry.versions[-1].utc_datetime | babel_format_datetime }}</span>{% endif %}</div>
            {% if log_entry.versions[:-1] %}
              <div class="text-right"><label for="instrument-log-show-versions-{{ log_entry.id }}" class="instrument-log-show-versions"></label>{% if log_entry.user_id == current_user.id and not current_user.is_readonly %}&nbsp;/&nbsp;<span class="instrument-log-show-edit" data-toggle="modal" data-target="#logEntryContentModal_{{ log_entry.id }}">{{ _('Edit log entry') }}</span>{% endif %}</div>
              {% for version in log_entry.versions[:-1] | reverse %}
                <div class="instrument-log-version">
                  <hr />
                  {% if version.event_utc_datetime %}
                  <div class="text-right"><i class="fa fa-calendar" aria-hidden="true"></i> {{ version.event_utc_datetime | babel_format_datetime }}</div>
                  {% endif %}
                  {% if version.content %}
                    {% if version.content_is_markdown %}
                      <div class="instrument-user-content" style="padding-left: 0; border: 0">{{ version.content | markdown_to_safe_html(anchor_prefix='log-entry-' + (log_entry.id | string)) | safe  }}</div>
                    {% else %}
                      <pre class="comment">{{ version.content }}</pre>
                    {% endif %}
                  {% else %}
                    &mdash;
                  {% endif %}
                  <div class="text-right text-muted">{{ version.utc_datetime | babel_format_datetime }}</div>
                </div>
              {% endfor %}
            {% elif log_entry.user_id == current_user.id and not current_user.is_readonly %}
              <div class="text-right"><span class="instrument-log-show-edit" data-toggle="modal" data-target="#logEntryContentModal_{{ log_entry.id }}">{{ _('Edit log entry') }}</span></div>
            {% endif %}
          {% if log_entry.file_attachments or log_entry.object_attachments %}
              <hr />
          {% endif %}
          {% set file_attachments = log_entry.file_attachments %}
          {% if file_attachments %}
            <div class="file-attachment-header">{{ _('Attached Files') }}:</div>
            <ul class="file-attachment-list">
            {% with hidden_file_attachments = [] %}
            {% for file_attachment in file_attachments %}{% if not file_attachment.is_hidden %}
              <li>
                {% if file_attachment | attachment_is_image %}
                <span class="file-attachment-preview">
                  <img src="{{ url_for('.instrument_log_file_attachment', instrument_id=instrument.id, log_entry_id=log_entry.id, file_attachment_id=file_attachment.id, preview=1) }}" alt="&#xf15b;" class="show-fullscreen-image-preview" />
                  <span class="fullscreen-image-preview">
                    <span class="close-fullscreen-image-preview"><i class="fa fa-close fa-fw"></i></span>
                    <a href="{{ url_for('.instrument_log_file_attachment', instrument_id=instrument.id, log_entry_id=log_entry.id, file_attachment_id=file_attachment.id) }}">
                      <span class="download-fullscreen-image-preview"><i class="fa fa-download fa-fw"></i></span>
                    </a>
                    <img src="{{ url_for('.instrument_log_file_attachment', instrument_id=instrument.id, log_entry_id=log_entry.id, file_attachment_id=file_attachment.id) }}" alt="Fullscreen Image Preview">
                  </span>
                </span>
                <a href="{{ url_for('.instrument_log_file_attachment', instrument_id=instrument.id, log_entry_id=log_entry.id, file_attachment_id=file_attachment.id) }}">
                {% else %}
                <a href="{{ url_for('.instrument_log_file_attachment', instrument_id=instrument.id, log_entry_id=log_entry.id, file_attachment_id=file_attachment.id) }}">
                  <span class="file-attachment-preview">
                    <i class="fa fa-file"></i>
                  </span>
                {% endif %}
                  <span>{{ file_attachment.file_name }}</span>
                </a>
              </li>
            {% else %}{{ hidden_file_attachments.append(file_attachment) or '' }}{% endif %}{% endfor %}
            {% if hidden_file_attachments %}
              <li>{{ ngettext('%(num)s hidden file', '%(num)s hidden files', hidden_file_attachments | length) }}</li>
            {% endif %}
            {% endwith %}
            </ul>
          {% endif %}
          {% set object_attachments = log_entry.object_attachments %}
          {% if object_attachments %}
            <div class="object-attachment-header">{{ _('Attached Objects') }}:</div>
            <ul class="object-attachment-list">
            {% with hidden_object_attachments = [] %}
            {% for object_attachment in object_attachments %}{% if not object_attachment.is_hidden %}<li>
                <a href="{{ url_for('.object', object_id=object_attachment.object_id) }}">{{ attached_object_names.get(object_attachment.object_id, 'Object') | get_translated_text }} (#{{ object_attachment.object_id }})</a></li>
            {% else %}{{ hidden_object_attachments.append(object_attachment) or '' }}{% endif %}{% endfor %}
            {% if hidden_object_attachments %}
              <li>{{ ngettext('%(num)s hidden object', '%(num)s hidden objects', hidden_object_attachments | length) }}</li>
            {% endif %}
            {% endwith %}
            </ul>
          {% endif %}
          </div>
          {% if not current_user.is_readonly and log_entry.user_id == current_user.id %}
            <div class="modal fade" id="logEntryContentModal_{{ log_entry.id }}" tabindex="-1" role="dialog" aria-labelledby="logEntryContentModalLabel_{{ log_entry.id }}">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                  <h4 class="modal-title" id="logEntryContentModalLabel_{{ log_entry.id }}">{{ _('Edit Log Entry') }}</h4>
                </div>
                <form method="post" enctype="multipart/form-data">
                <div class="modal-body">
                  {{ instrument_log_entry_form.csrf_token }}
                  <input type="hidden" name="{{ instrument_log_entry_form.log_entry_id.name }}" value="{{ log_entry.id }}" />
                  <div class="form-group">
                    <label for="textarea-log-entry-text-{{ log_entry.id }}">{{ _('Edit content') }}</label>
                    <label class="pull-right" style="font-weight: normal"><input type="checkbox" id="input-edit-content-is-markdown-{{ log_entry.id }}" name="{{ instrument_log_entry_form.content_is_markdown.name }}" {% if log_entry.versions[-1].content_is_markdown %}checked="checked"{% endif %}> {{ _('Use Markdown') }}</label>
                    <textarea class="form-control" id="textarea-log-entry-text-{{ log_entry.id }}" rows="3" placeholder="{{ _('Instrument Log Entry') }}" style="resize:vertical; min-height:171px; margin-bottom: 10px;" name="{{ instrument_log_entry_form.content.name }}">{{ log_entry.versions[-1].content or '' }}</textarea>
                  </div>
                <div class="form-group">
                  <label for="textarea-log-entry-event_utc_datetime-{{ log_entry.id }}">{{ _('Set event datetime') }}</label>
                  <label class="pull-right" style="font-weight: normal"><input type="checkbox" id="input-has-event-datetime-{{ log_entry.id }}" name="{{ instrument_log_entry_form.has_event_utc_datetime.name }}" {% if log_entry.versions[-1].event_utc_datetime %}checked="checked"{% endif %}> {{ _('Has event datetime') }}</label>
                  <div class="input-group log_entry_date_picker">
                    <input type="text" class="form-control" id="textarea-log-entry-event_utc_datetime-{{ log_entry.id }}" disabled="disabled" name="{{ instrument_log_entry_form.event_utc_datetime.name }}" value="{% if log_entry.versions[-1].event_utc_datetime %}{{ log_entry.versions[-1].event_utc_datetime.strftime(instrument_log_entry_form.event_utc_datetime.format) }}{% endif %}">
                    <span class="input-group-addon">
                      <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                  </div>
                </div>
                  <label for="input-file-upload-{{ log_entry.id }}">{{ _('Add file attachments') }}</label>
                 <div class="input-group" id="upload-area-{{ log_entry.id }}">
                    <span class="input-group-addon"><i class="fa fa-file"></i></span>
                    <input id="input-file-text-{{ log_entry.id }}" type="text" class="form-control disabled" disabled placeholder="{{ _('No files selected') }}" />
                    <div class="input-group-btn">
                      <label class="btn btn-primary" style="width: 10em;"><i class="fa fa-folder-open"></i>{{ _('Browse...') }}<input id="input-file-upload-{{ log_entry.id }}" type="file" name="{{ instrument_log_entry_form.files.name }}" multiple style="display: none;"></label>
                    </div>
                  </div>
                  {% if instrument_log_entry_form.objects.choices or config["LOAD_OBJECTS_IN_BACKGROUND"] %}
                  <div class="form-group" style="margin: 15px 0" id="wrapper-object-attachments-{{ log_entry.id }}">
                    <label for="select-object-attachments-{{ log_entry.id }}">{{ _('Add object attachments') }}</label>
                    <select id="select-object-attachments-{{ log_entry.id }}" name="{{ instrument_log_entry_form.objects.name }}" class="selectpicker" multiple="multiple" data-live-search="true" data-none-selected-text="{{ _('No objects selected') }}" data-width="100%" data-sampledb-required-perm="1" data-sampledb-remove="{% for object_attachment in log_entry.object_attachments %}{% if not object_attachment.is_hidden%}{{ object_attachment.object_id }},{% endif %}{% endfor %}-1" data-sampledb-empty-hide="#wrapper-object-attachments-{{ log_entry.id }}">
                      {% for choice in instrument_log_entry_form.objects.choices %}
                        {% set ns = namespace(found=False) %}
                        {% for object_attachment in log_entry.object_attachments %}
                          {% if object_attachment.object_id | string == choice[0] and not object_attachment.is_hidden%}
                            {% set ns.found = True %}
                          {% endif %}
                        {% endfor %}
                        {% if not ns.found %}
                        <option value="{{ choice[0] }}">{{ choice[1] }}</option>
                        {% endif %}
                      {% endfor %}
                    </select>
                  </div>
                  {% endif %}
                  {% if instrument_log_entry_form.categories.choices %}
                  <div class="form-group" style="margin: 15px 0">
                    <label for="select-categories-{{ log_entry.id }}">{{ _('Edit categories') }}</label>
                    <select id="select-categories-{{ log_entry.id }}" name="{{ instrument_log_entry_form.categories.name }}" class="selectpicker" multiple="multiple" data-none-selected-text="{{ _('No categories selected') }}" data-width="100%">
                      {% for choice in instrument_log_entry_form.categories.choices %}
                        <option value="{{ choice[0] }}" {% for category in log_entry.versions[-1].categories %}{% if category.id | string == choice[0] %}selected="selected"{% endif %}{% endfor %}>{{ choice[1] }}</option>
                      {% endfor %}
                    </select>
                  </div>
                  {% endif %}

                {% if log_entry.file_attachments or log_entry.object_attachments %}
                  <hr />
                    <p class="text-muted">{{ _('You can hide a file or object, if it was attached erroneously.') }}</p>

                  {% if log_entry.file_attachments %}
                  <div class="form-group" style="margin: 15px 0">
                    <label for="select-existing-file-attachments-{{ log_entry.id }}">{{ _('Hide file attachments') }}</label>
                    <select id="select-existing-file-attachments-{{ log_entry.id }}" name="{{ instrument_log_entry_form.existing_files.name }}" class="selectpicker" multiple="multiple" data-none-selected-text="{{ _('No attached files selected') }}" data-width="100%">
                      {% for file_attachment in log_entry.file_attachments %}
                        <option value="{{ file_attachment.id }}">{{ file_attachment.file_name }}</option>
                      {% endfor %}
                    </select>
                  </div>
                  {% endif %}

                  {% if log_entry.object_attachments %}
                  <div class="form-group" style="margin: 15px 0">
                    <label for="select-existing-object-attachments-{{ log_entry.id }}">{{ _('Hide object attachments') }}</label>
                    <select id="select-existing-object-attachments-{{ log_entry.id }}" name="{{ instrument_log_entry_form.existing_objects.name }}" class="selectpicker" multiple="multiple" data-none-selected-text="{{ _('No attached objects selected') }}" data-width="100%">
                      {% for object_attachment in log_entry.object_attachments %}
                        <option value="{{ object_attachment.id }}">{{ attached_object_names.get(object_attachment.object_id, 'Object') | get_translated_text }} (#{{ object_attachment.object_id }})</option>
                      {% endfor %}
                    </select>
                  </div>
                  {% endif %}
                {% endif %}

                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">{{ _('Close') }}</button>
                  <button type="submit" name="action_edit_content" class="btn btn-primary">{{ _('Save changes') }}</button>
                </div>
                </form>
              </div>
            </div>
          </div>
          {% endif %}
          </div>
        {% endfor %}
        <div id="instrument-log-tree">
        </div>
      {% else %}
        <p class="text-muted">{{ _('There are no log entries for this instrument.') }}</p>
        {% if not current_user.is_readonly and (is_instrument_responsible_user or instrument.users_can_create_log_entries) %}
          <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#newLogEntryModal" style="height:32px">
            <i class="fa fa-comment-o fa-fw"></i> {{ _('Create Log Entry') }}
          </button>
          <button type="button" class="btn btn-sm btn-default" data-toggle="modal" data-target="#mobileFileLinkModal" style="height:32px">
            <i class="fa fa-mobile-phone fa-fw"></i> {{ _('Smartphone Upload as Log Entry') }}
          </button>
        {% endif %}
      {% endif %}
    {% endif %}
    {% if not current_user.is_readonly and (is_instrument_responsible_user or instrument.users_can_create_log_entries) %}

    {% set log_entry_text_missing = [] %}
    {% for message in get_flashed_messages() %}
      {% if 'Please enter a log entry text' in message %}
        {{ log_entry_text_missing.append(True) or '' }}
      {% endif %}
    {% endfor %}
      <div class="modal fade" id="newLogEntryModal" tabindex="-1" role="dialog" aria-labelledby="newLogEntryModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <form class="form" method="post" id="new_instrument_log_entry_form" enctype="multipart/form-data">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="newLogEntryModalLabel">{{ _('Create Log Entry') }}</h4>
              </div>
              <div class="modal-body">
                {{ instrument_log_entry_form.csrf_token }}
                <div class="form-group {% if log_entry_text_missing %}has-error{% endif %}">
                  <label for="textarea-log-entry-text" class="control-label">{{ _('Content') }}</label>
                  <label class="pull-right" style="font-weight: normal"><input type="checkbox" id="input-content-is-markdown" name="{{ instrument_log_entry_form.content_is_markdown.name }}"> {{ _('Use Markdown') }}</label>
                  <textarea class="form-control" id="textarea-log-entry-text" rows="3" placeholder="{{ _('Instrument Log Entry') }}" style="resize: vertical; min-height: 171px; margin-bottom: 10px;" name="{{ instrument_log_entry_form.content.name }}"></textarea>
                  {% if log_entry_text_missing %}
                    <span class="help-block">{{ _('Please enter a text or add an attachment.') }}</span>
                  {% endif %}
                </div>
                <div class="form-group">
                  <label for="textarea-log-entry-event_utc_datetime">{{ _('Set event datetime')}}</label>
                  <label class="pull-right" style="font-weight: normal"><input type="checkbox" id="input-has-event-datetime" name="{{ instrument_log_entry_form.has_event_utc_datetime.name }}"> {{ _('Has event datetime')}}</label>
                  <div class="input-group log_entry_date_picker">
                    <input type="text" class="form-control" id="textarea-log-entry-event_utc_datetime" disabled="disabled" name="{{ instrument_log_entry_form.event_utc_datetime.name }}" {% if instrument_log_entry_form.event_utc_datetime.data %}value="{{ instrument_log_entry_form.event_utc_datetime.data }}"{% endif %}>
                    <span class="input-group-addon">
                      <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                  </div>
                </div>
                <label for="input-file-upload">{{ _('Add file attachments')}}</label>
                <div class="input-group" id="upload-area">
                  <span class="input-group-addon"><i class="fa fa-file"></i></span>
                  <input id="input-file-text" type="text" class="form-control disabled" disabled placeholder="{{ _('No files selected')}}" />
                  <div class="input-group-btn">
                    <label class="btn btn-primary" style="width: 10em;"><i class="fa fa-folder-open"></i>{{ _('Browse...')}}<input id="input-file-upload" type="file" name="{{ instrument_log_entry_form.files.name }}" multiple style="display: none;"></label>
                  </div>
                </div>
                {% if instrument_log_entry_form.objects.choices or config["LOAD_OBJECTS_IN_BACKGROUND"]%}
                <div class="form-group" style="margin: 15px 0" id="wrapper-object-attachments-new">
                  <label for="select-object-attachments">{{ _('Add object attachments') }}</label>
                  <select id="select-object-attachments" name="{{ instrument_log_entry_form.objects.name }}" class="selectpicker" multiple="multiple" data-live-search="true" data-none-selected-text="{{ _('No objects selected') }}" data-width="100%" data-sampledb-required-perm="1" data-sampledb-remove="-1" data-sampledb-empty-hide="#wrapper-object-attachments-new">
                    {% for choice in instrument_log_entry_form.objects.choices %}
                      <option value="{{ choice[0] }}">{{ choice[1] }}</option>
                    {% endfor %}
                  </select>
                </div>
                {% endif %}
                {% if instrument_log_entry_form.categories.choices %}
                <div class="form-group" style="margin: 15px 0">
                  <label for="select-categories">{{ _('Add categories') }}</label>
                  <select id="select-categories" name="{{ instrument_log_entry_form.categories.name }}" class="selectpicker" multiple="multiple" data-none-selected-text="{{ _('No categories selected') }}" data-width="100%">
                    {% for choice in instrument_log_entry_form.categories.choices %}
                      <option value="{{ choice[0] }}">{{ choice[1] }}</option>
                    {% endfor %}
                  </select>
                </div>
                {% endif %}
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">{{ _('Cancel') }}</button>
                <button type="submit" class="btn btn-primary">{{ _('Create log entry')}}</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    {% endif %}
  {% endif %}

  {% if mobile_upload_qrcode and mobile_upload_url%}
    <div class="modal fade" id="mobileFileLinkModal" tabindex="-1" role="dialog" aria-labelledby="mobileFileLinkModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="mobileFileLinkModalLabel">{{ _('Mobile File Upload') }}</h4>
          </div>
          <div class="modal-body">
            <p class="text-center">{{ _('To upload files from mobile devices, scan this QR code:') }}</p>
            <a href="{{ mobile_upload_url }}"><img src="{{ mobile_upload_qrcode }}" alt="{{ mobile_upload_url }}" style="width: 100%"/></a>
          </div>
        </div>
      </div>
    </div>
  {% endif %}
{% endblock %}

{% block stylesheets %}
  {{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-select.min.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-toggle.min.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-datetimepicker.min.css') }}" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/inscrybmde.min.css') }}" />
<style>
label.instrument-log-show-versions:before {
    content: '{{ _('Show previous versions') }}';
}
input.instrument-log-show-versions:checked ~ div label.instrument-log-show-versions:before {
    content: '{{ _('Hide previous versions') }}';
}

.instrument-scientists li:nth-last-child(2):after,
.file-attachment-list li:nth-last-child(2):after,
.object-attachment-list li:nth-last-child(2):after {
    content: '{{ _(' and ') }}';
}
</style>
{% endblock %}

{% block scripts %}
  {{ super() }}
  <script src="{{ url_for('static', filename='js/markdown_image_viewer.js') }}"></script>
  <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-toggle.min.js') }}"></script>
  {% if config['LOAD_OBJECTS_IN_BACKGROUND'] %}
    <script src="{{ url_for('static', filename='js/sampledb-load-objects.js') }}"></script>
  {% endif %}
  <script src="{{ url_for('static', filename='js/inscrybmde.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/markdown_image_upload.js') }}"></script>
  <script type="text/javascript">
    window.categoriesShown = {
      {% for category in instrument_log_categories %}
      '{{ category.id }}': true,
      {% endfor %}
      'none': true
    };
    window.filterDate = null;
    window.filterUser = null;
    function setup_instrument_log_filter_states() {
      {% for category in instrument_log_categories %}
      $('#instrument_log_filter_{{ category.id }}').prop('checked', window.categoriesShown['{{ category.id }}']);
      {% endfor %}
      $('#instrument_log_filter_none').prop('checked', window.categoriesShown['none']);
      $('#instrument_log_counter').html($('.instrument-log-entry:not(:hidden)').length.toString()+ " / " + $('.instrument-log-entry').length.toString());
        $('.input-group.date').each(function() {
          var datetimepicker = $(this).datetimepicker({
            date: window.filterDate,
            locale: "{{ get_user_language(current_user).lang_code }}",
            format: 'YYYY-MM',
            showClear: true,
            showClose: true,
            maxDate: moment(new Date())
          });
          datetimepicker.on('dp.change', function() {
            update_instrument_log_filter_states();
          });
          $('#input-instrument-log-filter-date').on('click', function() {
            datetimepicker.data("DateTimePicker").toggle();
          });
        });
        var selectpicker = $('#input-instrument-log-filter-user');
        selectpicker.selectpicker('val', window.filterUser);
        selectpicker.on('changed.bs.select', function() {
            update_instrument_log_filter_states();
        });
    }
    function update_instrument_log_filter_states() {
      var filter_date = $('#input-instrument-log-filter-date').val();
      if (filter_date === "") {
        window.filterDate = null;
      } else {
        window.filterDate = filter_date;
      }
      var filter_user = $('#input-instrument-log-filter-user').val();
      if (filter_user === "") {
        window.filterUser = null;
      } else {
        window.filterUser = filter_user;
      }
      $('.instrument-log-entry').hide();
      {% for category in instrument_log_categories %}
        window.categoriesShown['{{ category.id }}'] = $('#instrument_log_filter_{{ category.id }}').prop('checked');
        if (window.categoriesShown['{{ category.id }}']) {
          let filter_selector = 'div[data-instrument-log-category-{{ category.id }}="yes"]';
          if (filter_date !== "") {
            filter_selector = filter_selector + '[data-instrument-log-date='+filter_date+']';
          }
          if (filter_user !== "") {
            filter_selector = filter_selector + '[data-instrument-log-user-id='+filter_user+']';
          }
          $(filter_selector).show();
        }
      {% endfor %}
      window.categoriesShown['none'] = $('#instrument_log_filter_none').prop('checked');
      if (window.categoriesShown['none']) {
        let filter_selector = 'div[data-instrument-log-category-none="yes"]';
        if (filter_date !== "") {
          filter_selector = filter_selector + '[data-instrument-log-date='+filter_date+']';
        }
        if (filter_user !== "") {
          filter_selector = filter_selector + '[data-instrument-log-user-id='+filter_user+']';
        }
        $(filter_selector).show();
      }
      $('#instrument_log_counter').html($('.instrument-log-entry:not(:hidden)').length.toString()+ " / " + $('.instrument-log-entry').length.toString());
    }
    function reset_instrument_log_filter_states() {
      window.categoriesShown['none'] = true;
      {% for category in instrument_log_categories %}
      window.categoriesShown['{{ category.id }}'] = true;
      {% endfor %}
      window.filterUser = null;
      window.filterDate = null;
      let num_entries = $('#instrument-log-container > div > .instrument-log-entry').length;
      $('#instrument_log_counter').html(num_entries.toString() + " / " + num_entries.toString());
    }
    $(function () {
      setup_instrument_log_filter_states();
      $('[data-toggle="popover"]').popover();

      function updateNewLogEntryMarkdown() {
        if ($('#input-content-is-markdown').prop('checked')) {
          window.new_log_entry = new InscrybMDE({
            element: $("#textarea-log-entry-text")[0],
            indentWithTabs: false,
            spellChecker: false,
            status: false,
            hideIcons: ["guide", "fullscreen", "side-by-side", "quote"],
            showIcons: ["code", "table"],
            minHeight: '100px',
          });
          setupImageDragAndDrop(window.new_log_entry);
        } else {
          if (window.new_log_entry) {
            window.new_log_entry.toTextArea();
            window.new_log_entry = null;
          }
        }
      }
      $('#input-content-is-markdown').change(updateNewLogEntryMarkdown);
      updateNewLogEntryMarkdown();

      {% if instrument_log_entries %}
      {% for log_entry in instrument_log_entries %}
        {% if not current_user.is_readonly and (current_user.id == log_entry.user_id) %}
        function changeHandler{{ log_entry.id }}() {
          var files =  $('#input-file-upload-{{ log_entry.id }}').get(0).files;
          if (files.length === 0) {
            $('#input-file-text-{{ log_entry.id }}').val("");
          } else if (files.length === 1) {
            $('#input-file-text-{{ log_entry.id }}').val(files[0].name);
          } else {
            $('#input-file-text-{{ log_entry.id }}').val(files.length + " files selected");
          }
        }
        $('#input-file-upload-{{ log_entry.id }}').on('change', changeHandler{{ log_entry.id }});
        function dropHandler{{ log_entry.id }}(e) {
          e.preventDefault();
          $('#input-file-upload-{{ log_entry.id }}')[0].files = e.dataTransfer.files;
          changeHandler{{ log_entry.id }}();
        }
        function dragOverHandler{{ log_entry.id }}(e) {
          e.preventDefault();
        }
        var upload_area = $('#upload-area-{{ log_entry.id }}')[0];
        upload_area.ondrop = dropHandler{{ log_entry.id }};
        upload_area.ondragover = dragOverHandler{{ log_entry.id }};

        function updateLogEntryMarkdown_{{ log_entry.id }}() {
          if ($('#input-edit-content-is-markdown-{{ log_entry.id }}').prop('checked')) {
            if (window.log_entry_{{ log_entry.id }}) {
              window.log_entry_{{ log_entry.id }}.toTextArea();
            }
            window.log_entry_{{ log_entry.id }} = new InscrybMDE({
              element: $("#textarea-log-entry-text-{{ log_entry.id }}")[0],
              indentWithTabs: false,
              spellChecker: false,
              status: false,
              hideIcons: ["guide", "fullscreen", "side-by-side", "quote"],
              showIcons: ["code", "table"],
              minHeight: '100px',
            });
            setupImageDragAndDrop(window.log_entry_{{ log_entry.id }});
          } else {
            if (window.log_entry_{{ log_entry.id }}) {
              window.log_entry_{{ log_entry.id }}.toTextArea();
              window.log_entry_{{ log_entry.id }} = null;
            }
          }
        }
        $('#input-edit-content-is-markdown-{{ log_entry.id }}').change(updateLogEntryMarkdown_{{ log_entry.id }});
        $('#logEntryContentModal_{{ log_entry.id }}').on('shown.bs.modal', updateLogEntryMarkdown_{{ log_entry.id }});
        updateLogEntryMarkdown_{{ log_entry.id }}();
        $()
        {% endif %}
      {% endfor %}
      {% endif %}
      function changeHandler() {
        var files =  $('#input-file-upload').get(0).files;
        if (files.length === 0) {
          $('#input-file-text').val("");
        } else if (files.length === 1) {
          $('#input-file-text').val(files[0].name);
        } else {
          $('#input-file-text').val(files.length + " files selected");
        }
      }
      {% if not current_user.is_readonly and (is_instrument_responsible_user or instrument.users_can_create_log_entries) %}
      $('#input-file-upload').on('change', changeHandler);
      function dropHandler(e) {
        e.preventDefault();
        $('#input-file-upload')[0].files = e.dataTransfer.files;
        changeHandler();
      }
      function dragOverHandler(e) {
        e.preventDefault();
      }
      var upload_area = $('#upload-area')[0];
      upload_area.ondrop = dropHandler;
      upload_area.ondragover = dragOverHandler;
      {% endif %}

      function applySortOrder(log_order_button, attribute) {
        var log_order_button_indicator = log_order_button.find('i');
        if (log_order_button_indicator.css('visibility') === 'hidden') {
          $('.button-switch-instrument-log-order i').css('visibility', 'hidden');
          log_order_button_indicator.css('visibility', 'visible');
        } else {
          log_order_button_indicator.toggleClass('fa-sort-asc').toggleClass('fa-sort-desc');
        }

        var ascending = (log_order_button.find('i.fa-sort-asc').length !== 0);

        var container = $('#instrument-log-container');
        container.children().sort(function(a, b) {
          a_datetime = $(a).find('.instrument-log-entry').data('instrumentLog' + attribute);
          b_datetime = $(b).find('.instrument-log-entry').data('instrumentLog' + attribute);
          if (ascending) {
            return a_datetime > b_datetime;
          } else {
            return a_datetime < b_datetime;
          }
        }).appendTo(container);

        var form = $('#form-instrument-log-order');
        form.find('input[type="checkbox"]').prop('checked', ascending);
        form.find('input[type="text"]').val(attribute.toLowerCase());
        $.ajax({
          type: "POST",
          url: {{ url_for('.set_instrument_log_order') | tojson }},
          data: form.serialize()
        });
      }
      var log_order_button_date = $('#button-switch-instrument-log-order-date');
      log_order_button_date.on('click', function () {
        applySortOrder(log_order_button_date, "Datetime");
      });
      var log_order_button_user_name = $('#button-switch-instrument-log-order-user-name');
      log_order_button_user_name.on('click', function () {
        applySortOrder(log_order_button_user_name, "UserName");
      });

      let show_list_button = $('.button-show-instrument-log-list');
      let show_tree_button_date_author = $('.button-show-instrument-log-tree-date-author');
      let show_tree_button_author_date = $('.button-show-instrument-log-tree-author-date');
      show_list_button.on('click', function() {
        reset_instrument_log_filter_states();
        show_list_button.prop('disabled', true);
        show_tree_button_date_author.prop('disabled', false);
        show_tree_button_author_date.prop('disabled', false);
        $('.button-switch-instrument-log-order, #button-instrument-log-list-filter').prop('disabled', false);
        $('#instrument-log-tree').html('');
        $('.instrument-log-entry').show();
      });
      function sort_tree_container_children(container) {
        container.children('.instrument-log-tree-container').sort(function(a, b) {
          let a_value = $(a).data('instrumentLogTreeSortValue');
          let b_value = $(b).data('instrumentLogTreeSortValue');
          let a_number = Number.parseInt(a_value);
          let b_number = Number.parseInt(b_value);
          if (Number.isNaN(a_number) || Number.isNaN(b_number)) {
            return a_value > b_value;
          } else {
            return a_number > b_number;
          }
        }).appendTo(container);
      }
      show_tree_button_date_author.on('click', function() {
        reset_instrument_log_filter_states();
        show_list_button.prop('disabled', false);
        show_tree_button_date_author.prop('disabled', true);
        show_tree_button_author_date.prop('disabled', false);
        $('.button-switch-instrument-log-order, #button-instrument-log-list-filter').prop('disabled', true);
        let log_entries = $('#instrument-log-container > div > .instrument-log-entry');
        $('#button-instrument-log-list-filter').popover('hide');
        log_entries.hide();
        let tree_container = $('#instrument-log-tree');
        if (log_entries.length) {
          tree_container.html('<div class="instrument-log-tree-container"><div class="instrument-log-tree-block" id="instrument-log-tree-root-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all years') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all years') }}</button></div></div></div>');
        } else {
          tree_container.html("");
        }
        let containers_by_date = {};
        let i = 0;
        const MONTH_NAMES = {{ get_local_month_names() | tojson }};
        log_entries.each(function(_, element) {
          let log_entry = $(element);
          let author = log_entry.data('instrumentLogUserName');
          let utc_datetime_string = log_entry.data('instrumentLogDatetime');
          let utc_datetime = moment.utc(utc_datetime_string);
          let local_datetime = utc_datetime.local();
          let year = local_datetime.year();
          let month = local_datetime.month();
          let day = local_datetime.date();
          if (!(year in containers_by_date)) {
            let parent_container = tree_container.find('#instrument-log-tree-root-block');
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + year + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + year + '</label></h3><div class="instrument-log-tree-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all months') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all months') }}</button></div></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_date[year] = [container.find('.instrument-log-tree-block'), {}];
          }
          if (!(month in containers_by_date[year][1])) {
            let parent_container = containers_by_date[year][0];
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + month + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + MONTH_NAMES[month] + '</label></h3><div class="instrument-log-tree-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all days') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all days') }}</button></div></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_date[year][1][month] = [container.find('.instrument-log-tree-block'), {}];
          }
          if (!(day in containers_by_date[year][1][month][1])) {
            let parent_container = containers_by_date[year][1][month][0];
            let container = $('<div class="instrument-log-tree-container"  data-instrument-log-tree-sort-value="' + day + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + day + '</label></h3><div class="instrument-log-tree-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all authors') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all authors') }}</button></div></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_date[year][1][month][1][day] = [container.find('.instrument-log-tree-block'), {}];
          }
          if (!(author in containers_by_date[year][1][month][1][day][1])) {
            let parent_container = containers_by_date[year][1][month][1][day][0];
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + author + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + author + '</label></h3><div class="instrument-log-tree-block"></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_date[year][1][month][1][day][1][author] = [container.find('.instrument-log-tree-block'), {}];
          }
          let log_entry_clone = $(log_entry).clone();
          log_entry_clone.show();
          log_entry_clone.appendTo(containers_by_date[year][1][month][1][day][1][author][0]);
        });
        tree_container.find('.button-instrument-log-tree-expand-all').on('click', function() {
          $(this).closest('.instrument-log-tree-block').find('> .instrument-log-tree-container > input[type="checkbox"]').each(function(_, checkbox) {
            checkbox.checked = true;
          });
        });
        tree_container.find('.button-instrument-log-tree-collapse-all').on('click', function() {
          $(this).closest('.instrument-log-tree-block').find('> .instrument-log-tree-container > input[type="checkbox"]').each(function(_, checkbox) {
            checkbox.checked = false;
          });
        });
      });
      show_tree_button_author_date.on('click', function() {
        reset_instrument_log_filter_states();
        show_list_button.prop('disabled', false);
        show_tree_button_date_author.prop('disabled', false);
        show_tree_button_author_date.prop('disabled', true);
        $('.button-switch-instrument-log-order, #button-instrument-log-list-filter').prop('disabled', true);
        let log_entries = $('#instrument-log-container > div > .instrument-log-entry');
        $('#button-instrument-log-list-filter').popover('hide');
        log_entries.hide();
        let tree_container = $('#instrument-log-tree');
        if (log_entries.length) {
          tree_container.html('<div class="instrument-log-tree-container"><div class="instrument-log-tree-block" id="instrument-log-tree-root-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all authors') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all authors') }}</button></div></div></div>');
        } else {
          tree_container.html();
        }
        let containers_by_author = {};
        let i = 0;
        const MONTH_NAMES = {{ get_local_month_names() | tojson }};
        log_entries.each(function(_, element) {
          let log_entry = $(element);
          let author = log_entry.data('instrumentLogUserName');
          let utc_datetime_string = log_entry.data('instrumentLogDatetime');
          let utc_datetime = moment.utc(utc_datetime_string);
          let local_datetime = utc_datetime.local();
          let year = local_datetime.year();
          let month = local_datetime.month();
          let day = local_datetime.date();
          if (!(author in containers_by_author)) {
            let parent_container = tree_container.find('#instrument-log-tree-root-block');
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + author + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + author + '</label></h3><div class="instrument-log-tree-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all years') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all years') }}</button></div></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_author[author] = [container.find('.instrument-log-tree-block'), {}];
          }
          if (!(year in containers_by_author[author][1])) {
            let parent_container = containers_by_author[author][0];
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + year + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + year + '</label></h3><div class="instrument-log-tree-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all months') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all months') }}</button></div></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_author[author][1][year] = [container.find('.instrument-log-tree-block'), {}];
          }
          if (!(month in containers_by_author[author][1][year][1])) {
            let parent_container = containers_by_author[author][1][year][0];
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + month + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + MONTH_NAMES[month] + '</label></h3><div class="instrument-log-tree-block"><div><button type="button" class="btn btn-default btn-xs button-instrument-log-tree-expand-all">{{ _('Expand all days') }}</button> <button type="button" class="btn btn-default btn-xs button-instrument-log-tree-collapse-all">{{ _('Collapse all days') }}</button></div></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_author[author][1][year][1][month] = [container.find('.instrument-log-tree-block'), {}];
          }
          if (!(day in containers_by_author[author][1][year][1][month][1])) {
            let parent_container = containers_by_author[author][1][year][1][month][0];
            let container = $('<div class="instrument-log-tree-container" data-instrument-log-tree-sort-value="' + day + '"><input type="checkbox" id="instrument-log-tree-toggle-' + (++i) + '"/><h3><label for="instrument-log-tree-toggle-' + i + '"><i class="fa fa-fw fa-plus-square"></i> ' + day + '</label></h3><div class="instrument-log-tree-block"></div></div>');
            container.appendTo(parent_container);
            sort_tree_container_children(parent_container);
            containers_by_author[author][1][year][1][month][1][day] = [container.find('.instrument-log-tree-block'), {}];
          }
          let log_entry_clone = $(log_entry).clone();
          log_entry_clone.show();
          log_entry_clone.appendTo(containers_by_author[author][1][year][1][month][1][day][0]);
        });
        tree_container.find('.button-instrument-log-tree-expand-all').on('click', function() {
          $(this).closest('.instrument-log-tree-block').find('> .instrument-log-tree-container > input[type="checkbox"]').each(function(_, checkbox) {
            checkbox.checked = true;
          });
        });
        tree_container.find('.button-instrument-log-tree-collapse-all').on('click', function() {
          $(this).closest('.instrument-log-tree-block').find('> .instrument-log-tree-container > input[type="checkbox"]').each(function(_, checkbox) {
            checkbox.checked = false;
          });
        });
      });

      {% set log_entry_text_missing = [] %}
      {% for message in get_flashed_messages() %}
        {% if 'Please enter a log entry text' in message %}
          {{ log_entry_text_missing.append(True) or '' }}
        {% endif %}
      {% endfor %}

      $('.log_entry_date_picker').each(function() {
        var datetimepicker = $(this);
        var textbox = datetimepicker.find('input[type="text"]');
        var checkbox = datetimepicker.parent().find('input[type="checkbox"]');
        if (textbox.val()) {
          checkbox.prop('checked', true);
          textbox.prop('disabled', false);
        }
        datetimepicker.datetimepicker({
          format: '{{ instrument_log_entry_form.event_utc_datetime.format_moment }}',
          showClear: true,
          showClose: true,
          showTodayButton: true
        });
        checkbox.on('change', function() {
          var checked = checkbox.prop('checked');
          textbox.prop('disabled', !checked);
          if (checked) {
            datetimepicker.data("DateTimePicker").show();
          } else {
            datetimepicker.data("DateTimePicker").hide();
            textbox.val('');
          }
        });
        datetimepicker.on('dp.change', function() {
          if (textbox.val() === "") {
            checkbox.prop('checked', false);
            textbox.prop('disabled', true);
            datetimepicker.data("DateTimePicker").hide();
          }
        });
        textbox.on('change', function() {
          if (textbox.val() === "") {
            checkbox.prop('checked', false);
            textbox.prop('disabled', true);
            datetimepicker.data("DateTimePicker").hide();
          }
        });
      });

      {% if log_entry_text_missing %}
      $('#newLogEntryModal').modal({'show': true});
      {% endif %}

      $('.button-show-instrument-log-list').prop('disabled', true);
    });
  </script>
{% endblock %}