/*
* jQuery Quode Tree
* Update on 25th June 2008
* Version 0.1
*
* Licensed under BSD
* Copyright (c) 2008, www.quode.net
*/


(function($) {

  $.fn.quodeTree = function(options) {

    options = $.extend({
      leafClick: null
    }, options);

    var self = this;

    return this.each(function() {
      var el = $(this);
      makeTree(el);
      el.click(function(e) {
        var t = $(e.target);
        var a, p = t.parent();
        if ((a = t.find(">ul.ajax")).length || (a = p.find(">ul.ajax")).length) {
          ajaxLoad(a);
        }
        else if (toggleState(t)) { }
        else if (toggleState(p)) { }
        else if (!t.is("li")) { // it's a leaf !
          if (options.leafClick) options.leafClick(
            $.fn.quodeTree.makeNode(t)
          );
        }
      });
    });
  };

  $.fn.quodeTree.makeNode = function(o) {
    o = $.extend({
      addMark: function() {
        trav.call(this, true);
      },
      removeMark: function() {
        trav.call(this);
      },
      hasMark: function() {
        return this.data("refc");
      }
    }, o);
    return o;
  };

  $.fn.quodeTree.massAjaxLoad = function(tree, sync) {
    tree.find("ul.ajax").each(function() {
      ajaxLoad($(this), sync, true);
    });
  }

  function ajaxLoad(a, sync, close) { // close: leave folder closed
    a.each(function() {
      //alert(this); //UL
      var self = $(this);
      var url = self.text();
      self.children().remove();
      self.parent().addClass("loading");
      $.ajax({
        type: "GET",
        url: url,
        contentType:'html',
        cache:false,
        async: !sync,
        success: function(responce){
          self.html(responce);
          makeTree(self.parent());
          if (!close) {
            self.parent().removeClass("closed").addClass("open"); // pas ici!!??
          }
          self.removeClass('ajax');
          self.parent().removeClass("loading");
        }
      });
    });
  }

  function trav(add) {
    this.parents("li").find("> a, > span").each(function() { // filtrer jusqu'au #tree (pas prendre les ancestors!)
      var $this = $(this);
      var refc = $this.data("refc");
      if (!refc) refc = 0;
      if (add) {
        $this.addClass("mark");
        $this.data("refc", ++refc);
      }
      else {
        refc = --refc < 0 ? 0 : refc;
        if (!refc) $this.removeClass("mark");
        $this.data("refc", refc);
      }
    });
  };

  function makeTree(el) {
    var s = "li > ul > li";
    el.find(s).each(function() {
      $(this).parent().parent().addClass("closed");
    });
    el.find("li > ul.ajax").each(function() {
      $(this).parent().addClass("closed");
    });
  };

  function toggleState(e) {
    if (e.hasClass("closed")) {
      e.removeClass("closed").addClass("open");
    }
    else if (e.hasClass("open")) {
      e.removeClass("open").addClass("closed");
    }
    else return false;
    return true;
  };

})(jQuery);

