{# variation of admin/change_list_results.html #}
{% load i18n polymorphic_tree_admin_tags suit_list %}

{% if result_hidden_fields %}
  <div class="hiddenfields">{# DIV for HTML validation #}
    {% for item in result_hidden_fields %}{{ item }}{% endfor %}
  </div>
{% endif %}
{% if results %}
  <div class="results jqtree-django"><div id="js-result-list">
    <table id="result_list" class="table table-striped table-bordered table-hover table-condensed">
      <thead>
        <tr>
          {% for header in result_headers|headers_handler:cl %}
            {% if header.field_name != "action_checkbox" %}
            <th scope="col" {{ header.class_attrib }}>
              <div class="text">
                <span>{{ header.text|capfirst }}</span>
              </div>
            </th>
            {% endif %}
          {% endfor %}
      </tr>
      </thead>
      <tbody>
      {% for result in results|cells_handler:cl %}
        {% if result.form.non_field_errors %}
            <tr>
              <td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td>
            </tr>
        {% endif %}
          <tr class="{% cycle 'row1' 'row2' %} nodetype-{{ result.object|real_model_name|lower }}">
            {% for item in result %}{% if "action-select" not in item %}{{ item }}{% endif %}{% endfor %}</tr>
      {% endfor %}
      </tbody>
    </table>
  </div></div>
{% endif %}

<script type="text/javascript">
  /*
   * This code is currently inline because it is generated using various template variables and translation messages.
   */
    var data = [
        {% adminlist_recursetree cl %}{% with is_leaf=node.is_leaf_node %}
        {
            id: {{ node.pk }},
            classes: 'nodetype-{{ node|real_model_name|lower }}',
            can_have_children: {{ node.can_have_children|yesno:'true,false' }},
            label: '<div class="col-primary{% if is_leaf %} leaf{% endif %}"><div class="col first-column"><a href="{{ change_url }}"{% if cl.is_popup %} onclick="opener.dismissRelatedLookupPopup(window, {{ node.pk }}); return false;"{% endif %}>{{ first_column|escapejs }}</a></div></div>{% if other_columns %}<div class="col-metadata">{% for name, repr in other_columns %}<div class="col col-{{ name }}">{{ repr|escapejs }}</div>{% endfor %}</div>{% endif %}'{% if not is_leaf %}, children: [ {{ children }} ]{% endif %}},
        {% endwith %}{% endadminlist_recursetree %}
    null  // for MSIE
  ];
  data.pop();


  function onCreateLi(node, $li) {
    // Move node contents directly in li element. not in a span.
    var $div = $li.children('div')
    var $span = $div.children('span');
    var contents = $span.children();
    $span.remove();
    $li.addClass(node.classes);
    $div.append(contents);
  }

  function onCanMoveTo(moved_node, target_node, position) {
    return ( target_node.can_have_children || position != 'inside' );
  }

  var tree = jQuery("#js-result-list").tree({
    data: data,
    autoOpen: true,
    saveState: true,
    dragAndDrop: {{ cl.is_popup|yesno:"false,true" }},
    onCreateLi: onCreateLi,
    onCanMoveTo: onCanMoveTo
  });

    tree.before('<table class="js-tree-header table table-striped table-bordered table-hover table-condensed"><thead><tr>{% for header in result_headers|headers_handler:cl %}{% if header.field_name != "action_checkbox" %}<th scope="col" {{ header.class_attrib }}><div class="text"><span>{{ header.text|capfirst }}</span></div></th>{% endif %}{% endfor %}</tr></thead></table>');
  tree.bind('tree.move', function(e) {
    var move_info = e.move_info;

    jQuery.ajax({
      type: 'POST',
      url: '{{ cl.model_admin.api_node_moved_view_url }}',
      dataType: 'json',
      data: {
        'moved_id': parseInt(move_info.moved_node.id),
        'target_id': parseInt(move_info.target_node.id),
        'previous_parent_id': parseInt(move_info.previous_parent.id || 0),
        'position': move_info.position,
        'csrfmiddlewaretoken': '{{ csrf_token }}'
      },
      success: function onMoveSuccess(data, status, xhr) {
        // Replace the action column, the preview URL changed.
        if( data.action_column && data.moved_id == move_info.moved_node.id ) {
          $(".col-actions_column", move_info.moved_node.element).html(data.action_column);
        }
      },
      error: onMoveError
    });
  });

  function onMoveError(xhr, status, exception) {
    var response = jQuery.parseJSON(xhr.responseText);
    // TODO: it would be possible to stream new data from the server instead.
    if( response.action == 'reload' ) {
      alert('{% trans "Unable to move the node, the current display is out-of-date.\nThe current page now reloaded." %}');
      location.reload();
    }
    else if( response.action == 'reject' ) {
      alert(response.error);
      location.reload();
    }
    else {
      alert('{% trans "There was an error while moving the node, please reload the current page." %}');
    }
  }
</script>
