{% extends "admin/base_site.html" %}
{% load i18n admin_modify admin_static %}

{% block extrahead %}{{ block.super }}
{% url 'admin:jsi18n' as jsi18nurl %}
<script type="text/javascript" src="{{ jsi18nurl|default:"../../../jsi18n/" }}"></script>
{{ media }}
{% if navtree %}
  <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/tree.css" />
  <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/smoothness/jquery-ui-1.8.14.custom.css" />

  <script src="{{STATIC_URL}}js/jquery-1.7.1.min.js"></script>
  <script src="{{STATIC_URL}}js/jquery-ui-1.8.14.custom.min.js"></script>
  <script src="{{STATIC_URL}}js/jquery.jstree.js"></script>
  <script src="{{STATIC_URL}}js/jquery-ajax-csrf.js"></script>
  <script>
    $.widget("custom.catcomplete", $.ui.autocomplete, {
      _renderMenu: function(ul, items) {
        var self = this, currentCategory = "";
        $.each( items, function( index, item ) {
          if ( item.category != currentCategory ) {
            ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
            currentCategory = item.category;
          }
          self._renderItem( ul, item );
        });
      }
    });
  </script>
  <script type="text/javascript">
    $(function() {
      var last_selection = null;

      var admin_hideMessage = function ()  {
          $('#admin-status').hide();
          $(".error-field").removeClass("error-field");
      };

      var admin_printMessage = function (message, css_class) {
          $('#admin-status').removeClass().html(message).addClass(css_class).show();
          setTimeout(admin_hideMessage, 3000);
      };

      function disable_actions() {
        //$("#rename_node").attr('disabled', 'disabled');
        //$("#delete_node").attr('disabled', 'disabled');
        $("#rename_node").parent('li').hide();
        $("#delete_node").parent('li').hide();
        $("#navnode_in_navigation").parent('li').hide();
      }

      function enable_actions() {
        //$("#rename_node").removeAttr('disabled');
        //$("#delete_node").removeAttr('disabled');
        $("#rename_node").parent('li').show();
        $("#delete_node").parent('li').show();
        $("#navnode_in_navigation").parent('li').show();
      }
      disable_actions();

      function post_msg(msg_id, data, callback) {
        data['msg_id'] = msg_id;
        $.post(
          "{{navtree.get_absolute_url}}",
          data,
          callback,
          'json'
        );
      }

      function get_node_id(node) {
        return node.attr("id").slice(5);
      }

      $("#add_object").click(function() {
        data = {msg_id: 'add_navnode'};
        data["object_id"] = $("#object_id").val();
        data["object_type"] = $("#object_type").val();
        try {
          var selected_nodes = $("#nodes").jstree('get_selected');
          data['parent_id'] = get_node_id($(selected_nodes[0]));
        } catch (ex) {
          //alert(''+ex);
        }
        post_msg('add_navnode', data,
          function(data) {
            admin_printMessage(data.message, data.status);
            if (data.status==='success') {
              $("#nodes").jstree("create",null,"last",{data:data.label, attr:{id: data.id, rel: 'in_nav'}});
              $("#object_label").val("");
            }
          }
        );
      });

      $("#nodes").jstree({
          "themes" : {
              "theme" : "classic",
              "dots" : true,
              "icons" : true
              },
        "dnd" : {
          "drop_target": false,
          "drag_target": false,
          "drag_check" : function () {
            return { after : true, before : true, inside : true };
          }
        },
        "ui" : {
          "select_limit" : 1,
        },
        "types" : {
          "types" : {
            "valid_children" : "all",
            "out_nav" : {
                "icon" : {
                  "image" : "{{STATIC_URL}}img/out_nav.png"
                }
            },
            "in_nav" : {
              "valid_children" : "all",
              "icon" : {
                "image" : "{{STATIC_URL}}img/in_nav.png"
              }
            }
          }
        },
        "plugins" : [ "themes", "html_data", "dnd", "ui", "crrm", "types" ]
      })

      $("#nodes").bind("move_node.jstree", function (event, data) {
        var tree_data = {
          node_id: get_node_id(data.rslt.o),
          ref_pos: data.rslt.p
        };
        try {
          tree_data['ref_id'] = get_node_id(data.rslt.or);
        } catch (ex) {
          console.log('error > invalid ref_id');
        }

        try {
          tree_data['parent_id'] = get_node_id(data.rslt.np);
        } catch (ex) {}

        post_msg('move_navnode', tree_data, function(data) {
          admin_printMessage(data.message, data.status);
        });
      })
      $("#nodes").bind("rename_node.jstree", function (event, data) {
          var tree_data = {
          node_id: get_node_id(data.rslt.obj),
          name: data.rslt.name
          };
          post_msg('rename_navnode', tree_data, function(data) {
            if (data.message) {
              admin_printMessage(data.message, data.status);
            }
            deselect_all();
          });
      });

      function deselect_all() {
        $("#nodes").jstree("deselect_all");
        disable_actions();
        last_selection = null;
        $("#aside #object-links").html("");
      }

      $("#nodes").bind("select_node.jstree", function (event, data) {
        if (last_selection === get_node_id(data.rslt.obj)) {
            deselect_all();
        } else {
          last_selection = get_node_id(data.rslt.obj);
          enable_actions();

          post_msg('view_navnode', {node_id: get_node_id(data.rslt.obj)},
            function(data) {
              if (data.status === "success") {
                $("#aside #object-links").html(data.html);
              } else {
                $("#aside #object-links").html("");
              }
            }
          );
        }
      });

      $("#object_label").catcomplete({
          source: function(request, add){
            post_msg('get_suggest_list', {term: request.term}, function(data) {
              var existing_objects = [];
              if (data.status === "success") {
                $.each(data.suggestions, function(i, val){
                  existing_objects.push(val);
                });
              } else {
                admin_printMessage(data.message, data.status);
              }
              add(existing_objects);
            });
          },
          select: function(event, ui) {
            $("#object_label").val(ui.item.label);
            $("#object_id").val(ui.item.value);
            $("#object_type").val(ui.item.type);
            return false;
          },
          focus: function(event, ui) {
            $("#object_label").val(ui.item.label);
            $("#object_id").val(ui.item.value);
            return false;
          }
      });

      $("#rename_node").click(function () {
          $("#nodes").jstree("rename");
          return false;
      });

      $("#delete_node").click(function () {
        var selected_nodes = $("#nodes").jstree('get_selected');
        var length = selected_nodes.length;
        if (length>0){
          var confirm_msg = "{% trans 'Are you sure to delete the selected node?' %}"
          if (confirm(confirm_msg)) {
            var node_ids = [];
            for (var i=0; i<length; i++) {
              node_ids.push(get_node_id($(selected_nodes[i])))
            }
            post_msg('remove_navnode', {'node_ids': node_ids.join(";")}, function(data) {
              admin_printMessage(data.message, data.status);
              if (data.status === "success"){
                for (var i=0; i<length; i++) {
                  $("#nodes").jstree("remove", "#"+$(selected_nodes[i]).attr("id"));
                }
              }
            });
          }
        }
        return false;
      });

      $("#navnode_in_navigation").click(function () {
        var selected_nodes = $("#nodes").jstree('get_selected');
        var node=selected_nodes[0];
        post_msg('navnode_in_navigation', {'node_id': get_node_id($(node))}, function(data) {
          admin_printMessage(data.message, data.status);
          if (data.status === "success"){
            $("#navnode_in_navigation").html(data.label);
            $("#nodes").jstree('set_type', data.icon, $(node));
          }
        });
        return false;
      });

    });
  </script>
{% endif %}
{% endblock %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}" />{% endblock %}

{% block coltype %}{% if ordered_objects %}colMS{% else %}colM{% endif %}{% endblock %}

{% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %}

{% block breadcrumbs %}{% if not is_popup %}
<div class="breadcrumbs">
     <a href="../../../">{% trans "Home" %}</a> &rsaquo;
     <a href="../../">{{ app_label|capfirst|escape }}</a> &rsaquo;
     {% if has_change_permission %}<a href="../">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %} &rsaquo;
     {% if add %}{% trans "Add" %} {{ opts.verbose_name }}{% else %}{{ original|truncatewords:"18" }}{% endif %}
</div>
{% endif %}{% endblock %}

{% block content %}
  {% if object_id %}
  <noscript><div id="jswarning">{% trans "The site requires javascript to be enabled!" %}</div></noscript>
  <div id="content">
    <div class="button-bar">
      <span class="add_object_section">
        <input id="object_label" size=30/>
        <button id="add_object" class="btn primary">{% trans "Add a new node" %}</button>
        <input id="object_id" type="hidden"/>
        <input id="object_type" type="hidden"/>
      </span>
      <span id="admin-status"></span>
    </div>
    <div id="aside">
      <div id="object-links">
      </div>
      <ul class="content-links">
          <li><a href="{{content.get_absolute_url}}" id="rename_node">{% trans "Rename this node" %}</a></li>
          <li><a href="{{content.get_absolute_url}}" id="navnode_in_navigation">{% trans "Navigation" %}</a></li>
          <li><a href="{{content.get_absolute_url}}" id="delete_node">{% trans "Remove this node" %}</a></li>

      </ul>
    </div>
    <div id="nodes" class="">
      <ul>{{navtree_nodes|safe}}</ul>
    </div>
  </div>
  {% else %}
    <div id="content-main">
    {% block object-tools %}
    {% if change %}{% if not is_popup %}
      <ul class="object-tools">
        {% block object-tools-items %}
        <li><a href="history/" class="historylink">{% trans "History" %}</a></li>
        {% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif%}
        {% endblock %}
      </ul>
    {% endif %}{% endif %}
    {% endblock %}
    <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% csrf_token %}{% block form_top %}{% endblock %}
    <div>
    {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
    {% if save_on_top %}{% submit_row %}{% endif %}
    {% if errors %}
        <p class="errornote">
        {% blocktrans count errors|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
        </p>
        {{ adminform.form.non_field_errors }}
    {% endif %}

    {% for fieldset in adminform %}
      {% include "admin/includes/fieldset.html" %}
    {% endfor %}

    {% block after_field_sets %}{% endblock %}

    {% for inline_admin_formset in inline_admin_formsets %}
        {% include inline_admin_formset.opts.template %}
    {% endfor %}

    {% block after_related_objects %}{% endblock %}

    {% submit_row %}

    {% if adminform and add %}
       <script type="text/javascript">document.getElementById("{{ adminform.first_field.id_for_label }}").focus();</script>
    {% endif %}

    {# JavaScript for prepopulated fields #}
    {% prepopulated_fields_js %}

    </div>
    </form></div>
  {% endif %}
{% endblock %}
