{% load i18n %}
<div class="assetmanager-file">
  <input type="hidden" class="file" id="{{ name }}" name="{{ name }}" value="{{ value_as_json }}"/>
  <a class="related-widget-wrapper-link change-related asset-manager-link" id="change_{{ name }}"
     href="/admin/assetmanager/file/list/?{{ url_params }}"
     title="{% blocktrans %}Change file{% endblocktrans %}">
    {% blocktrans %}Change file{% endblocktrans %}
  </a>
  <div id="preview_{{ name }}" class="preview" {% if not value %}style="display: none;"{% endif %}>
    <a href="{{ value.url }}" target="_blank">
      {% if images_only %}
        <img class="url" src="{{ value.url }}" width="200"/>
        <div class="name"><span>{{ value.fileOriginalName }}</span> <i class="fontello-icon-popup"></i></div>
      {% else %}
        <div class="name"><span>{{ value.fileOriginalName }}</span> <i class="fontello-icon-popup"></i></div>
      {% endif %}
    </a>
  </div>
  {% if not is_required %}
  <a class="clear"
     {% if not value %}style="display: none;"{% endif %}
     href="#">Clear</a>
  {% endif %}
</div>
<script type="application/javascript">
  (function(globals, $) {
    'use strict';

    function dismissChooseFilePopup(win, newFile) {
      var name = win;
      if (win.name) {
        name = win.name;
      }
      name = windowname_to_id(name);

      var $popups = $('body, .related-popup');
      $popups.each(function(idx, iframe) {
        var $iframe = $(iframe).contents();
        var elem = $iframe.find('#change_' + name);
        var fileInput = $iframe.find('#' + name);
        var previewElement = $iframe.find('#preview_' + name);
        if (elem && fileInput) {
          $(fileInput).val(JSON.stringify(newFile));
          previewElement.find('> a').attr('href', newFile.url);
          previewElement.find('.url').attr('src', newFile.url);
          previewElement.find('.name > span').text(newFile.fileOriginalName);
          previewElement.show();

          var doc = iframe.contentDocument || iframe.ownerDocument;
          doc.dispatchEvent(new Event('tt.imageSelected'));
        }

        $(elem).siblings('.clear').show();
      });

      if (win.close) {
        win.close();
      }

      $('select').trigger('select:init');
      $(window.parent).trigger('related-popup:close');
    }

    var container = $(document);
    container.on('click', '.assetmanager-file .clear', function(event) {
      $(this).hide();
      $(this).siblings('.file').val('');
      previewElement.hide();
      event.preventDefault();
    });

    globals.dismissChooseFilePopup = dismissChooseFilePopup;
  })(window, jet.jQuery);
</script>
