Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1888_OaaS/HeuristicLab.Services.Optimization.Web/Content/dynatree/dist/jquery.dynatree-1.2.2.js @ 17578

Last change on this file since 17578 was 9215, checked in by fschoepp, 12 years ago

#1888:

  • Janitor is now working as expected in Windows Azure
  • Added basic support for experiments (draggable experiments)
  • Added methods to save/read experiments from TableStorage
  • The job status can now be retrieved by using the GetTasks/GetTaskData methods
  • Added a class to convert JSON-objects to Algorithm instances
  • Web page: Added experiment button to navigation
File size: 103.4 KB
Line 
1/*! jQuery Dynatree Plugin - v1.2.2 - 2012-10-07
2* http://dynatree.googlecode.com/
3* Copyright (c) 2012 Martin Wendt; Licensed MIT, GPL */
4
5/* jsHint options*/
6// Note: We currently allow eval() to parse the 'data' attribtes, when initializing from HTML.
7// TODO: pass jsHint with the options given in grunt.js only.
8//       The following should not be required:
9/*global alert */
10/*jshint nomen:false, smarttabs:true, eqeqeq:false, evil:true, regexp:false */
11
12/*************************************************************************
13 *  Debug functions
14 */
15
16var _canLog = true;
17
18function _log(mode, msg) {
19  /**
20   * Usage: logMsg("%o was toggled", this);
21   */
22  if( !_canLog ){
23    return;
24  }
25  // Remove first argument
26  var args = Array.prototype.slice.apply(arguments, [1]);
27  // Prepend timestamp
28  var dt = new Date();
29  var tag = dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds()+"."+dt.getMilliseconds();
30  args[0] = tag + " - " + args[0];
31
32  try {
33    switch( mode ) {
34    case "info":
35      window.console.info.apply(window.console, args);
36      break;
37    case "warn":
38      window.console.warn.apply(window.console, args);
39      break;
40    default:
41      window.console.log.apply(window.console, args);
42      break;
43    }
44  } catch(e) {
45    if( !window.console ){
46      _canLog = false; // Permanently disable, when logging is not supported by the browser
47    }
48  }
49}
50
51function logMsg(msg) {
52  Array.prototype.unshift.apply(arguments, ["debug"]);
53  _log.apply(this, arguments);
54}
55
56
57// Forward declaration
58var getDynaTreePersistData = null;
59
60
61
62/*************************************************************************
63 *  Constants
64 */
65var DTNodeStatus_Error   = -1;
66var DTNodeStatus_Loading = 1;
67var DTNodeStatus_Ok      = 0;
68
69
70// Start of local namespace
71(function($) {
72
73/*************************************************************************
74 *  Common tool functions.
75 */
76
77var Class = {
78  create: function() {
79    return function() {
80      this.initialize.apply(this, arguments);
81    };
82  }
83};
84
85// Tool function to get dtnode from the event target:
86function getDtNodeFromElement(el) {
87  alert("getDtNodeFromElement is deprecated");
88  return $.ui.dynatree.getNode(el);
89/*
90  var iMax = 5;
91  while( el && iMax-- ) {
92    if(el.dtnode) { return el.dtnode; }
93    el = el.parentNode;
94  }
95  return null;
96*/
97}
98
99function noop() {
100}
101
102/*************************************************************************
103 *  Class DynaTreeNode
104 */
105var DynaTreeNode = Class.create();
106
107DynaTreeNode.prototype = {
108  initialize: function(parent, tree, data) {
109    /**
110     * @constructor
111     */
112    this.parent = parent;
113    this.tree = tree;
114    if ( typeof data === "string" ){
115      data = { title: data };
116    }
117    if( data.key === undefined ){
118      data.key = "_" + tree._nodeCount++;
119    }
120    this.data = $.extend({}, $.ui.dynatree.nodedatadefaults, data);
121    this.li = null; // not yet created
122    this.span = null; // not yet created
123    this.ul = null; // not yet created
124    this.childList = null; // no subnodes yet
125    this._isLoading = false; // Lazy content is being loaded
126    this.hasSubSel = false;
127    this.bExpanded = false;
128    this.bSelected = false;
129
130  },
131
132  toString: function() {
133    return "DynaTreeNode<" + this.data.key + ">: '" + this.data.title + "'";
134  },
135
136  toDict: function(recursive, callback) {
137    var dict = $.extend({}, this.data);
138    dict.activate = ( this.tree.activeNode === this );
139    dict.focus = ( this.tree.focusNode === this );
140    dict.expand = this.bExpanded;
141    dict.select = this.bSelected;
142    if( callback ){
143      callback(dict);
144    }
145    if( recursive && this.childList ) {
146      dict.children = [];
147      for(var i=0, l=this.childList.length; i<l; i++ ){
148        dict.children.push(this.childList[i].toDict(true, callback));
149      }
150    } else {
151      delete dict.children;
152    }
153    return dict;
154  },
155
156  fromDict: function(dict) {
157    /**
158     * Update node data. If dict contains 'children', then also replace
159     * the hole sub tree.
160     */
161    var children = dict.children;
162    if(children === undefined){
163      this.data = $.extend(this.data, dict);
164      this.render();
165      return;
166    }
167    dict = $.extend({}, dict);
168    dict.children = undefined;
169    this.data = $.extend(this.data, dict);
170    this.removeChildren();
171    this.addChild(children);
172  },
173
174  _getInnerHtml: function() {
175    var tree = this.tree,
176      opts = tree.options,
177      cache = tree.cache,
178      level = this.getLevel(),
179      data = this.data,
180      res = "",
181      imageSrc;
182    // connector (expanded, expandable or simple)
183    if( level < opts.minExpandLevel ) {
184      if(level > 1){
185        res += cache.tagConnector;
186      }
187      // .. else (i.e. for root level) skip expander/connector altogether
188    } else if( this.hasChildren() !== false ) {
189      res += cache.tagExpander;
190    } else {
191      res += cache.tagConnector;
192    }
193    // Checkbox mode
194    if( opts.checkbox && data.hideCheckbox !== true && !data.isStatusNode ) {
195      res += cache.tagCheckbox;
196    }
197    // folder or doctype icon
198    if ( data.icon ) {
199      if (data.icon.charAt(0) === "/"){
200        imageSrc = data.icon;
201      }else{
202        imageSrc = opts.imagePath + data.icon;
203      }
204      res += "<img src='" + imageSrc + "' alt='' />";
205    } else if ( data.icon === false ) {
206      // icon == false means 'no icon'
207//      noop(); // keep JSLint happy
208    } else {
209      // icon == null means 'default icon'
210      res += cache.tagNodeIcon;
211    }
212    // node title
213    var nodeTitle = "";
214    if ( opts.onCustomRender ){
215      nodeTitle = opts.onCustomRender.call(tree, this) || "";
216    }
217    if(!nodeTitle){
218      var tooltip = data.tooltip ? ' title="' + data.tooltip.replace(/\"/g, '&quot;') + '"' : '',
219        href = data.href || "#";
220      if( opts.noLink || data.noLink ) {
221        nodeTitle = '<span style="display:inline-block;" class="' + opts.classNames.title + '"' + tooltip + '>' + data.title + '</span>';
222//        this.tree.logDebug("nodeTitle: " + nodeTitle);
223      } else {
224        nodeTitle = '<a href="' + href + '" class="' + opts.classNames.title + '"' + tooltip + '>' + data.title + '</a>';
225      }
226    }
227    res += nodeTitle;
228    return res;
229  },
230
231
232  _fixOrder: function() {
233    /**
234     * Make sure, that <li> order matches childList order.
235     */
236    var cl = this.childList;
237    if( !cl || !this.ul ){
238      return;
239    }
240    var childLI = this.ul.firstChild;
241    for(var i=0, l=cl.length-1; i<l; i++) {
242      var childNode1 = cl[i];
243      var childNode2 = childLI.dtnode;
244      if( childNode1 !== childNode2 ) {
245        this.tree.logDebug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
246        this.ul.insertBefore(childNode1.li, childNode2.li);
247      } else {
248        childLI = childLI.nextSibling;
249      }
250    }
251  },
252
253
254  render: function(useEffects, includeInvisible) {
255    /**
256     * Create <li><span>..</span> .. </li> tags for this node.
257     *
258     * <li id='KEY' dtnode=NODE> // This div contains the node's span and list of child div's.
259     *   <span class='title'>S S S A</span> // Span contains graphic spans and title <a> tag
260     *   <ul> // only present, when node has children
261     *       <li id='KEY' dtnode=NODE>child1</li>
262     *       <li id='KEY' dtnode=NODE>child2</li>
263     *   </ul>
264     * </li>
265     */
266//    this.tree.logDebug("%s.render(%s)", this, useEffects);
267    // ---
268    var tree = this.tree,
269      parent = this.parent,
270      data = this.data,
271      opts = tree.options,
272      cn = opts.classNames,
273      isLastSib = this.isLastSibling(),
274      firstTime = false;
275
276    if( !parent && !this.ul ) {
277      // Root node has only a <ul>
278      this.li = this.span = null;
279      this.ul = document.createElement("ul");
280      if( opts.minExpandLevel > 1 ){
281        this.ul.className = cn.container + " " + cn.noConnector;
282      }else{
283        this.ul.className = cn.container;
284      }
285    } else if( parent ) {
286      // Create <li><span /> </li>
287      if( ! this.li ) {
288        firstTime = true;
289        this.li = document.createElement("li");
290        this.li.dtnode = this;
291        if( data.key && opts.generateIds ){
292          this.li.id = opts.idPrefix + data.key;
293        }
294        this.span = document.createElement("span");
295        this.span.className = cn.title;
296        this.li.appendChild(this.span);
297
298        if( !parent.ul ) {
299          // This is the parent's first child: create UL tag
300          // (Hidden, because it will be
301          parent.ul = document.createElement("ul");
302          parent.ul.style.display = "none";
303          parent.li.appendChild(parent.ul);
304//          if( opts.minExpandLevel > this.getLevel() ){
305//            parent.ul.className = cn.noConnector;
306//          }
307        }
308        // set node connector images, links and text
309//        this.span.innerHTML = this._getInnerHtml();
310
311        parent.ul.appendChild(this.li);
312      }
313      // set node connector images, links and text
314      this.span.innerHTML = this._getInnerHtml();
315      // Set classes for current status
316      var cnList = [];
317      cnList.push(cn.node);
318      if( data.isFolder ){
319        cnList.push(cn.folder);
320      }
321      if( this.bExpanded ){
322        cnList.push(cn.expanded);
323      }
324      if( this.hasChildren() !== false ){
325        cnList.push(cn.hasChildren);
326      }
327      if( data.isLazy && this.childList === null ){
328        cnList.push(cn.lazy);
329      }
330      if( isLastSib ){
331        cnList.push(cn.lastsib);
332      }
333      if( this.bSelected ){
334        cnList.push(cn.selected);
335      }
336      if( this.hasSubSel ){
337        cnList.push(cn.partsel);
338      }
339      if( tree.activeNode === this ){
340        cnList.push(cn.active);
341      }
342      if( data.addClass ){
343        cnList.push(data.addClass);
344      }
345      // IE6 doesn't correctly evaluate multiple class names,
346      // so we create combined class names that can be used in the CSS
347      cnList.push(cn.combinedExpanderPrefix
348          + (this.bExpanded ? "e" : "c")
349          + (data.isLazy && this.childList === null ? "d" : "")
350          + (isLastSib ? "l" : "")
351          );
352      cnList.push(cn.combinedIconPrefix
353          + (this.bExpanded ? "e" : "c")
354          + (data.isFolder ? "f" : "")
355          );
356      this.span.className = cnList.join(" ");
357
358      // TODO: we should not set this in the <span> tag also, if we set it here:
359      this.li.className = isLastSib ? cn.lastsib : "";
360
361      // Allow tweaking, binding, after node was created for the first time
362      if(firstTime && opts.onCreate){
363        opts.onCreate.call(tree, this, this.span);
364      }
365      // Hide children, if node is collapsed
366//      this.ul.style.display = ( this.bExpanded || !parent ) ? "" : "none";
367      // Allow tweaking after node state was rendered
368      if(opts.onRender){
369        opts.onRender.call(tree, this, this.span);
370      }
371    }
372    // Visit child nodes
373    if( (this.bExpanded || includeInvisible === true) && this.childList ) {
374      for(var i=0, l=this.childList.length; i<l; i++) {
375        this.childList[i].render(false, includeInvisible);
376      }
377      // Make sure the tag order matches the child array
378      this._fixOrder();
379    }
380    // Hide children, if node is collapsed
381    if( this.ul ) {
382      var isHidden = (this.ul.style.display === "none");
383      var isExpanded = !!this.bExpanded;
384//      logMsg("isHidden:%s", isHidden);
385      if( useEffects && opts.fx && (isHidden === isExpanded) ) {
386        var duration = opts.fx.duration || 200;
387        $(this.ul).animate(opts.fx, duration);
388      } else {
389        this.ul.style.display = ( this.bExpanded || !parent ) ? "" : "none";
390      }
391    }
392  },
393  /** Return '/id1/id2/id3'. */
394  getKeyPath: function(excludeSelf) {
395    var path = [];
396    this.visitParents(function(node){
397      if(node.parent){
398        path.unshift(node.data.key);
399      }
400    }, !excludeSelf);
401    return "/" + path.join(this.tree.options.keyPathSeparator);
402  },
403
404  getParent: function() {
405    return this.parent;
406  },
407
408  getChildren: function() {
409    if(this.hasChildren() === undefined){
410      return undefined; // Lazy node: unloaded, currently loading, or load error
411    }
412    return this.childList;
413  },
414
415  /** Check if node has children (returns undefined, if not sure). */
416  hasChildren: function() {
417    if(this.data.isLazy){
418      if(this.childList === null || this.childList === undefined){
419        // Not yet loaded
420        return undefined;
421      }else if(this.childList.length === 0){
422        // Loaded, but response was empty
423        return false;
424      }else if(this.childList.length === 1 && this.childList[0].isStatusNode()){
425        // Currently loading or load error
426        return undefined;
427      }
428      return true;
429    }
430    return !!this.childList;
431  },
432
433  isFirstSibling: function() {
434    var p = this.parent;
435    return !p || p.childList[0] === this;
436  },
437
438  isLastSibling: function() {
439    var p = this.parent;
440    return !p || p.childList[p.childList.length-1] === this;
441  },
442
443  isLoading: function() {
444    return !!this._isLoading;
445  },
446
447  getPrevSibling: function() {
448    if( !this.parent ){
449      return null;
450    }
451    var ac = this.parent.childList;
452    for(var i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
453      if( ac[i] === this ){
454        return ac[i-1];
455      }
456    }
457    return null;
458  },
459
460  getNextSibling: function() {
461    if( !this.parent ){
462      return null;
463    }
464    var ac = this.parent.childList;
465    for(var i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
466      if( ac[i] === this ){
467        return ac[i+1];
468      }
469    }
470    return null;
471  },
472
473  isStatusNode: function() {
474    return (this.data.isStatusNode === true);
475  },
476
477  isChildOf: function(otherNode) {
478    return (this.parent && this.parent === otherNode);
479  },
480
481  isDescendantOf: function(otherNode) {
482    if(!otherNode){
483      return false;
484    }
485    var p = this.parent;
486    while( p ) {
487      if( p === otherNode ){
488        return true;
489      }
490      p = p.parent;
491    }
492    return false;
493  },
494
495  countChildren: function() {
496    var cl = this.childList;
497    if( !cl ){
498      return 0;
499    }
500    var n = cl.length;
501    for(var i=0, l=n; i<l; i++){
502      var child = cl[i];
503      n += child.countChildren();
504    }
505    return n;
506  },
507
508  /**Sort child list by title.
509   * cmd: optional compare function.
510   * deep: optional: pass true to sort all descendant nodes.
511   */
512  sortChildren: function(cmp, deep) {
513    var cl = this.childList;
514    if( !cl ){
515      return;
516    }
517    cmp = cmp || function(a, b) {
518//      return a.data.title === b.data.title ? 0 : a.data.title > b.data.title ? 1 : -1;
519      var x = a.data.title.toLowerCase(),
520        y = b.data.title.toLowerCase();
521      return x === y ? 0 : x > y ? 1 : -1;
522      };
523    cl.sort(cmp);
524    if( deep ){
525      for(var i=0, l=cl.length; i<l; i++){
526        if( cl[i].childList ){
527          cl[i].sortChildren(cmp, "$norender$");
528        }
529      }
530    }
531    if( deep !== "$norender$" ){
532      this.render();
533    }
534  },
535
536  _setStatusNode: function(data) {
537    // Create, modify or remove the status child node (pass 'null', to remove it).
538    var firstChild = ( this.childList ? this.childList[0] : null );
539    if( !data ) {
540      if ( firstChild && firstChild.isStatusNode()) {
541        try{
542          // I've seen exceptions here with loadKeyPath...
543          if(this.ul){
544            this.ul.removeChild(firstChild.li);
545            firstChild.li = null; // avoid leaks (issue 215)
546          }
547        }catch(e){}
548        if( this.childList.length === 1 ){
549          this.childList = [];
550        }else{
551          this.childList.shift();
552        }
553      }
554    } else if ( firstChild ) {
555      data.isStatusNode = true;
556      data.key = "_statusNode";
557      firstChild.data = data;
558      firstChild.render();
559    } else {
560      data.isStatusNode = true;
561      data.key = "_statusNode";
562      firstChild = this.addChild(data);
563    }
564  },
565
566  setLazyNodeStatus: function(lts, opts) {
567    var tooltip = (opts && opts.tooltip) ? opts.tooltip : null,
568      info = (opts && opts.info) ? " (" + opts.info + ")" : "";
569    switch( lts ) {
570      case DTNodeStatus_Ok:
571        this._setStatusNode(null);
572        $(this.span).removeClass(this.tree.options.classNames.nodeLoading);
573        this._isLoading = false;
574//        this.render();
575        if( this.tree.options.autoFocus ) {
576          if( this === this.tree.tnRoot && this.childList && this.childList.length > 0) {
577            // special case: using ajaxInit
578            this.childList[0].focus();
579          } else {
580            this.focus();
581          }
582        }
583        break;
584      case DTNodeStatus_Loading:
585        this._isLoading = true;
586        $(this.span).addClass(this.tree.options.classNames.nodeLoading);
587        // The root is hidden, so we set a temporary status child
588        if(!this.parent){
589          this._setStatusNode({
590            title: this.tree.options.strings.loading + info,
591            tooltip: tooltip,
592            addClass: this.tree.options.classNames.nodeWait
593          });
594        }
595        break;
596      case DTNodeStatus_Error:
597        this._isLoading = false;
598//        $(this.span).addClass(this.tree.options.classNames.nodeError);
599        this._setStatusNode({
600          title: this.tree.options.strings.loadError + info,
601          tooltip: tooltip,
602          addClass: this.tree.options.classNames.nodeError
603        });
604        break;
605      default:
606        throw "Bad LazyNodeStatus: '" + lts + "'.";
607    }
608  },
609
610  _parentList: function(includeRoot, includeSelf) {
611    var l = [];
612    var dtn = includeSelf ? this : this.parent;
613    while( dtn ) {
614      if( includeRoot || dtn.parent ){
615        l.unshift(dtn);
616      }
617      dtn = dtn.parent;
618    }
619    return l;
620  },
621  getLevel: function() {
622    /**
623     * Return node depth. 0: System root node, 1: visible top-level node.
624     */
625    var level = 0;
626    var dtn = this.parent;
627    while( dtn ) {
628      level++;
629      dtn = dtn.parent;
630    }
631    return level;
632  },
633
634  _getTypeForOuterNodeEvent: function(event) {
635    /** Return the inner node span (title, checkbox or expander) if
636     *  event.target points to the outer span.
637     *  This function should fix issue #93:
638     *  FF2 ignores empty spans, when generating events (returning the parent instead).
639     */
640    var cns = this.tree.options.classNames;
641    var target = event.target;
642    // Only process clicks on an outer node span (probably due to a FF2 event handling bug)
643    if( target.className.indexOf(cns.node) < 0 ) {
644      return null;
645    }
646    // Event coordinates, relative to outer node span:
647    var eventX = event.pageX - target.offsetLeft;
648    var eventY = event.pageY - target.offsetTop;
649
650    for(var i=0, l=target.childNodes.length; i<l; i++) {
651      var cn = target.childNodes[i];
652      var x = cn.offsetLeft - target.offsetLeft;
653      var y = cn.offsetTop - target.offsetTop;
654      var nx = cn.clientWidth, ny = cn.clientHeight;
655//          alert (cn.className + ": " + x + ", " + y + ", s:" + nx + ", " + ny);
656      if( eventX >= x && eventX <= (x+nx) && eventY >= y && eventY <= (y+ny) ) {
657//              alert("HIT "+ cn.className);
658        if( cn.className==cns.title ){
659          return "title";
660        }else if( cn.className==cns.expander ){
661          return "expander";
662        }else if( cn.className==cns.checkbox ){
663          return "checkbox";
664        }else if( cn.className==cns.nodeIcon ){
665          return "icon";
666        }
667      }
668    }
669    return "prefix";
670  },
671
672  getEventTargetType: function(event) {
673    // Return the part of a node, that a click event occured on.
674    // Note: there is no check, if the event was fired on THIS node.
675    var tcn = event && event.target ? event.target.className : "",
676      cns = this.tree.options.classNames;
677
678    if( tcn === cns.title ){
679      return "title";
680    }else if( tcn === cns.expander ){
681      return "expander";
682    }else if( tcn === cns.checkbox ){
683      return "checkbox";
684    }else if( tcn === cns.nodeIcon ){
685      return "icon";
686    }else if( tcn === cns.empty || tcn === cns.vline || tcn === cns.connector ){
687      return "prefix";
688    }else if( tcn.indexOf(cns.node) >= 0 ){
689      // FIX issue #93
690      return this._getTypeForOuterNodeEvent(event);
691    }
692    return null;
693  },
694
695  isVisible: function() {
696    // Return true, if all parents are expanded.
697    var parents = this._parentList(true, false);
698    for(var i=0, l=parents.length; i<l; i++){
699      if( ! parents[i].bExpanded ){ return false; }
700    }
701    return true;
702  },
703
704  makeVisible: function() {
705    // Make sure, all parents are expanded
706    var parents = this._parentList(true, false);
707    for(var i=0, l=parents.length; i<l; i++){
708      parents[i]._expand(true);
709    }
710  },
711
712  focus: function() {
713    // TODO: check, if we already have focus
714//    this.tree.logDebug("dtnode.focus(): %o", this);
715    this.makeVisible();
716    try {
717      $(this.span).find(">a").focus();
718    } catch(e) { }
719  },
720
721  isFocused: function() {
722    return (this.tree.tnFocused === this);
723  },
724
725  _activate: function(flag, fireEvents) {
726    // (De)Activate - but not focus - this node.
727    this.tree.logDebug("dtnode._activate(%o, fireEvents=%o) - %o", flag, fireEvents, this);
728    var opts = this.tree.options;
729    if( this.data.isStatusNode ){
730      return;
731    }
732    if ( fireEvents && opts.onQueryActivate && opts.onQueryActivate.call(this.tree, flag, this) === false ){
733      return; // Callback returned false
734    }
735    if( flag ) {
736      // Activate
737      if( this.tree.activeNode ) {
738        if( this.tree.activeNode === this ){
739          return;
740        }
741        this.tree.activeNode.deactivate();
742      }
743      if( opts.activeVisible ){
744        this.makeVisible();
745      }
746      this.tree.activeNode = this;
747      if( opts.persist ){
748        $.cookie(opts.cookieId+"-active", this.data.key, opts.cookie);
749      }
750      this.tree.persistence.activeKey = this.data.key;
751      $(this.span).addClass(opts.classNames.active);
752      if ( fireEvents && opts.onActivate ){
753        opts.onActivate.call(this.tree, this);
754      }
755    } else {
756      // Deactivate
757      if( this.tree.activeNode === this ) {
758        if ( opts.onQueryActivate && opts.onQueryActivate.call(this.tree, false, this) === false ){
759          return; // Callback returned false
760        }
761        $(this.span).removeClass(opts.classNames.active);
762        if( opts.persist ) {
763          // Note: we don't pass null, but ''. So the cookie is not deleted.
764          // If we pass null, we also have to pass a COPY of opts, because $cookie will override opts.expires (issue 84)
765          $.cookie(opts.cookieId+"-active", "", opts.cookie);
766        }
767        this.tree.persistence.activeKey = null;
768        this.tree.activeNode = null;
769        if ( fireEvents && opts.onDeactivate ){
770          opts.onDeactivate.call(this.tree, this);
771        }
772      }
773    }
774  },
775
776  activate: function() {
777    // Select - but not focus - this node.
778//    this.tree.logDebug("dtnode.activate(): %o", this);
779    this._activate(true, true);
780  },
781
782  activateSilently: function() {
783    this._activate(true, false);
784  },
785
786  deactivate: function() {
787//    this.tree.logDebug("dtnode.deactivate(): %o", this);
788    this._activate(false, true);
789  },
790
791  isActive: function() {
792    return (this.tree.activeNode === this);
793  },
794
795  _userActivate: function() {
796    // Handle user click / [space] / [enter], according to clickFolderMode.
797    var activate = true;
798    var expand = false;
799    if ( this.data.isFolder ) {
800      switch( this.tree.options.clickFolderMode ) {
801      case 2:
802        activate = false;
803        expand = true;
804        break;
805      case 3:
806        activate = expand = true;
807        break;
808      }
809    }
810    if( this.parent === null ) {
811      expand = false;
812    }
813    if( expand ) {
814      this.toggleExpand();
815      this.focus();
816    }
817    if( activate ) {
818      this.activate();
819    }
820  },
821
822  _setSubSel: function(hasSubSel) {
823    if( hasSubSel ) {
824      this.hasSubSel = true;
825      $(this.span).addClass(this.tree.options.classNames.partsel);
826    } else {
827      this.hasSubSel = false;
828      $(this.span).removeClass(this.tree.options.classNames.partsel);
829    }
830  },
831  /**
832   * Fix selection and partsel status, of parent nodes, according to current status of
833   * end nodes.
834   */
835  _updatePartSelectionState: function() {
836//    alert("_updatePartSelectionState " + this);
837//    this.tree.logDebug("_updatePartSelectionState() - %o", this);
838    var sel;
839    // Return `true` or `false` for end nodes and remove part-sel flag
840    if( ! this.hasChildren() ){
841      sel = (this.bSelected && !this.data.unselectable && !this.data.isStatusNode);
842      this._setSubSel(false);
843      return sel;
844    }
845    // Return `true`, `false`, or `undefined` for parent nodes
846    var i, l,
847      cl = this.childList,
848      allSelected = true,
849      allDeselected = true;
850    for(i=0, l=cl.length; i<l;  i++) {
851      var n = cl[i],
852        s = n._updatePartSelectionState();
853      if( s !== false){
854        allDeselected = false;
855      }
856      if( s !== true){
857        allSelected = false;
858      }
859    }
860    if( allSelected ){
861      sel = true;
862    } else if ( allDeselected ){
863      sel = false;
864    } else {
865      sel = undefined;
866    }
867    this._setSubSel(sel === undefined);
868    this.bSelected = (sel === true);
869    return sel;
870  },
871
872  /**
873   * Fix selection status, after this node was (de)selected in multi-hier mode.
874   * This includes (de)selecting all children.
875   */
876  _fixSelectionState: function() {
877//    alert("_fixSelectionState " + this);
878//    this.tree.logDebug("_fixSelectionState(%s) - %o", this.bSelected, this);
879    var p, i, l;
880    if( this.bSelected ) {
881      // Select all children
882      this.visit(function(node){
883        node.parent._setSubSel(true);
884        if(!node.data.unselectable){
885          node._select(true, false, false);
886        }
887      });
888      // Select parents, if all children are selected
889      p = this.parent;
890      while( p ) {
891        p._setSubSel(true);
892        var allChildsSelected = true;
893        for(i=0, l=p.childList.length; i<l;  i++) {
894          var n = p.childList[i];
895          if( !n.bSelected && !n.data.isStatusNode && !n.data.unselectable) {
896          // issue 305 proposes this:
897//          if( !n.bSelected && !n.data.isStatusNode ) {
898            allChildsSelected = false;
899            break;
900          }
901        }
902        if( allChildsSelected ){
903          p._select(true, false, false);
904        }
905        p = p.parent;
906      }
907    } else {
908      // Deselect all children
909      this._setSubSel(false);
910      this.visit(function(node){
911        node._setSubSel(false);
912        node._select(false, false, false);
913      });
914      // Deselect parents, and recalc hasSubSel
915      p = this.parent;
916      while( p ) {
917        p._select(false, false, false);
918        var isPartSel = false;
919        for(i=0, l=p.childList.length; i<l;  i++) {
920          if( p.childList[i].bSelected || p.childList[i].hasSubSel ) {
921            isPartSel = true;
922            break;
923          }
924        }
925        p._setSubSel(isPartSel);
926        p = p.parent;
927      }
928    }
929  },
930
931  _select: function(sel, fireEvents, deep) {
932    // Select - but not focus - this node.
933//    this.tree.logDebug("dtnode._select(%o) - %o", sel, this);
934    var opts = this.tree.options;
935    if( this.data.isStatusNode ){
936      return;
937    }
938    //
939    if( this.bSelected === sel ) {
940//      this.tree.logDebug("dtnode._select(%o) IGNORED - %o", sel, this);
941      return;
942    }
943    // Allow event listener to abort selection
944    if ( fireEvents && opts.onQuerySelect && opts.onQuerySelect.call(this.tree, sel, this) === false ){
945      return; // Callback returned false
946    }
947    // Force single-selection
948    if( opts.selectMode==1 && sel ) {
949      this.tree.visit(function(node){
950        if( node.bSelected ) {
951          // Deselect; assuming that in selectMode:1 there's max. one other selected node
952          node._select(false, false, false);
953          return false;
954        }
955      });
956    }
957
958    this.bSelected = sel;
959//        this.tree._changeNodeList("select", this, sel);
960
961    if( sel ) {
962      if( opts.persist ){
963        this.tree.persistence.addSelect(this.data.key);
964      }
965      $(this.span).addClass(opts.classNames.selected);
966
967      if( deep && opts.selectMode === 3 ){
968        this._fixSelectionState();
969      }
970      if ( fireEvents && opts.onSelect ){
971        opts.onSelect.call(this.tree, true, this);
972      }
973    } else {
974      if( opts.persist ){
975        this.tree.persistence.clearSelect(this.data.key);
976      }
977      $(this.span).removeClass(opts.classNames.selected);
978
979      if( deep && opts.selectMode === 3 ){
980        this._fixSelectionState();
981      }
982      if ( fireEvents && opts.onSelect ){
983        opts.onSelect.call(this.tree, false, this);
984      }
985    }
986  },
987
988  select: function(sel) {
989    // Select - but not focus - this node.
990//    this.tree.logDebug("dtnode.select(%o) - %o", sel, this);
991    if( this.data.unselectable ){
992      return this.bSelected;
993    }
994    return this._select(sel!==false, true, true);
995  },
996
997  toggleSelect: function() {
998//    this.tree.logDebug("dtnode.toggleSelect() - %o", this);
999    return this.select(!this.bSelected);
1000  },
1001
1002  isSelected: function() {
1003    return this.bSelected;
1004  },
1005
1006  isLazy: function() {
1007    return !!this.data.isLazy;
1008  },
1009
1010  _loadContent: function() {
1011    try {
1012      var opts = this.tree.options;
1013      this.tree.logDebug("_loadContent: start - %o", this);
1014      this.setLazyNodeStatus(DTNodeStatus_Loading);
1015      if( true === opts.onLazyRead.call(this.tree, this) ) {
1016        // If function returns 'true', we assume that the loading is done:
1017        this.setLazyNodeStatus(DTNodeStatus_Ok);
1018        // Otherwise (i.e. if the loading was started as an asynchronous process)
1019        // the onLazyRead(dtnode) handler is expected to call dtnode.setLazyNodeStatus(DTNodeStatus_Ok/_Error) when done.
1020        this.tree.logDebug("_loadContent: succeeded - %o", this);
1021      }
1022    } catch(e) {
1023      this.tree.logWarning("_loadContent: failed - %o", e);
1024      this.setLazyNodeStatus(DTNodeStatus_Error, {tooltip: ""+e});
1025    }
1026  },
1027
1028  _expand: function(bExpand, forceSync) {
1029    if( this.bExpanded === bExpand ) {
1030      this.tree.logDebug("dtnode._expand(%o) IGNORED - %o", bExpand, this);
1031      return;
1032    }
1033    this.tree.logDebug("dtnode._expand(%o) - %o", bExpand, this);
1034    var opts = this.tree.options;
1035    if( !bExpand && this.getLevel() < opts.minExpandLevel ) {
1036      this.tree.logDebug("dtnode._expand(%o) prevented collapse - %o", bExpand, this);
1037      return;
1038    }
1039    if ( opts.onQueryExpand && opts.onQueryExpand.call(this.tree, bExpand, this) === false ){
1040      return; // Callback returned false
1041    }
1042    this.bExpanded = bExpand;
1043
1044    // Persist expand state
1045    if( opts.persist ) {
1046      if( bExpand ){
1047        this.tree.persistence.addExpand(this.data.key);
1048      }else{
1049        this.tree.persistence.clearExpand(this.data.key);
1050      }
1051    }
1052    // Do not apply animations in init phase, or before lazy-loading
1053    var allowEffects = !(this.data.isLazy && this.childList === null)
1054      && !this._isLoading
1055      && !forceSync;
1056    this.render(allowEffects);
1057
1058    // Auto-collapse mode: collapse all siblings
1059    if( this.bExpanded && this.parent && opts.autoCollapse ) {
1060      var parents = this._parentList(false, true);
1061      for(var i=0, l=parents.length; i<l; i++){
1062        parents[i].collapseSiblings();
1063      }
1064    }
1065    // If the currently active node is now hidden, deactivate it
1066    if( opts.activeVisible && this.tree.activeNode && ! this.tree.activeNode.isVisible() ) {
1067      this.tree.activeNode.deactivate();
1068    }
1069    // Expanding a lazy node: set 'loading...' and call callback
1070    if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
1071      this._loadContent();
1072      return;
1073    }
1074    if ( opts.onExpand ){
1075      opts.onExpand.call(this.tree, bExpand, this);
1076    }
1077  },
1078
1079  isExpanded: function() {
1080    return this.bExpanded;
1081  },
1082
1083  expand: function(flag) {
1084    flag = (flag !== false);
1085    if( !this.childList && !this.data.isLazy && flag ){
1086      return; // Prevent expanding empty nodes
1087    } else if( this.parent === null && !flag ){
1088      return; // Prevent collapsing the root
1089    }
1090    this._expand(flag);
1091  },
1092
1093  scheduleAction: function(mode, ms) {
1094    /** Schedule activity for delayed execution (cancel any pending request).
1095     *  scheduleAction('cancel') will cancel the request.
1096     */
1097    if( this.tree.timer ) {
1098      clearTimeout(this.tree.timer);
1099      this.tree.logDebug("clearTimeout(%o)", this.tree.timer);
1100    }
1101    var self = this; // required for closures
1102    switch (mode) {
1103    case "cancel":
1104      // Simply made sure that timer was cleared
1105      break;
1106    case "expand":
1107      this.tree.timer = setTimeout(function(){
1108        self.tree.logDebug("setTimeout: trigger expand");
1109        self.expand(true);
1110      }, ms);
1111      break;
1112    case "activate":
1113      this.tree.timer = setTimeout(function(){
1114        self.tree.logDebug("setTimeout: trigger activate");
1115        self.activate();
1116      }, ms);
1117      break;
1118    default:
1119      throw "Invalid mode " + mode;
1120    }
1121    this.tree.logDebug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
1122  },
1123
1124  toggleExpand: function() {
1125    this.expand(!this.bExpanded);
1126  },
1127
1128  collapseSiblings: function() {
1129    if( this.parent === null ){
1130      return;
1131    }
1132    var ac = this.parent.childList;
1133    for (var i=0, l=ac.length; i<l; i++) {
1134      if ( ac[i] !== this && ac[i].bExpanded ){
1135        ac[i]._expand(false);
1136      }
1137    }
1138  },
1139
1140  _onClick: function(event) {
1141//    this.tree.logDebug("dtnode.onClick(" + event.type + "): dtnode:" + this + ", button:" + event.button + ", which: " + event.which);
1142    var targetType = this.getEventTargetType(event);
1143    if( targetType === "expander" ) {
1144      // Clicking the expander icon always expands/collapses
1145      this.toggleExpand();
1146      this.focus(); // issue 95
1147    } else if( targetType === "checkbox" ) {
1148      // Clicking the checkbox always (de)selects
1149      this.toggleSelect();
1150      this.focus(); // issue 95
1151    } else {
1152      this._userActivate();
1153      var aTag = this.span.getElementsByTagName("a");
1154      if(aTag[0]){
1155        // issue 154, 313
1156        if(!($.browser.msie && parseInt($.browser.version, 10) < 9)){
1157          aTag[0].focus();
1158        }
1159      }else{
1160        // 'noLink' option was set
1161        return true;
1162      }
1163    }
1164    // Make sure that clicks stop, otherwise <a href='#'> jumps to the top
1165    event.preventDefault();
1166  },
1167
1168  _onDblClick: function(event) {
1169//    this.tree.logDebug("dtnode.onDblClick(" + event.type + "): dtnode:" + this + ", button:" + event.button + ", which: " + event.which);
1170  },
1171
1172  _onKeydown: function(event) {
1173//    this.tree.logDebug("dtnode.onKeydown(" + event.type + "): dtnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
1174    var handled = true,
1175      sib;
1176//    alert("keyDown" + event.which);
1177
1178    switch( event.which ) {
1179      // charCodes:
1180//      case 43: // '+'
1181      case 107: // '+'
1182      case 187: // '+' @ Chrome, Safari
1183        if( !this.bExpanded ){ this.toggleExpand(); }
1184        break;
1185//      case 45: // '-'
1186      case 109: // '-'
1187      case 189: // '+' @ Chrome, Safari
1188        if( this.bExpanded ){ this.toggleExpand(); }
1189        break;
1190      //~ case 42: // '*'
1191        //~ break;
1192      //~ case 47: // '/'
1193        //~ break;
1194      // case 13: // <enter>
1195        // <enter> on a focused <a> tag seems to generate a click-event.
1196        // this._userActivate();
1197        // break;
1198      case 32: // <space>
1199        this._userActivate();
1200        break;
1201      case 8: // <backspace>
1202        if( this.parent ){
1203          this.parent.focus();
1204        }
1205        break;
1206      case 37: // <left>
1207        if( this.bExpanded ) {
1208          this.toggleExpand();
1209          this.focus();
1210//        } else if( this.parent && (this.tree.options.rootVisible || this.parent.parent) ) {
1211        } else if( this.parent && this.parent.parent ) {
1212          this.parent.focus();
1213        }
1214        break;
1215      case 39: // <right>
1216        if( !this.bExpanded && (this.childList || this.data.isLazy) ) {
1217          this.toggleExpand();
1218          this.focus();
1219        } else if( this.childList ) {
1220          this.childList[0].focus();
1221        }
1222        break;
1223      case 38: // <up>
1224        sib = this.getPrevSibling();
1225        while( sib && sib.bExpanded && sib.childList ){
1226          sib = sib.childList[sib.childList.length-1];
1227        }
1228//        if( !sib && this.parent && (this.tree.options.rootVisible || this.parent.parent) )
1229        if( !sib && this.parent && this.parent.parent ){
1230          sib = this.parent;
1231        }
1232        if( sib ){
1233          sib.focus();
1234        }
1235        break;
1236      case 40: // <down>
1237        if( this.bExpanded && this.childList ) {
1238          sib = this.childList[0];
1239        } else {
1240          var parents = this._parentList(false, true);
1241          for(var i=parents.length-1; i>=0; i--) {
1242            sib = parents[i].getNextSibling();
1243            if( sib ){ break; }
1244          }
1245        }
1246        if( sib ){
1247          sib.focus();
1248        }
1249        break;
1250      default:
1251        handled = false;
1252    }
1253    // Return false, if handled, to prevent default processing
1254//    return !handled;
1255    if(handled){
1256      event.preventDefault();
1257    }
1258  },
1259
1260  _onKeypress: function(event) {
1261    // onKeypress is only hooked to allow user callbacks.
1262    // We don't process it, because IE and Safari don't fire keypress for cursor keys.
1263//    this.tree.logDebug("dtnode.onKeypress(" + event.type + "): dtnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
1264  },
1265
1266  _onFocus: function(event) {
1267    // Handles blur and focus events.
1268//    this.tree.logDebug("dtnode._onFocus(%o): %o", event, this);
1269    var opts = this.tree.options;
1270    if ( event.type == "blur" || event.type == "focusout" ) {
1271      if ( opts.onBlur ){
1272        opts.onBlur.call(this.tree, this);
1273      }
1274      if( this.tree.tnFocused ){
1275        $(this.tree.tnFocused.span).removeClass(opts.classNames.focused);
1276      }
1277      this.tree.tnFocused = null;
1278      if( opts.persist ){
1279        $.cookie(opts.cookieId+"-focus", "", opts.cookie);
1280      }
1281    } else if ( event.type=="focus" || event.type=="focusin") {
1282      // Fix: sometimes the blur event is not generated
1283      if( this.tree.tnFocused && this.tree.tnFocused !== this ) {
1284        this.tree.logDebug("dtnode.onFocus: out of sync: curFocus: %o", this.tree.tnFocused);
1285        $(this.tree.tnFocused.span).removeClass(opts.classNames.focused);
1286      }
1287      this.tree.tnFocused = this;
1288      if ( opts.onFocus ){
1289        opts.onFocus.call(this.tree, this);
1290      }
1291      $(this.tree.tnFocused.span).addClass(opts.classNames.focused);
1292      if( opts.persist ){
1293        $.cookie(opts.cookieId+"-focus", this.data.key, opts.cookie);
1294      }
1295    }
1296    // TODO: return anything?
1297//    return false;
1298  },
1299
1300  visit: function(fn, includeSelf) {
1301    // Call fn(node) for all child nodes. Stop iteration, if fn() returns false.
1302    var res = true;
1303    if( includeSelf === true ) {
1304      res = fn(this);
1305      if( res === false || res == "skip" ){
1306        return res;
1307      }
1308    }
1309    if(this.childList){
1310      for(var i=0, l=this.childList.length; i<l; i++){
1311        res = this.childList[i].visit(fn, true);
1312        if( res === false ){
1313          break;
1314        }
1315      }
1316    }
1317    return res;
1318  },
1319
1320  visitParents: function(fn, includeSelf) {
1321    // Visit parent nodes (bottom up)
1322    if(includeSelf && fn(this) === false){
1323      return false;
1324    }
1325    var p = this.parent;
1326    while( p ) {
1327      if(fn(p) === false){
1328        return false;
1329      }
1330      p = p.parent;
1331    }
1332    return true;
1333  },
1334
1335  remove: function() {
1336    // Remove this node
1337//    this.tree.logDebug ("%s.remove()", this);
1338    if ( this === this.tree.root ){
1339      throw "Cannot remove system root";
1340    }
1341    return this.parent.removeChild(this);
1342  },
1343
1344  removeChild: function(tn) {
1345    // Remove tn from list of direct children.
1346    var ac = this.childList;
1347    if( ac.length == 1 ) {
1348      if( tn !== ac[0] ){
1349        throw "removeChild: invalid child";
1350      }
1351      return this.removeChildren();
1352    }
1353    if( tn === this.tree.activeNode ){
1354      tn.deactivate();
1355    }
1356    if( this.tree.options.persist ) {
1357      if( tn.bSelected ){
1358        this.tree.persistence.clearSelect(tn.data.key);
1359      }
1360      if ( tn.bExpanded ){
1361        this.tree.persistence.clearExpand(tn.data.key);
1362      }
1363    }
1364    tn.removeChildren(true);
1365//    this.div.removeChild(tn.div);
1366    this.ul.removeChild(tn.li);
1367    for(var i=0, l=ac.length; i<l; i++) {
1368      if( ac[i] === tn ) {
1369        this.childList.splice(i, 1);
1370//        delete tn;  // JSLint complained
1371        break;
1372      }
1373    }
1374  },
1375
1376  removeChildren: function(isRecursiveCall, retainPersistence) {
1377    // Remove all child nodes (more efficiently than recursive remove())
1378    this.tree.logDebug("%s.removeChildren(%o)", this, isRecursiveCall);
1379    var tree = this.tree;
1380    var ac = this.childList;
1381    if( ac ) {
1382      for(var i=0, l=ac.length; i<l; i++) {
1383        var tn = ac[i];
1384        if ( tn === tree.activeNode && !retainPersistence ){
1385          tn.deactivate();
1386        }
1387        if( this.tree.options.persist && !retainPersistence ) {
1388          if( tn.bSelected ){
1389            this.tree.persistence.clearSelect(tn.data.key);
1390          }
1391          if ( tn.bExpanded ){
1392            this.tree.persistence.clearExpand(tn.data.key);
1393          }
1394        }
1395        tn.removeChildren(true, retainPersistence);
1396        if(this.ul){
1397//          this.ul.removeChild(tn.li);
1398          $("li", $(this.ul)).remove(); // issue 231
1399        }
1400//        delete tn;  JSLint complained
1401      }
1402      // Set to 'null' which is interpreted as 'not yet loaded' for lazy
1403      // nodes
1404      this.childList = null;
1405    }
1406    if( ! isRecursiveCall ) {
1407//      this._expand(false);
1408//      this.isRead = false;
1409      this._isLoading = false;
1410      this.render();
1411    }
1412  },
1413
1414  setTitle: function(title) {
1415    this.fromDict({title: title});
1416  },
1417
1418  reload: function(force) {
1419    throw "Use reloadChildren() instead";
1420  },
1421
1422  reloadChildren: function(callback) {
1423    // Reload lazy content (expansion state is maintained).
1424    if( this.parent === null ){
1425      throw "Use tree.reload() instead";
1426    }else if( ! this.data.isLazy ){
1427      throw "node.reloadChildren() requires lazy nodes.";
1428    }
1429    // appendAjax triggers 'nodeLoaded' event.
1430    // We listen to this, if a callback was passed to reloadChildren
1431    if(callback){
1432      var self = this;
1433      var eventType = "nodeLoaded.dynatree." + this.tree.$tree.attr("id")
1434        + "." + this.data.key;
1435      this.tree.$tree.bind(eventType, function(e, node, isOk){
1436        self.tree.$tree.unbind(eventType);
1437        self.tree.logDebug("loaded %o, %o, %o", e, node, isOk);
1438        if(node !== self){
1439          throw "got invalid load event";
1440        }
1441        callback.call(self.tree, node, isOk);
1442      });
1443    }
1444    // The expansion state is maintained
1445    this.removeChildren();
1446    this._loadContent();
1447//    if( this.bExpanded ) {
1448//      // Remove children first, to prevent effects being applied
1449//      this.removeChildren();
1450//      // then force re-expand to trigger lazy loading
1451////      this.expand(false);
1452////      this.expand(true);
1453//      this._loadContent();
1454//    } else {
1455//      this.removeChildren();
1456//      this._loadContent();
1457//    }
1458  },
1459
1460  /**
1461   * Make sure the node with a given key path is available in the tree.
1462   */
1463  _loadKeyPath: function(keyPath, callback) {
1464    var tree = this.tree;
1465    tree.logDebug("%s._loadKeyPath(%s)", this, keyPath);
1466    if(keyPath === ""){
1467      throw "Key path must not be empty";
1468    }
1469    var segList = keyPath.split(tree.options.keyPathSeparator);
1470    if(segList[0] === ""){
1471      throw "Key path must be relative (don't start with '/')";
1472    }
1473    var seg = segList.shift();
1474    if(this.childList){
1475      for(var i=0, l=this.childList.length; i < l; i++){
1476        var child = this.childList[i];
1477        if( child.data.key === seg ){
1478          if(segList.length === 0) {
1479            // Found the end node
1480            callback.call(tree, child, "ok");
1481
1482          }else if(child.data.isLazy && (child.childList === null || child.childList === undefined)){
1483            tree.logDebug("%s._loadKeyPath(%s) -> reloading %s...", this, keyPath, child);
1484            var self = this;
1485            // Note: this line gives a JSLint warning (Don't make functions within a loop)
1486            /*jshint loopfunc:true */
1487            child.reloadChildren(function(node, isOk){
1488              // After loading, look for direct child with that key
1489              if(isOk){
1490                tree.logDebug("%s._loadKeyPath(%s) -> reloaded %s.", node, keyPath, node);
1491                callback.call(tree, child, "loaded");
1492                node._loadKeyPath(segList.join(tree.options.keyPathSeparator), callback);
1493              }else{
1494                tree.logWarning("%s._loadKeyPath(%s) -> reloadChildren() failed.", self, keyPath);
1495                callback.call(tree, child, "error");
1496              }
1497            });
1498            // we can ignore it, since it will only be exectuted once, the the loop is ended
1499            // See also http://stackoverflow.com/questions/3037598/how-to-get-around-the-jslint-error-dont-make-functions-within-a-loop
1500          } else {
1501            callback.call(tree, child, "loaded");
1502            // Look for direct child with that key
1503            child._loadKeyPath(segList.join(tree.options.keyPathSeparator), callback);
1504          }
1505          return;
1506        }
1507      }
1508    }
1509    // Could not find key
1510    // Callback params: child: undefined, the segment, isEndNode (segList.length === 0)
1511    callback.call(tree, undefined, "notfound", seg, segList.length === 0);
1512    tree.logWarning("Node not found: " + seg);
1513    return;
1514  },
1515
1516  resetLazy: function() {
1517    // Discard lazy content.
1518    if( this.parent === null ){
1519      throw "Use tree.reload() instead";
1520    }else if( ! this.data.isLazy ){
1521      throw "node.resetLazy() requires lazy nodes.";
1522    }
1523    this.expand(false);
1524    this.removeChildren();
1525  },
1526
1527  _addChildNode: function(dtnode, beforeNode) {
1528    /**
1529     * Internal function to add one single DynatreeNode as a child.
1530     *
1531     */
1532    var tree = this.tree,
1533      opts = tree.options,
1534      pers = tree.persistence;
1535
1536//    tree.logDebug("%s._addChildNode(%o)", this, dtnode);
1537
1538    // --- Update and fix dtnode attributes if necessary
1539    dtnode.parent = this;
1540//    if( beforeNode && (beforeNode.parent !== this || beforeNode === dtnode ) )
1541//      throw "<beforeNode> must be another child of <this>";
1542
1543    // --- Add dtnode as a child
1544    if ( this.childList === null ) {
1545      this.childList = [];
1546    } else if( ! beforeNode ) {
1547      // Fix 'lastsib'
1548      if(this.childList.length > 0) {
1549        $(this.childList[this.childList.length-1].span).removeClass(opts.classNames.lastsib);
1550      }
1551    }
1552    if( beforeNode ) {
1553      var iBefore = $.inArray(beforeNode, this.childList);
1554      if( iBefore < 0 ){
1555        throw "<beforeNode> must be a child of <this>";
1556      }
1557      this.childList.splice(iBefore, 0, dtnode);
1558    } else {
1559      // Append node
1560      this.childList.push(dtnode);
1561    }
1562
1563    // --- Handle persistence
1564    // Initial status is read from cookies, if persistence is active and
1565    // cookies are already present.
1566    // Otherwise the status is read from the data attributes and then persisted.
1567    var isInitializing = tree.isInitializing();
1568    if( opts.persist && pers.cookiesFound && isInitializing ) {
1569      // Init status from cookies
1570//      tree.logDebug("init from cookie, pa=%o, dk=%o", pers.activeKey, dtnode.data.key);
1571      if( pers.activeKey === dtnode.data.key ){
1572        tree.activeNode = dtnode;
1573      }
1574      if( pers.focusedKey === dtnode.data.key ){
1575        tree.focusNode = dtnode;
1576      }
1577      dtnode.bExpanded = ($.inArray(dtnode.data.key, pers.expandedKeyList) >= 0);
1578      dtnode.bSelected = ($.inArray(dtnode.data.key, pers.selectedKeyList) >= 0);
1579//      tree.logDebug("    key=%o, bSelected=%o", dtnode.data.key, dtnode.bSelected);
1580    } else {
1581      // Init status from data (Note: we write the cookies after the init phase)
1582//      tree.logDebug("init from data");
1583      if( dtnode.data.activate ) {
1584        tree.activeNode = dtnode;
1585        if( opts.persist ){
1586          pers.activeKey = dtnode.data.key;
1587        }
1588      }
1589      if( dtnode.data.focus ) {
1590        tree.focusNode = dtnode;
1591        if( opts.persist ){
1592          pers.focusedKey = dtnode.data.key;
1593        }
1594      }
1595      dtnode.bExpanded = ( dtnode.data.expand === true ); // Collapsed by default
1596      if( dtnode.bExpanded && opts.persist ){
1597        pers.addExpand(dtnode.data.key);
1598      }
1599      dtnode.bSelected = ( dtnode.data.select === true ); // Deselected by default
1600/*
1601      Doesn't work, cause pers.selectedKeyList may be null
1602      if( dtnode.bSelected && opts.selectMode==1
1603        && pers.selectedKeyList && pers.selectedKeyList.length>0 ) {
1604        tree.logWarning("Ignored multi-selection in single-mode for %o", dtnode);
1605        dtnode.bSelected = false; // Fixing bad input data (multi selection for mode:1)
1606      }
1607*/
1608      if( dtnode.bSelected && opts.persist ){
1609        pers.addSelect(dtnode.data.key);
1610      }
1611    }
1612
1613    // Always expand, if it's below minExpandLevel
1614//    tree.logDebug ("%s._addChildNode(%o), l=%o", this, dtnode, dtnode.getLevel());
1615    if ( opts.minExpandLevel >= dtnode.getLevel() ) {
1616//      tree.logDebug ("Force expand for %o", dtnode);
1617      this.bExpanded = true;
1618    }
1619
1620    // In multi-hier mode, update the parents selection state
1621    // issue #82: only if not initializing, because the children may not exist yet
1622//    if( !dtnode.data.isStatusNode && opts.selectMode==3 && !isInitializing )
1623//      dtnode._fixSelectionState();
1624
1625    // In multi-hier mode, update the parents selection state
1626    if( dtnode.bSelected && opts.selectMode==3 ) {
1627      var p = this;
1628      while( p ) {
1629        if( !p.hasSubSel ){
1630          p._setSubSel(true);
1631        }
1632        p = p.parent;
1633      }
1634    }
1635    // render this node and the new child
1636    if ( tree.bEnableUpdate ){
1637      this.render();
1638    }
1639    return dtnode;
1640  },
1641
1642  addChild: function(obj, beforeNode) {
1643    /**
1644     * Add a node object as child.
1645     *
1646     * This should be the only place, where a DynaTreeNode is constructed!
1647     * (Except for the root node creation in the tree constructor)
1648     *
1649     * @param obj A JS object (may be recursive) or an array of those.
1650     * @param {DynaTreeNode} beforeNode (optional) sibling node.
1651     *
1652     * Data format: array of node objects, with optional 'children' attributes.
1653     * [
1654     *  { title: "t1", isFolder: true, ... }
1655     *  { title: "t2", isFolder: true, ...,
1656     *    children: [
1657     *      {title: "t2.1", ..},
1658     *      {..}
1659     *      ]
1660     *  }
1661     * ]
1662     * A simple object is also accepted instead of an array.
1663     *
1664     */
1665//    this.tree.logDebug("%s.addChild(%o, %o)", this, obj, beforeNode);
1666    if(typeof(obj) == "string"){
1667      throw "Invalid data type for " + obj;
1668    }else if( !obj || obj.length === 0 ){ // Passed null or undefined or empty array
1669      return;
1670    }else if( obj instanceof DynaTreeNode ){
1671      return this._addChildNode(obj, beforeNode);
1672    }
1673
1674    if( !obj.length ){ // Passed a single data object
1675      obj = [ obj ];
1676    }
1677    var prevFlag = this.tree.enableUpdate(false);
1678
1679    var tnFirst = null;
1680    for (var i=0, l=obj.length; i<l; i++) {
1681      var data = obj[i];
1682      var dtnode = this._addChildNode(new DynaTreeNode(this, this.tree, data), beforeNode);
1683      if( !tnFirst ){
1684        tnFirst = dtnode;
1685      }
1686      // Add child nodes recursively
1687      if( data.children ){
1688        dtnode.addChild(data.children, null);
1689      }
1690    }
1691    this.tree.enableUpdate(prevFlag);
1692    return tnFirst;
1693  },
1694
1695  append: function(obj) {
1696    this.tree.logWarning("node.append() is deprecated (use node.addChild() instead).");
1697    return this.addChild(obj, null);
1698  },
1699
1700  appendAjax: function(ajaxOptions) {
1701    var self = this;
1702    this.removeChildren(false, true);
1703    this.setLazyNodeStatus(DTNodeStatus_Loading);
1704    // Debug feature: force a delay, to simulate slow loading...
1705    if(ajaxOptions.debugLazyDelay){
1706      var ms = ajaxOptions.debugLazyDelay;
1707      ajaxOptions.debugLazyDelay = 0;
1708      this.tree.logInfo("appendAjax: waiting for debugLazyDelay " + ms);
1709      setTimeout(function(){self.appendAjax(ajaxOptions);}, ms);
1710      return;
1711    }
1712    // Ajax option inheritance: $.ajaxSetup < $.ui.dynatree.prototype.options.ajaxDefaults < tree.options.ajaxDefaults < ajaxOptions
1713    var orgSuccess = ajaxOptions.success,
1714      orgError = ajaxOptions.error,
1715      eventType = "nodeLoaded.dynatree." + this.tree.$tree.attr("id") + "." + this.data.key;
1716    var options = $.extend({}, this.tree.options.ajaxDefaults, ajaxOptions, {
1717      success: function(data, textStatus, jqXHR){
1718        // <this> is the request options
1719//        self.tree.logDebug("appendAjax().success");
1720        var prevPhase = self.tree.phase;
1721        self.tree.phase = "init";
1722        // postProcess is similar to the standard dataFilter hook,
1723        // but it is also called for JSONP
1724        if( options.postProcess ){
1725          data = options.postProcess.call(this, data, this.dataType);
1726        }
1727        // Process ASPX WebMethod JSON object inside "d" property
1728        // http://code.google.com/p/dynatree/issues/detail?id=202
1729        else if (data && data.hasOwnProperty("d")) {
1730           data = (typeof data.d) == "string" ? $.parseJSON(data.d) : data.d;
1731        }
1732        if(!$.isArray(data) || data.length !== 0){
1733          self.addChild(data, null);
1734        }
1735        self.tree.phase = "postInit";
1736        if( orgSuccess ){
1737          orgSuccess.call(options, self, data, textStatus);
1738        }
1739        self.tree.logDebug("trigger " + eventType);
1740        self.tree.$tree.trigger(eventType, [self, true]);
1741        self.tree.phase = prevPhase;
1742        // This should be the last command, so node._isLoading is true
1743        // while the callbacks run
1744        self.setLazyNodeStatus(DTNodeStatus_Ok);
1745        if($.isArray(data) && data.length === 0){
1746          // Set to [] which is interpreted as 'no children' for lazy
1747          // nodes
1748          self.childList = [];
1749          self.render();
1750        }
1751        },
1752      error: function(jqXHR, textStatus, errorThrown){
1753        // <this> is the request options
1754        self.tree.logWarning("appendAjax failed:", textStatus, ":\n", jqXHR, "\n", errorThrown);
1755        if( orgError ){
1756          orgError.call(options, self, jqXHR, textStatus, errorThrown);
1757        }
1758        self.tree.$tree.trigger(eventType, [self, false]);
1759        self.setLazyNodeStatus(DTNodeStatus_Error, {info: textStatus, tooltip: "" + errorThrown});
1760        }
1761    });
1762    $.ajax(options);
1763  },
1764
1765  move: function(targetNode, mode) {
1766    /**Move this node to targetNode.
1767     *  mode 'child': append this node as last child of targetNode.
1768     *                This is the default. To be compatble with the D'n'd
1769     *                hitMode, we also accept 'over'.
1770     *  mode 'before': add this node as sibling before targetNode.
1771     *  mode 'after': add this node as sibling after targetNode.
1772     */
1773    var pos;
1774    if(this === targetNode){
1775      return;
1776    }
1777    if( !this.parent  ){
1778      throw "Cannot move system root";
1779    }
1780    if(mode === undefined || mode == "over"){
1781      mode = "child";
1782    }
1783    var prevParent = this.parent;
1784    var targetParent = (mode === "child") ? targetNode : targetNode.parent;
1785    if( targetParent.isDescendantOf(this) ){
1786      throw "Cannot move a node to it's own descendant";
1787    }
1788    // Unlink this node from current parent
1789    if( this.parent.childList.length == 1 ) {
1790      this.parent.childList = this.parent.data.isLazy ? [] : null;
1791      this.parent.bExpanded = false;
1792    } else {
1793      pos = $.inArray(this, this.parent.childList);
1794      if( pos < 0 ){
1795        throw "Internal error";
1796      }
1797      this.parent.childList.splice(pos, 1);
1798    }
1799    // Remove from source DOM parent
1800    if(this.parent.ul){
1801      this.parent.ul.removeChild(this.li);
1802    }
1803
1804    // Insert this node to target parent's child list
1805    this.parent = targetParent;
1806    if( targetParent.hasChildren() ) {
1807      switch(mode) {
1808      case "child":
1809        // Append to existing target children
1810        targetParent.childList.push(this);
1811        break;
1812      case "before":
1813        // Insert this node before target node
1814        pos = $.inArray(targetNode, targetParent.childList);
1815        if( pos < 0 ){
1816          throw "Internal error";
1817        }
1818        targetParent.childList.splice(pos, 0, this);
1819        break;
1820      case "after":
1821        // Insert this node after target node
1822        pos = $.inArray(targetNode, targetParent.childList);
1823        if( pos < 0 ){
1824          throw "Internal error";
1825        }
1826        targetParent.childList.splice(pos+1, 0, this);
1827        break;
1828      default:
1829        throw "Invalid mode " + mode;
1830      }
1831    } else {
1832      targetParent.childList = [ this ];
1833    }
1834    // Parent has no <ul> tag yet:
1835    if( !targetParent.ul ) {
1836      // This is the parent's first child: create UL tag
1837      // (Hidden, because it will be
1838      targetParent.ul = document.createElement("ul");
1839      targetParent.ul.style.display = "none";
1840      targetParent.li.appendChild(targetParent.ul);
1841    }
1842    // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
1843    if(this.li){
1844      targetParent.ul.appendChild(this.li);
1845    }
1846
1847    if( this.tree !== targetNode.tree ) {
1848      // Fix node.tree for all source nodes
1849      this.visit(function(node){
1850        node.tree = targetNode.tree;
1851      }, null, true);
1852      throw "Not yet implemented.";
1853    }
1854    // TODO: fix selection state
1855    // TODO: fix active state
1856    if( !prevParent.isDescendantOf(targetParent)) {
1857      prevParent.render();
1858    }
1859    if( !targetParent.isDescendantOf(prevParent) ) {
1860      targetParent.render();
1861    }
1862//    this.tree.redraw();
1863/*
1864    var tree = this.tree;
1865    var opts = tree.options;
1866    var pers = tree.persistence;
1867
1868
1869    // Always expand, if it's below minExpandLevel
1870//    tree.logDebug ("%s._addChildNode(%o), l=%o", this, dtnode, dtnode.getLevel());
1871    if ( opts.minExpandLevel >= dtnode.getLevel() ) {
1872//      tree.logDebug ("Force expand for %o", dtnode);
1873      this.bExpanded = true;
1874    }
1875
1876    // In multi-hier mode, update the parents selection state
1877    // issue #82: only if not initializing, because the children may not exist yet
1878//    if( !dtnode.data.isStatusNode && opts.selectMode==3 && !isInitializing )
1879//      dtnode._fixSelectionState();
1880
1881    // In multi-hier mode, update the parents selection state
1882    if( dtnode.bSelected && opts.selectMode==3 ) {
1883      var p = this;
1884      while( p ) {
1885        if( !p.hasSubSel )
1886          p._setSubSel(true);
1887        p = p.parent;
1888      }
1889    }
1890    // render this node and the new child
1891    if ( tree.bEnableUpdate )
1892      this.render();
1893
1894    return dtnode;
1895
1896*/
1897  },
1898
1899  // --- end of class
1900  lastentry: undefined
1901};
1902
1903/*************************************************************************
1904 * class DynaTreeStatus
1905 */
1906
1907var DynaTreeStatus = Class.create();
1908
1909
1910DynaTreeStatus._getTreePersistData = function(cookieId, cookieOpts) {
1911  // Static member: Return persistence information from cookies
1912  var ts = new DynaTreeStatus(cookieId, cookieOpts);
1913  ts.read();
1914  return ts.toDict();
1915};
1916// Make available in global scope
1917getDynaTreePersistData = DynaTreeStatus._getTreePersistData; // TODO: deprecated
1918
1919
1920DynaTreeStatus.prototype = {
1921  // Constructor
1922  initialize: function(cookieId, cookieOpts) {
1923//    this._log("DynaTreeStatus: initialize");
1924    if( cookieId === undefined ){
1925      cookieId = $.ui.dynatree.prototype.options.cookieId;
1926    }
1927    cookieOpts = $.extend({}, $.ui.dynatree.prototype.options.cookie, cookieOpts);
1928
1929    this.cookieId = cookieId;
1930    this.cookieOpts = cookieOpts;
1931    this.cookiesFound = undefined;
1932    this.activeKey = null;
1933    this.focusedKey = null;
1934    this.expandedKeyList = null;
1935    this.selectedKeyList = null;
1936  },
1937  // member functions
1938  _log: function(msg) {
1939    //  this.logDebug("_changeNodeList(%o): nodeList:%o, idx:%o", mode, nodeList, idx);
1940    Array.prototype.unshift.apply(arguments, ["debug"]);
1941    _log.apply(this, arguments);
1942  },
1943  read: function() {
1944//    this._log("DynaTreeStatus: read");
1945    // Read or init cookies.
1946    this.cookiesFound = false;
1947
1948    var cookie = $.cookie(this.cookieId + "-active");
1949    this.activeKey = ( cookie === null ) ? "" : cookie;
1950    if( cookie !== null ){
1951      this.cookiesFound = true;
1952    }
1953    cookie = $.cookie(this.cookieId + "-focus");
1954    this.focusedKey = ( cookie === null ) ? "" : cookie;
1955    if( cookie !== null ){
1956      this.cookiesFound = true;
1957    }
1958    cookie = $.cookie(this.cookieId + "-expand");
1959    this.expandedKeyList = ( cookie === null ) ? [] : cookie.split(",");
1960    if( cookie !== null ){
1961      this.cookiesFound = true;
1962    }
1963    cookie = $.cookie(this.cookieId + "-select");
1964    this.selectedKeyList = ( cookie === null ) ? [] : cookie.split(",");
1965    if( cookie !== null ){
1966      this.cookiesFound = true;
1967    }
1968  },
1969  write: function() {
1970//    this._log("DynaTreeStatus: write");
1971    $.cookie(this.cookieId + "-active", ( this.activeKey === null ) ? "" : this.activeKey, this.cookieOpts);
1972    $.cookie(this.cookieId + "-focus", ( this.focusedKey === null ) ? "" : this.focusedKey, this.cookieOpts);
1973    $.cookie(this.cookieId + "-expand", ( this.expandedKeyList === null ) ? "" : this.expandedKeyList.join(","), this.cookieOpts);
1974    $.cookie(this.cookieId + "-select", ( this.selectedKeyList === null ) ? "" : this.selectedKeyList.join(","), this.cookieOpts);
1975  },
1976  addExpand: function(key) {
1977//    this._log("addExpand(%o)", key);
1978    if( $.inArray(key, this.expandedKeyList) < 0 ) {
1979      this.expandedKeyList.push(key);
1980      $.cookie(this.cookieId + "-expand", this.expandedKeyList.join(","), this.cookieOpts);
1981    }
1982  },
1983  clearExpand: function(key) {
1984//    this._log("clearExpand(%o)", key);
1985    var idx = $.inArray(key, this.expandedKeyList);
1986    if( idx >= 0 ) {
1987      this.expandedKeyList.splice(idx, 1);
1988      $.cookie(this.cookieId + "-expand", this.expandedKeyList.join(","), this.cookieOpts);
1989    }
1990  },
1991  addSelect: function(key) {
1992//    this._log("addSelect(%o)", key);
1993    if( $.inArray(key, this.selectedKeyList) < 0 ) {
1994      this.selectedKeyList.push(key);
1995      $.cookie(this.cookieId + "-select", this.selectedKeyList.join(","), this.cookieOpts);
1996    }
1997  },
1998  clearSelect: function(key) {
1999//    this._log("clearSelect(%o)", key);
2000    var idx = $.inArray(key, this.selectedKeyList);
2001    if( idx >= 0 ) {
2002      this.selectedKeyList.splice(idx, 1);
2003      $.cookie(this.cookieId + "-select", this.selectedKeyList.join(","), this.cookieOpts);
2004    }
2005  },
2006  isReloading: function() {
2007    return this.cookiesFound === true;
2008  },
2009  toDict: function() {
2010    return {
2011      cookiesFound: this.cookiesFound,
2012      activeKey: this.activeKey,
2013      focusedKey: this.activeKey,
2014      expandedKeyList: this.expandedKeyList,
2015      selectedKeyList: this.selectedKeyList
2016    };
2017  },
2018  // --- end of class
2019  lastentry: undefined
2020};
2021
2022
2023/*************************************************************************
2024 * class DynaTree
2025 */
2026
2027var DynaTree = Class.create();
2028
2029// --- Static members ----------------------------------------------------------
2030
2031DynaTree.version = "$Version:$";
2032
2033/*
2034DynaTree._initTree = function() {
2035};
2036
2037DynaTree._bind = function() {
2038};
2039*/
2040//--- Class members ------------------------------------------------------------
2041
2042DynaTree.prototype = {
2043  // Constructor
2044//  initialize: function(divContainer, options) {
2045  initialize: function($widget) {
2046    // instance members
2047    this.phase = "init";
2048    this.$widget = $widget;
2049    this.options = $widget.options;
2050    this.$tree = $widget.element;
2051    this.timer = null;
2052    // find container element
2053    this.divTree = this.$tree.get(0);
2054
2055//    var parentPos = $(this.divTree).parent().offset();
2056//    this.parentTop = parentPos.top;
2057//    this.parentLeft = parentPos.left;
2058
2059    _initDragAndDrop(this);
2060  },
2061
2062  // member functions
2063
2064  _load: function(callback) {
2065    var $widget = this.$widget;
2066    var opts = this.options,
2067      self = this;
2068    this.bEnableUpdate = true;
2069    this._nodeCount = 1;
2070    this.activeNode = null;
2071    this.focusNode = null;
2072
2073    // Some deprecation warnings to help with migration
2074    if( opts.rootVisible !== undefined ){
2075      this.logWarning("Option 'rootVisible' is no longer supported.");
2076    }
2077    if( opts.minExpandLevel < 1 ) {
2078      this.logWarning("Option 'minExpandLevel' must be >= 1.");
2079      opts.minExpandLevel = 1;
2080    }
2081//    _log("warn", "jQuery.support.boxModel " + jQuery.support.boxModel);
2082
2083    // If a 'options.classNames' dictionary was passed, still use defaults
2084    // for undefined classes:
2085    if( opts.classNames !== $.ui.dynatree.prototype.options.classNames ) {
2086      opts.classNames = $.extend({}, $.ui.dynatree.prototype.options.classNames, opts.classNames);
2087    }
2088    if( opts.ajaxDefaults !== $.ui.dynatree.prototype.options.ajaxDefaults ) {
2089      opts.ajaxDefaults = $.extend({}, $.ui.dynatree.prototype.options.ajaxDefaults, opts.ajaxDefaults);
2090    }
2091    if( opts.dnd !== $.ui.dynatree.prototype.options.dnd ) {
2092      opts.dnd = $.extend({}, $.ui.dynatree.prototype.options.dnd, opts.dnd);
2093    }
2094    // Guess skin path, if not specified
2095    if(!opts.imagePath) {
2096      $("script").each( function () {
2097        var _rexDtLibName = /.*dynatree[^\/]*\.js$/i;
2098        if( this.src.search(_rexDtLibName) >= 0 ) {
2099          if( this.src.indexOf("/")>=0 ){ // issue #47
2100            opts.imagePath = this.src.slice(0, this.src.lastIndexOf("/")) + "/skin/";
2101          }else{
2102            opts.imagePath = "skin/";
2103          }
2104          self.logDebug("Guessing imagePath from '%s': '%s'", this.src, opts.imagePath);
2105          return false; // first match
2106        }
2107      });
2108    }
2109
2110    this.persistence = new DynaTreeStatus(opts.cookieId, opts.cookie);
2111    if( opts.persist ) {
2112      if( !$.cookie ){
2113        _log("warn", "Please include jquery.cookie.js to use persistence.");
2114      }
2115      this.persistence.read();
2116    }
2117    this.logDebug("DynaTree.persistence: %o", this.persistence.toDict());
2118
2119    // Cached tag strings
2120    this.cache = {
2121      tagEmpty: "<span class='" + opts.classNames.empty + "'></span>",
2122      tagVline: "<span class='" + opts.classNames.vline + "'></span>",
2123      tagExpander: "<span class='" + opts.classNames.expander + "'></span>",
2124      tagConnector: "<span class='" + opts.classNames.connector + "'></span>",
2125      tagNodeIcon: "<span class='" + opts.classNames.nodeIcon + "'></span>",
2126      tagCheckbox: "<span class='" + opts.classNames.checkbox + "'></span>",
2127      lastentry: undefined
2128    };
2129
2130    // Clear container, in case it contained some 'waiting' or 'error' text
2131    // for clients that don't support JS.
2132    // We don't do this however, if we try to load from an embedded UL element.
2133    if( opts.children || (opts.initAjax && opts.initAjax.url) || opts.initId ){
2134      $(this.divTree).empty();
2135    }
2136    var $ulInitialize = this.$tree.find(">ul:first").hide();
2137
2138    // Create the root element
2139    this.tnRoot = new DynaTreeNode(null, this, {});
2140    this.tnRoot.bExpanded = true;
2141    this.tnRoot.render();
2142    this.divTree.appendChild(this.tnRoot.ul);
2143
2144    var root = this.tnRoot,
2145      isReloading = ( opts.persist && this.persistence.isReloading() ),
2146      isLazy = false,
2147      prevFlag = this.enableUpdate(false);
2148
2149    this.logDebug("Dynatree._load(): read tree structure...");
2150
2151    // Init tree structure
2152    if( opts.children ) {
2153      // Read structure from node array
2154      root.addChild(opts.children);
2155
2156    } else if( opts.initAjax && opts.initAjax.url ) {
2157      // Init tree from AJAX request
2158      isLazy = true;
2159      root.data.isLazy = true;
2160      this._reloadAjax(callback);
2161
2162    } else if( opts.initId ) {
2163      // Init tree from another UL element
2164      this._createFromTag(root, $("#"+opts.initId));
2165
2166    } else {
2167      // Init tree from the first UL element inside the container <div>
2168//      var $ul = this.$tree.find(">ul:first").hide();
2169      this._createFromTag(root, $ulInitialize);
2170      $ulInitialize.remove();
2171    }
2172
2173    this._checkConsistency();
2174    // Fix part-sel flags
2175    if(!isLazy && opts.selectMode == 3){
2176      root._updatePartSelectionState();
2177    }
2178    // Render html markup
2179    this.logDebug("Dynatree._load(): render nodes...");
2180    this.enableUpdate(prevFlag);
2181
2182    // bind event handlers
2183    this.logDebug("Dynatree._load(): bind events...");
2184    this.$widget.bind();
2185
2186    // --- Post-load processing
2187    this.logDebug("Dynatree._load(): postInit...");
2188    this.phase = "postInit";
2189
2190    // In persist mode, make sure that cookies are written, even if they are empty
2191    if( opts.persist ) {
2192      this.persistence.write();
2193    }
2194    // Set focus, if possible (this will also fire an event and write a cookie)
2195    if( this.focusNode && this.focusNode.isVisible() ) {
2196      this.logDebug("Focus on init: %o", this.focusNode);
2197      this.focusNode.focus();
2198    }
2199    if( !isLazy ) {
2200      if( opts.onPostInit ) {
2201        opts.onPostInit.call(this, isReloading, false);
2202      }
2203      if( callback ){
2204        callback.call(this, "ok");
2205      }
2206    }
2207    this.phase = "idle";
2208  },
2209
2210  _reloadAjax: function(callback) {
2211    // Reload
2212    var opts = this.options;
2213    if( ! opts.initAjax || ! opts.initAjax.url ){
2214      throw "tree.reload() requires 'initAjax' mode.";
2215    }
2216    var pers = this.persistence;
2217    var ajaxOpts = $.extend({}, opts.initAjax);
2218    // Append cookie info to the request
2219//    this.logDebug("reloadAjax: key=%o, an.key:%o", pers.activeKey, this.activeNode?this.activeNode.data.key:"?");
2220    if( ajaxOpts.addActiveKey ){
2221      ajaxOpts.data.activeKey = pers.activeKey;
2222    }
2223    if( ajaxOpts.addFocusedKey ){
2224      ajaxOpts.data.focusedKey = pers.focusedKey;
2225    }
2226    if( ajaxOpts.addExpandedKeyList ){
2227      ajaxOpts.data.expandedKeyList = pers.expandedKeyList.join(",");
2228    }
2229    if( ajaxOpts.addSelectedKeyList ){
2230      ajaxOpts.data.selectedKeyList = pers.selectedKeyList.join(",");
2231    }
2232    // Set up onPostInit callback to be called when Ajax returns
2233    if( ajaxOpts.success ){
2234      this.logWarning("initAjax: success callback is ignored; use onPostInit instead.");
2235    }
2236    if( ajaxOpts.error ){
2237      this.logWarning("initAjax: error callback is ignored; use onPostInit instead.");
2238    }
2239    var isReloading = pers.isReloading();
2240    ajaxOpts.success = function(dtnode, data, textStatus) {
2241      if(opts.selectMode == 3){
2242        dtnode.tree.tnRoot._updatePartSelectionState();
2243      }
2244      if(opts.onPostInit){
2245        opts.onPostInit.call(dtnode.tree, isReloading, false);
2246      }
2247      if(callback){
2248        callback.call(dtnode.tree, "ok");
2249      }
2250    };
2251    ajaxOpts.error = function(dtnode, XMLHttpRequest, textStatus, errorThrown) {
2252      if(opts.onPostInit){
2253        opts.onPostInit.call(dtnode.tree, isReloading, true, XMLHttpRequest, textStatus, errorThrown);
2254      }
2255      if(callback){
2256        callback.call(dtnode.tree, "error", XMLHttpRequest, textStatus, errorThrown);
2257      }
2258    };
2259//    }
2260    this.logDebug("Dynatree._init(): send Ajax request...");
2261    this.tnRoot.appendAjax(ajaxOpts);
2262  },
2263
2264  toString: function() {
2265//    return "DynaTree '" + this.options.title + "'";
2266    return "Dynatree '" + this.$tree.attr("id") + "'";
2267  },
2268
2269  toDict: function() {
2270    return this.tnRoot.toDict(true);
2271  },
2272
2273  serializeArray: function(stopOnParents) {
2274    // Return a JavaScript array of objects, ready to be encoded as a JSON
2275    // string for selected nodes
2276    var nodeList = this.getSelectedNodes(stopOnParents),
2277      name = this.$tree.attr("name") || this.$tree.attr("id"),
2278      arr = [];
2279    for(var i=0, l=nodeList.length; i<l; i++){
2280      arr.push({name: name, value: nodeList[i].data.key});
2281    }
2282    return arr;
2283  },
2284
2285  getPersistData: function() {
2286    return this.persistence.toDict();
2287  },
2288
2289  logDebug: function(msg) {
2290    if( this.options.debugLevel >= 2 ) {
2291      Array.prototype.unshift.apply(arguments, ["debug"]);
2292      _log.apply(this, arguments);
2293    }
2294  },
2295
2296  logInfo: function(msg) {
2297    if( this.options.debugLevel >= 1 ) {
2298      Array.prototype.unshift.apply(arguments, ["info"]);
2299      _log.apply(this, arguments);
2300    }
2301  },
2302
2303  logWarning: function(msg) {
2304    Array.prototype.unshift.apply(arguments, ["warn"]);
2305    _log.apply(this, arguments);
2306  },
2307
2308  isInitializing: function() {
2309    return ( this.phase=="init" || this.phase=="postInit" );
2310  },
2311  isReloading: function() {
2312    return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
2313  },
2314  isUserEvent: function() {
2315    return ( this.phase=="userEvent" );
2316  },
2317
2318  redraw: function() {
2319//    this.logDebug("dynatree.redraw()...");
2320    this.tnRoot.render(false, false);
2321//    this.logDebug("dynatree.redraw() done.");
2322  },
2323  renderInvisibleNodes: function() {
2324    this.tnRoot.render(false, true);
2325  },
2326  reload: function(callback) {
2327    this._load(callback);
2328  },
2329
2330  getRoot: function() {
2331    return this.tnRoot;
2332  },
2333
2334  enable: function() {
2335    this.$widget.enable();
2336  },
2337
2338  disable: function() {
2339    this.$widget.disable();
2340  },
2341
2342  getNodeByKey: function(key) {
2343    // Search the DOM by element ID (assuming this is faster than traversing all nodes).
2344    // $("#...") has problems, if the key contains '.', so we use getElementById()
2345    var el = document.getElementById(this.options.idPrefix + key);
2346    if( el ){
2347      return el.dtnode ? el.dtnode : null;
2348    }
2349    // Not found in the DOM, but still may be in an unrendered part of tree
2350    var match = null;
2351    this.visit(function(node){
2352//      window.console.log("%s", node);
2353      if(node.data.key == key) {
2354        match = node;
2355        return false;
2356      }
2357    }, true);
2358    return match;
2359  },
2360
2361  getActiveNode: function() {
2362    return this.activeNode;
2363  },
2364
2365  reactivate: function(setFocus) {
2366    // Re-fire onQueryActivate and onActivate events.
2367    var node = this.activeNode;
2368//    this.logDebug("reactivate %o", node);
2369    if( node ) {
2370      this.activeNode = null; // Force re-activating
2371      node.activate();
2372      if( setFocus ){
2373        node.focus();
2374      }
2375    }
2376  },
2377
2378  getSelectedNodes: function(stopOnParents) {
2379    var nodeList = [];
2380    this.tnRoot.visit(function(node){
2381      if( node.bSelected ) {
2382        nodeList.push(node);
2383        if( stopOnParents === true ){
2384          return "skip"; // stop processing this branch
2385        }
2386      }
2387    });
2388    return nodeList;
2389  },
2390
2391  activateKey: function(key) {
2392    var dtnode = (key === null) ? null : this.getNodeByKey(key);
2393    if( !dtnode ) {
2394      if( this.activeNode ){
2395        this.activeNode.deactivate();
2396      }
2397      this.activeNode = null;
2398      return null;
2399    }
2400    dtnode.focus();
2401    dtnode.activate();
2402    return dtnode;
2403  },
2404
2405  loadKeyPath: function(keyPath, callback) {
2406    var segList = keyPath.split(this.options.keyPathSeparator);
2407    // Remove leading '/'
2408    if(segList[0] === ""){
2409      segList.shift();
2410    }
2411    // Remove leading system root key
2412    if(segList[0] == this.tnRoot.data.key){
2413      this.logDebug("Removed leading root key.");
2414      segList.shift();
2415    }
2416    keyPath = segList.join(this.options.keyPathSeparator);
2417    return this.tnRoot._loadKeyPath(keyPath, callback);
2418  },
2419
2420  selectKey: function(key, select) {
2421    var dtnode = this.getNodeByKey(key);
2422    if( !dtnode ){
2423      return null;
2424    }
2425    dtnode.select(select);
2426    return dtnode;
2427  },
2428
2429  enableUpdate: function(bEnable) {
2430    if ( this.bEnableUpdate==bEnable ){
2431      return bEnable;
2432    }
2433    this.bEnableUpdate = bEnable;
2434    if ( bEnable ){
2435      this.redraw();
2436    }
2437    return !bEnable; // return previous value
2438  },
2439
2440  count: function() {
2441    return this.tnRoot.countChildren();
2442  },
2443
2444  visit: function(fn, includeRoot) {
2445    return this.tnRoot.visit(fn, includeRoot);
2446  },
2447
2448  _createFromTag: function(parentTreeNode, $ulParent) {
2449    // Convert a <UL>...</UL> list into children of the parent tree node.
2450    var self = this;
2451/*
2452TODO: better?
2453    this.$lis = $("li:has(a[href])", this.element);
2454    this.$tabs = this.$lis.map(function() { return $("a", this)[0]; });
2455 */
2456    $ulParent.find(">li").each(function() {
2457      var $li = $(this),
2458        $liSpan = $li.find(">span:first"),
2459        $liA = $li.find(">a:first"),
2460        title,
2461        href = null,
2462        target = null,
2463        tooltip;
2464      if( $liSpan.length ) {
2465        // If a <li><span> tag is specified, use it literally.
2466        title = $liSpan.html();
2467      } else if( $liA.length ) {
2468        title = $liA.html();
2469        href = $liA.attr("href");
2470        target = $liA.attr("target");
2471        tooltip = $liA.attr("title");
2472      } else {
2473        // If only a <li> tag is specified, use the trimmed string up to
2474        // the next child <ul> tag.
2475        title = $li.html();
2476        var iPos = title.search(/<ul/i);
2477        if( iPos >= 0 ){
2478          title = $.trim(title.substring(0, iPos));
2479        }else{
2480          title = $.trim(title);
2481        }
2482//        self.logDebug("%o", title);
2483      }
2484      // Parse node options from ID, title and class attributes
2485      var data = {
2486        title: title,
2487        tooltip: tooltip,
2488        isFolder: $li.hasClass("folder"),
2489        isLazy: $li.hasClass("lazy"),
2490        expand: $li.hasClass("expanded"),
2491        select: $li.hasClass("selected"),
2492        activate: $li.hasClass("active"),
2493        focus: $li.hasClass("focused"),
2494        noLink: $li.hasClass("noLink")
2495      };
2496      if( href ){
2497        data.href = href;
2498        data.target = target;
2499      }
2500      if( $li.attr("title") ){
2501        data.tooltip = $li.attr("title"); // overrides <a title='...'>
2502      }
2503      if( $li.attr("id") ){
2504        data.key = $li.attr("id");
2505      }
2506      // If a data attribute is present, evaluate as a JavaScript object
2507      if( $li.attr("data") ) {
2508        var dataAttr = $.trim($li.attr("data"));
2509        if( dataAttr ) {
2510          if( dataAttr.charAt(0) != "{" ){
2511            dataAttr = "{" + dataAttr + "}";
2512          }
2513          try {
2514            $.extend(data, eval("(" + dataAttr + ")"));
2515          } catch(e) {
2516            throw ("Error parsing node data: " + e + "\ndata:\n'" + dataAttr + "'");
2517          }
2518        }
2519      }
2520      var childNode = parentTreeNode.addChild(data);
2521      // Recursive reading of child nodes, if LI tag contains an UL tag
2522      var $ul = $li.find(">ul:first");
2523      if( $ul.length ) {
2524        self._createFromTag(childNode, $ul); // must use 'self', because 'this' is the each() context
2525      }
2526    });
2527  },
2528
2529  _checkConsistency: function() {
2530//    this.logDebug("tree._checkConsistency() NOT IMPLEMENTED - %o", this);
2531  },
2532
2533  _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) {
2534    // hitMode: 'after', 'before', 'over', 'out', 'start', 'stop'
2535    var $source = sourceNode ? $(sourceNode.span) : null,
2536      $target = $(targetNode.span);
2537    if( !this.$dndMarker ) {
2538      this.$dndMarker = $("<div id='dynatree-drop-marker'></div>")
2539        .hide()
2540        .css({"z-index": 1000})
2541        .prependTo($(this.divTree).parent());
2542
2543//      logMsg("Creating marker: %o", this.$dndMarker);
2544    }
2545/*
2546    if(hitMode === "start"){
2547    }
2548    if(hitMode === "stop"){
2549//      sourceNode.removeClass("dynatree-drop-target");
2550    }
2551*/
2552    if(hitMode === "after" || hitMode === "before" || hitMode === "over"){
2553//      $source && $source.addClass("dynatree-drag-source");
2554//      $target.addClass("dynatree-drop-target");
2555
2556      var markerOffset = "0 0";
2557
2558      switch(hitMode){
2559      case "before":
2560        this.$dndMarker.removeClass("dynatree-drop-after dynatree-drop-over");
2561        this.$dndMarker.addClass("dynatree-drop-before");
2562        markerOffset = "0 -8";
2563        break;
2564      case "after":
2565        this.$dndMarker.removeClass("dynatree-drop-before dynatree-drop-over");
2566        this.$dndMarker.addClass("dynatree-drop-after");
2567        markerOffset = "0 8";
2568        break;
2569      default:
2570        this.$dndMarker.removeClass("dynatree-drop-after dynatree-drop-before");
2571        this.$dndMarker.addClass("dynatree-drop-over");
2572        $target.addClass("dynatree-drop-target");
2573        markerOffset = "8 0";
2574      }
2575//      logMsg("Creating marker: %o", this.$dndMarker);
2576//      logMsg("    $target.offset=%o", $target);
2577//      logMsg("    pos/$target.offset=%o", pos);
2578//      logMsg("    $target.position=%o", $target.position());
2579//      logMsg("    $target.offsetParent=%o, ot:%o", $target.offsetParent(), $target.offsetParent().offset());
2580//      logMsg("    $(this.divTree).offset=%o", $(this.divTree).offset());
2581//      logMsg("    $(this.divTree).parent=%o", $(this.divTree).parent());
2582//      var pos = $target.offset();
2583//      var parentPos = $target.offsetParent().offset();
2584//      var bodyPos = $target.offsetParent().offset();
2585
2586      this.$dndMarker
2587        .show()
2588        .position({
2589          my: "left top",
2590          at: "left top",
2591          of: $target,
2592          offset: markerOffset
2593        });
2594
2595//      helper.addClass("dynatree-drop-hover");
2596    } else {
2597//      $source && $source.removeClass("dynatree-drag-source");
2598      $target.removeClass("dynatree-drop-target");
2599      this.$dndMarker.hide();
2600//      helper.removeClass("dynatree-drop-hover");
2601    }
2602    if(hitMode === "after"){
2603      $target.addClass("dynatree-drop-after");
2604    } else {
2605      $target.removeClass("dynatree-drop-after");
2606    }
2607    if(hitMode === "before"){
2608      $target.addClass("dynatree-drop-before");
2609    } else {
2610      $target.removeClass("dynatree-drop-before");
2611    }
2612    if(accept === true){
2613      if($source){
2614        $source.addClass("dynatree-drop-accept");
2615      }
2616      $target.addClass("dynatree-drop-accept");
2617      helper.addClass("dynatree-drop-accept");
2618    }else{
2619      if($source){
2620        $source.removeClass("dynatree-drop-accept");
2621      }
2622      $target.removeClass("dynatree-drop-accept");
2623      helper.removeClass("dynatree-drop-accept");
2624    }
2625    if(accept === false){
2626      if($source){
2627        $source.addClass("dynatree-drop-reject");
2628      }
2629      $target.addClass("dynatree-drop-reject");
2630      helper.addClass("dynatree-drop-reject");
2631    }else{
2632      if($source){
2633        $source.removeClass("dynatree-drop-reject");
2634      }
2635      $target.removeClass("dynatree-drop-reject");
2636      helper.removeClass("dynatree-drop-reject");
2637    }
2638  },
2639
2640  _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) {
2641    /**
2642     * Handles drag'n'drop functionality.
2643     *
2644     * A standard jQuery drag-and-drop process may generate these calls:
2645     *
2646     * draggable helper():
2647     *     _onDragEvent("helper", sourceNode, null, event, null, null);
2648     * start:
2649     *     _onDragEvent("start", sourceNode, null, event, ui, draggable);
2650     * drag:
2651     *     _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
2652     *     _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
2653     *     _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
2654     * stop:
2655     *     _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
2656     *     _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
2657     *     _onDragEvent("stop", sourceNode, null, event, ui, draggable);
2658     */
2659//    if(eventName !== "over"){
2660//      this.logDebug("tree._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
2661//    }
2662    var opts = this.options,
2663      dnd = this.options.dnd,
2664      res = null,
2665      nodeTag = $(node.span),
2666      hitMode,
2667      enterResponse;
2668
2669    switch (eventName) {
2670    case "helper":
2671      // Only event and node argument is available
2672      var $helper = $("<div class='dynatree-drag-helper'><span class='dynatree-drag-helper-img' /></div>")
2673        .append($(event.target).closest('a').clone());
2674      // issue 244: helper should be child of scrollParent
2675      $("ul.dynatree-container", node.tree.divTree).append($helper);
2676//      $(node.tree.divTree).append($helper);
2677      // Attach node reference to helper object
2678      $helper.data("dtSourceNode", node);
2679//      this.logDebug("helper=%o", $helper);
2680//      this.logDebug("helper.sourceNode=%o", $helper.data("dtSourceNode"));
2681      res = $helper;
2682      break;
2683    case "start":
2684      if(node.isStatusNode()) {
2685        res = false;
2686      } else if(dnd.onDragStart) {
2687        res = dnd.onDragStart(node);
2688      }
2689      if(res === false) {
2690        this.logDebug("tree.onDragStart() cancelled");
2691        //draggable._clear();
2692        // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned)
2693        ui.helper.trigger("mouseup");
2694        ui.helper.hide();
2695      } else {
2696        nodeTag.addClass("dynatree-drag-source");
2697      }
2698      break;
2699    case "enter":
2700      res = dnd.onDragEnter ? dnd.onDragEnter(node, otherNode) : null;
2701      if(!res){
2702        // convert null, undefined, false to false
2703        res = false;
2704      }else{
2705        res = {
2706          over: ((res === true) || (res === "over") || $.inArray("over", res) >= 0),
2707          before: ((res === true) || (res === "before") || $.inArray("before", res) >= 0),
2708          after: ((res === true) || (res === "after") || $.inArray("after", res) >= 0)
2709        };
2710      }
2711      ui.helper.data("enterResponse", res);
2712//      this.logDebug("helper.enterResponse: %o", res);
2713      break;
2714    case "over":
2715      enterResponse = ui.helper.data("enterResponse");
2716      hitMode = null;
2717      if(enterResponse === false){
2718        // Don't call onDragOver if onEnter returned false.
2719        // issue 332
2720//        break;
2721      } else if(typeof enterResponse === "string") {
2722        // Use hitMode from onEnter if provided.
2723        hitMode = enterResponse;
2724      } else {
2725        // Calculate hitMode from relative cursor position.
2726        var nodeOfs = nodeTag.offset();
2727//        var relPos = { x: event.clientX - nodeOfs.left,
2728//              y: event.clientY - nodeOfs.top };
2729//        nodeOfs.top += this.parentTop;
2730//        nodeOfs.left += this.parentLeft;
2731        var relPos = { x: event.pageX - nodeOfs.left,
2732                 y: event.pageY - nodeOfs.top };
2733        var relPos2 = { x: relPos.x / nodeTag.width(),
2734                y: relPos.y / nodeTag.height() };
2735//        this.logDebug("event.page: %s/%s", event.pageX, event.pageY);
2736//        this.logDebug("event.client: %s/%s", event.clientX, event.clientY);
2737//        this.logDebug("nodeOfs: %s/%s", nodeOfs.left, nodeOfs.top);
2738////        this.logDebug("parent: %s/%s", this.parentLeft, this.parentTop);
2739//        this.logDebug("relPos: %s/%s", relPos.x, relPos.y);
2740//        this.logDebug("relPos2: %s/%s", relPos2.x, relPos2.y);
2741        if( enterResponse.after && relPos2.y > 0.75 ){
2742          hitMode = "after";
2743        } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){
2744          hitMode = "after";
2745        } else if(enterResponse.before && relPos2.y <= 0.25) {
2746          hitMode = "before";
2747        } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) {
2748          hitMode = "before";
2749        } else if(enterResponse.over) {
2750          hitMode = "over";
2751        }
2752        // Prevent no-ops like 'before source node'
2753        // TODO: these are no-ops when moving nodes, but not in copy mode
2754        if( dnd.preventVoidMoves ){
2755          if(node === otherNode){
2756//            this.logDebug("    drop over source node prevented");
2757            hitMode = null;
2758          }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){
2759//            this.logDebug("    drop after source node prevented");
2760            hitMode = null;
2761          }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){
2762//            this.logDebug("    drop before source node prevented");
2763            hitMode = null;
2764          }else if(hitMode === "over" && otherNode
2765              && otherNode.parent === node && otherNode.isLastSibling() ){
2766//            this.logDebug("    drop last child over own parent prevented");
2767            hitMode = null;
2768          }
2769        }
2770//        this.logDebug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
2771        ui.helper.data("hitMode", hitMode);
2772      }
2773      // Auto-expand node (only when 'over' the node, not 'before', or 'after')
2774      if(hitMode === "over"
2775        && dnd.autoExpandMS && node.hasChildren() !== false && !node.bExpanded) {
2776        node.scheduleAction("expand", dnd.autoExpandMS);
2777      }
2778      if(hitMode && dnd.onDragOver){
2779        res = dnd.onDragOver(node, otherNode, hitMode);
2780        if(res === "over" || res === "before" || res === "after") {
2781          hitMode = res;
2782        }
2783      }
2784      // issue 332
2785//      this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false);
2786      this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null);
2787      break;
2788    case "drop":
2789      // issue 286: don't trigger onDrop, if DnD status is 'reject'
2790      var isForbidden = ui.helper.hasClass("dynatree-drop-reject");
2791      hitMode = ui.helper.data("hitMode");
2792      if(hitMode && dnd.onDrop && !isForbidden){
2793        dnd.onDrop(node, otherNode, hitMode, ui, draggable);
2794      }
2795      break;
2796    case "leave":
2797      // Cancel pending expand request
2798      node.scheduleAction("cancel");
2799      ui.helper.data("enterResponse", null);
2800      ui.helper.data("hitMode", null);
2801      this._setDndStatus(otherNode, node, ui.helper, "out", undefined);
2802      if(dnd.onDragLeave){
2803        dnd.onDragLeave(node, otherNode);
2804      }
2805      break;
2806    case "stop":
2807      nodeTag.removeClass("dynatree-drag-source");
2808      if(dnd.onDragStop){
2809        dnd.onDragStop(node);
2810      }
2811      break;
2812    default:
2813      throw "Unsupported drag event: " + eventName;
2814    }
2815    return res;
2816  },
2817
2818  cancelDrag: function() {
2819     var dd = $.ui.ddmanager.current;
2820     if(dd){
2821       dd.cancel();
2822     }
2823  },
2824
2825  // --- end of class
2826  lastentry: undefined
2827};
2828
2829/*************************************************************************
2830 * Widget $(..).dynatree
2831 */
2832
2833$.widget("ui.dynatree", {
2834/*
2835  init: function() {
2836    // ui.core 1.6 renamed init() to _init(): this stub assures backward compatibility
2837    _log("warn", "ui.dynatree.init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher.");
2838    return this._init();
2839  },
2840 */
2841  _init: function() {
2842    if( parseFloat($.ui.version) < 1.8 ) {
2843      // jquery.ui.core 1.8 renamed _init() to _create(): this stub assures backward compatibility
2844      if(this.options.debugLevel >= 0){
2845        _log("warn", "ui.dynatree._init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher.");
2846      }
2847      return this._create();
2848    }
2849    // jquery.ui.core 1.8 still uses _init() to perform "default functionality"
2850    if(this.options.debugLevel >= 2){
2851      _log("debug", "ui.dynatree._init() was called; no current default functionality.");
2852    }
2853  },
2854
2855  _create: function() {
2856    var opts = this.options;
2857    if(opts.debugLevel >= 1){
2858      logMsg("Dynatree._create(): version='%s', debugLevel=%o.", $.ui.dynatree.version, this.options.debugLevel);
2859    }
2860    // The widget framework supplies this.element and this.options.
2861    this.options.event += ".dynatree"; // namespace event
2862
2863    var divTree = this.element.get(0);
2864/*    // Clear container, in case it contained some 'waiting' or 'error' text
2865    // for clients that don't support JS
2866    if( opts.children || (opts.initAjax && opts.initAjax.url) || opts.initId )
2867      $(divTree).empty();
2868*/
2869    // Create the DynaTree object
2870    this.tree = new DynaTree(this);
2871    this.tree._load();
2872    this.tree.logDebug("Dynatree._init(): done.");
2873  },
2874
2875  bind: function() {
2876    // Prevent duplicate binding
2877    this.unbind();
2878
2879    var eventNames = "click.dynatree dblclick.dynatree";
2880    if( this.options.keyboard ){
2881      // Note: leading ' '!
2882      eventNames += " keypress.dynatree keydown.dynatree";
2883    }
2884    this.element.bind(eventNames, function(event){
2885      var dtnode = $.ui.dynatree.getNode(event.target);
2886      if( !dtnode ){
2887        return true;  // Allow bubbling of other events
2888      }
2889      var tree = dtnode.tree;
2890      var o = tree.options;
2891      tree.logDebug("event(%s): dtnode: %s", event.type, dtnode);
2892      var prevPhase = tree.phase;
2893      tree.phase = "userEvent";
2894      try {
2895        switch(event.type) {
2896        case "click":
2897          return ( o.onClick && o.onClick.call(tree, dtnode, event)===false ) ? false : dtnode._onClick(event);
2898        case "dblclick":
2899          return ( o.onDblClick && o.onDblClick.call(tree, dtnode, event)===false ) ? false : dtnode._onDblClick(event);
2900        case "keydown":
2901          return ( o.onKeydown && o.onKeydown.call(tree, dtnode, event)===false ) ? false : dtnode._onKeydown(event);
2902        case "keypress":
2903          return ( o.onKeypress && o.onKeypress.call(tree, dtnode, event)===false ) ? false : dtnode._onKeypress(event);
2904        }
2905      } catch(e) {
2906        var _ = null; // issue 117
2907        tree.logWarning("bind(%o): dtnode: %o, error: %o", event, dtnode, e);
2908      } finally {
2909        tree.phase = prevPhase;
2910      }
2911    });
2912
2913    // focus/blur don't bubble, i.e. are not delegated to parent <div> tags,
2914    // so we use the addEventListener capturing phase.
2915    // See http://www.howtocreate.co.uk/tutorials/javascript/domevents
2916    function __focusHandler(event) {
2917      // Handles blur and focus.
2918      // Fix event for IE:
2919      // doesn't pass JSLint:
2920//      event = arguments[0] = $.event.fix( event || window.event );
2921      // what jQuery does:
2922//      var args = jQuery.makeArray( arguments );
2923//      event = args[0] = jQuery.event.fix( event || window.event );
2924      event = $.event.fix( event || window.event );
2925      var dtnode = $.ui.dynatree.getNode(event.target);
2926      return dtnode ? dtnode._onFocus(event) : false;
2927    }
2928    var div = this.tree.divTree;
2929
2930    if( div.addEventListener ) {
2931      div.addEventListener("focus", __focusHandler, true);
2932      div.addEventListener("blur", __focusHandler, true);
2933    } else {
2934      div.onfocusin = div.onfocusout = __focusHandler;
2935    }
2936    // EVENTS
2937    // disable click if event is configured to something else
2938//    if (!(/^click/).test(o.event))
2939//      this.$tabs.bind("click.tabs", function() { return false; });
2940
2941  },
2942
2943  unbind: function() {
2944    this.element.unbind(".dynatree");
2945  },
2946
2947/* TODO: we could handle option changes during runtime here (maybe to re-render, ...)
2948  setData: function(key, value) {
2949    this.tree.logDebug("dynatree.setData('" + key + "', '" + value + "')");
2950  },
2951*/
2952  enable: function() {
2953    this.bind();
2954    // Call default disable(): remove -disabled from css:
2955    $.Widget.prototype.enable.apply(this, arguments);
2956  },
2957
2958  disable: function() {
2959    this.unbind();
2960    // Call default disable(): add -disabled to css:
2961    $.Widget.prototype.disable.apply(this, arguments);
2962  },
2963
2964  // --- getter methods (i.e. NOT returning a reference to $)
2965  getTree: function() {
2966    return this.tree;
2967  },
2968
2969  getRoot: function() {
2970    return this.tree.getRoot();
2971  },
2972
2973  getActiveNode: function() {
2974    return this.tree.getActiveNode();
2975  },
2976
2977  getSelectedNodes: function() {
2978    return this.tree.getSelectedNodes();
2979  },
2980
2981  // ------------------------------------------------------------------------
2982  lastentry: undefined
2983});
2984
2985
2986// The following methods return a value (thus breaking the jQuery call chain):
2987if( parseFloat($.ui.version) < 1.8 ) {
2988  $.ui.dynatree.getter = "getTree getRoot getActiveNode getSelectedNodes";
2989}
2990
2991/*******************************************************************************
2992 * Tools in ui.dynatree namespace
2993 */
2994$.ui.dynatree.version = "$Version:$";
2995
2996/**
2997 * Return a DynaTreeNode object for a given DOM element
2998 */
2999$.ui.dynatree.getNode = function(el) {
3000  if(el instanceof DynaTreeNode){
3001    return el; // el already was a DynaTreeNode
3002  }
3003  if(el.selector !== undefined){
3004    el = el[0]; // el was a jQuery object: use the DOM element
3005  }
3006  // TODO: for some reason $el.parents("[dtnode]") does not work (jQuery 1.6.1)
3007  // maybe, because dtnode is a property, not an attribute
3008  while( el ) {
3009    if(el.dtnode) {
3010      return el.dtnode;
3011    }
3012    el = el.parentNode;
3013  }
3014  return null;
3015/*
3016  var $el = el.selector === undefined ? $(el) : el,
3017//    parent = $el.closest("[dtnode]"),
3018//    parent = $el.parents("[dtnode]").first(),
3019    useProp = (typeof $el.prop == "function"),
3020    node;
3021  $el.parents().each(function(){
3022    node = useProp ? $(this).prop("dtnode") : $(this).attr("dtnode");
3023    if(node){
3024      return false;
3025    }
3026  });
3027  return node;
3028*/
3029};
3030
3031/**Return persistence information from cookies.*/
3032$.ui.dynatree.getPersistData = DynaTreeStatus._getTreePersistData;
3033
3034/*******************************************************************************
3035 * Plugin default options:
3036 */
3037$.ui.dynatree.prototype.options = {
3038  title: "Dynatree", // Tree's name (only used for debug output)
3039  minExpandLevel: 1, // 1: root node is not collapsible
3040  imagePath: null, // Path to a folder containing icons. Defaults to 'skin/' subdirectory.
3041  children: null, // Init tree structure from this object array.
3042  initId: null, // Init tree structure from a <ul> element with this ID.
3043  initAjax: null, // Ajax options used to initialize the tree strucuture.
3044  autoFocus: true, // Set focus to first child, when expanding or lazy-loading.
3045  keyboard: true, // Support keyboard navigation.
3046  persist: false, // Persist expand-status to a cookie
3047  autoCollapse: false, // Automatically collapse all siblings, when a node is expanded.
3048  clickFolderMode: 3, // 1:activate, 2:expand, 3:activate and expand
3049  activeVisible: true, // Make sure, active nodes are visible (expanded).
3050  checkbox: false, // Show checkboxes.
3051  selectMode: 2, // 1:single, 2:multi, 3:multi-hier
3052  fx: null, // Animations, e.g. null or { height: "toggle", duration: 200 }
3053  noLink: false, // Use <span> instead of <a> tags for all nodes
3054  // Low level event handlers: onEvent(dtnode, event): return false, to stop default processing
3055  onClick: null, // null: generate focus, expand, activate, select events.
3056  onDblClick: null, // (No default actions.)
3057  onKeydown: null, // null: generate keyboard navigation (focus, expand, activate).
3058  onKeypress: null, // (No default actions.)
3059  onFocus: null, // null: set focus to node.
3060  onBlur: null, // null: remove focus from node.
3061
3062  // Pre-event handlers onQueryEvent(flag, dtnode): return false, to stop processing
3063  onQueryActivate: null, // Callback(flag, dtnode) before a node is (de)activated.
3064  onQuerySelect: null, // Callback(flag, dtnode) before a node is (de)selected.
3065  onQueryExpand: null, // Callback(flag, dtnode) before a node is expanded/collpsed.
3066
3067  // High level event handlers
3068  onPostInit: null, // Callback(isReloading, isError) when tree was (re)loaded.
3069  onActivate: null, // Callback(dtnode) when a node is activated.
3070  onDeactivate: null, // Callback(dtnode) when a node is deactivated.
3071  onSelect: null, // Callback(flag, dtnode) when a node is (de)selected.
3072  onExpand: null, // Callback(flag, dtnode) when a node is expanded/collapsed.
3073  onLazyRead: null, // Callback(dtnode) when a lazy node is expanded for the first time.
3074  onCustomRender: null, // Callback(dtnode) before a node is rendered. Return a HTML string to override.
3075  onCreate: null, // Callback(dtnode, nodeSpan) after a node was rendered for the first time.
3076  onRender: null, // Callback(dtnode, nodeSpan) after a node was rendered.
3077        // postProcess is similar to the standard dataFilter hook,
3078        // but it is also called for JSONP
3079  postProcess: null, // Callback(data, dataType) before an Ajax result is passed to dynatree
3080
3081  // Drag'n'drop support
3082  dnd: {
3083    // Make tree nodes draggable:
3084    onDragStart: null, // Callback(sourceNode), return true, to enable dnd
3085    onDragStop: null, // Callback(sourceNode)
3086//    helper: null,
3087    // Make tree nodes accept draggables
3088    autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
3089    preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
3090    onDragEnter: null, // Callback(targetNode, sourceNode)
3091    onDragOver: null, // Callback(targetNode, sourceNode, hitMode)
3092    onDrop: null, // Callback(targetNode, sourceNode, hitMode)
3093    onDragLeave: null // Callback(targetNode, sourceNode)
3094  },
3095  ajaxDefaults: { // Used by initAjax option
3096    cache: false, // false: Append random '_' argument to the request url to prevent caching.
3097    timeout: 0, // >0: Make sure we get an ajax error for invalid URLs
3098    dataType: "json" // Expect json format and pass json object to callbacks.
3099  },
3100  strings: {
3101    loading: "Loading&#8230;",
3102    loadError: "Load error!"
3103  },
3104  generateIds: false, // Generate id attributes like <span id='dynatree-id-KEY'>
3105  idPrefix: "dynatree-id-", // Used to generate node id's like <span id="dynatree-id-<key>">.
3106  keyPathSeparator: "/", // Used by node.getKeyPath() and tree.loadKeyPath().
3107//    cookieId: "dynatree-cookie", // Choose a more unique name, to allow multiple trees.
3108  cookieId: "dynatree", // Choose a more unique name, to allow multiple trees.
3109  cookie: {
3110    expires: null //7, // Days or Date; null: session cookie
3111//    path: "/", // Defaults to current page
3112//    domain: "jquery.com",
3113//    secure: true
3114  },
3115  // Class names used, when rendering the HTML markup.
3116  // Note: if only single entries are passed for options.classNames, all other
3117  // values are still set to default.
3118  classNames: {
3119    container: "dynatree-container",
3120    node: "dynatree-node",
3121    folder: "dynatree-folder",
3122//    document: "dynatree-document",
3123
3124    empty: "dynatree-empty",
3125    vline: "dynatree-vline",
3126    expander: "dynatree-expander",
3127    connector: "dynatree-connector",
3128    checkbox: "dynatree-checkbox",
3129    nodeIcon: "dynatree-icon",
3130    title: "dynatree-title",
3131    noConnector: "dynatree-no-connector",
3132
3133    nodeError: "dynatree-statusnode-error",
3134    nodeWait: "dynatree-statusnode-wait",
3135    hidden: "dynatree-hidden",
3136    combinedExpanderPrefix: "dynatree-exp-",
3137    combinedIconPrefix: "dynatree-ico-",
3138    nodeLoading: "dynatree-loading",
3139//    disabled: "dynatree-disabled",
3140    hasChildren: "dynatree-has-children",
3141    active: "dynatree-active",
3142    selected: "dynatree-selected",
3143    expanded: "dynatree-expanded",
3144    lazy: "dynatree-lazy",
3145    focused: "dynatree-focused",
3146    partsel: "dynatree-partsel",
3147    lastsib: "dynatree-lastsib"
3148  },
3149  debugLevel: 2, // 0:quiet, 1:normal, 2:debug $REPLACE:  debugLevel: 1,
3150
3151  // ------------------------------------------------------------------------
3152  lastentry: undefined
3153};
3154//
3155if( parseFloat($.ui.version) < 1.8 ) {
3156  $.ui.dynatree.defaults = $.ui.dynatree.prototype.options;
3157}
3158
3159/*******************************************************************************
3160 * Reserved data attributes for a tree node.
3161 */
3162$.ui.dynatree.nodedatadefaults = {
3163  title: null, // (required) Displayed name of the node (html is allowed here)
3164  key: null, // May be used with activate(), select(), find(), ...
3165  isFolder: false, // Use a folder icon. Also the node is expandable but not selectable.
3166  isLazy: false, // Call onLazyRead(), when the node is expanded for the first time to allow for delayed creation of children.
3167  tooltip: null, // Show this popup text.
3168  href: null, // Added to the generated <a> tag.
3169  icon: null, // Use a custom image (filename relative to tree.options.imagePath). 'null' for default icon, 'false' for no icon.
3170  addClass: null, // Class name added to the node's span tag.
3171  noLink: false, // Use <span> instead of <a> tag for this node
3172  activate: false, // Initial active status.
3173  focus: false, // Initial focused status.
3174  expand: false, // Initial expanded status.
3175  select: false, // Initial selected status.
3176  hideCheckbox: false, // Suppress checkbox display for this node.
3177  unselectable: false, // Prevent selection.
3178//  disabled: false,
3179  // The following attributes are only valid if passed to some functions:
3180  children: null, // Array of child nodes.
3181  // NOTE: we can also add custom attributes here.
3182  // This may then also be used in the onActivate(), onSelect() or onLazyTree() callbacks.
3183  // ------------------------------------------------------------------------
3184  lastentry: undefined
3185};
3186
3187/*******************************************************************************
3188 * Drag and drop support
3189 */
3190function _initDragAndDrop(tree) {
3191  var dnd = tree.options.dnd || null;
3192  // Register 'connectToDynatree' option with ui.draggable
3193  if(dnd && (dnd.onDragStart || dnd.onDrop)) {
3194    _registerDnd();
3195  }
3196  // Attach ui.draggable to this Dynatree instance
3197  if(dnd && dnd.onDragStart ) {
3198    tree.$tree.draggable({
3199      addClasses: false,
3200      appendTo: "body",
3201      containment: false,
3202      delay: 0,
3203      distance: 4,
3204      revert: false,
3205      scroll: true, // issue 244: enable scrolling (if ul.dynatree-container)
3206      scrollSpeed: 7,
3207      scrollSensitivity: 10,
3208      // Delegate draggable.start, drag, and stop events to our handler
3209      connectToDynatree: true,
3210      // Let source tree create the helper element
3211      helper: function(event) {
3212        var sourceNode = $.ui.dynatree.getNode(event.target);
3213        if(!sourceNode){ // issue 211
3214          return "<div></div>";
3215        }
3216        return sourceNode.tree._onDragEvent("helper", sourceNode, null, event, null, null);
3217      },
3218      start: function(event, ui) {
3219        // See issues 211, 268, 278
3220//        var sourceNode = $.ui.dynatree.getNode(event.target);
3221        var sourceNode = ui.helper.data("dtSourceNode");
3222        return !!sourceNode; // Abort dragging if no Node could be found
3223      },
3224      _last: null
3225    });
3226  }
3227  // Attach ui.droppable to this Dynatree instance
3228  if(dnd && dnd.onDrop) {
3229    tree.$tree.droppable({
3230      addClasses: false,
3231      tolerance: "intersect",
3232      greedy: false,
3233      _last: null
3234    });
3235  }
3236}
3237
3238//--- Extend ui.draggable event handling --------------------------------------
3239var didRegisterDnd = false;
3240var _registerDnd = function() {
3241  if(didRegisterDnd){
3242    return;
3243  }
3244  // Register proxy-functions for draggable.start/drag/stop
3245  $.ui.plugin.add("draggable", "connectToDynatree", {
3246    start: function(event, ui) {
3247      var draggable = $(this).data("draggable"),
3248        sourceNode = ui.helper.data("dtSourceNode") || null;
3249//      logMsg("draggable-connectToDynatree.start, %s", sourceNode);
3250//      logMsg("    this: %o", this);
3251//      logMsg("    event: %o", event);
3252//      logMsg("    draggable: %o", draggable);
3253//      logMsg("    ui: %o", ui);
3254
3255      if(sourceNode) {
3256        // Adjust helper offset, so cursor is slightly outside top/left corner
3257//        draggable.offset.click.top -= event.target.offsetTop;
3258//        draggable.offset.click.left -= event.target.offsetLeft;
3259        draggable.offset.click.top = -2;
3260        draggable.offset.click.left = + 16;
3261//        logMsg("    draggable2: %o", draggable);
3262//        logMsg("    draggable.offset.click FIXED: %s/%s", draggable.offset.click.left, draggable.offset.click.top);
3263        // Trigger onDragStart event
3264        // TODO: when called as connectTo..., the return value is ignored(?)
3265        return sourceNode.tree._onDragEvent("start", sourceNode, null, event, ui, draggable);
3266      }
3267    },
3268    drag: function(event, ui) {
3269      var draggable = $(this).data("draggable"),
3270        sourceNode = ui.helper.data("dtSourceNode") || null,
3271        prevTargetNode = ui.helper.data("dtTargetNode") || null,
3272        targetNode = $.ui.dynatree.getNode(event.target);
3273//      logMsg("$.ui.dynatree.getNode(%o): %s", event.target, targetNode);
3274//      logMsg("connectToDynatree.drag: helper: %o", ui.helper[0]);
3275      if(event.target && !targetNode){
3276        // We got a drag event, but the targetNode could not be found
3277        // at the event location. This may happen,
3278        // 1. if the mouse jumped over the drag helper,
3279        // 2. or if non-dynatree element is dragged
3280        // We ignore it:
3281        var isHelper = $(event.target).closest("div.dynatree-drag-helper,#dynatree-drop-marker").length > 0;
3282        if(isHelper){
3283//          logMsg("Drag event over helper: ignored.");
3284          return;
3285        }
3286      }
3287//      logMsg("draggable-connectToDynatree.drag: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode"));
3288      ui.helper.data("dtTargetNode", targetNode);
3289      // Leaving a tree node
3290      if(prevTargetNode && prevTargetNode !== targetNode ) {
3291        prevTargetNode.tree._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
3292      }
3293      if(targetNode){
3294        if(!targetNode.tree.options.dnd.onDrop) {
3295          // not enabled as drop target
3296//          noop(); // Keep JSLint happy
3297        } else if(targetNode === prevTargetNode) {
3298          // Moving over same node
3299          targetNode.tree._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
3300        }else{
3301          // Entering this node first time
3302          targetNode.tree._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
3303        }
3304      }
3305      // else go ahead with standard event handling
3306    },
3307    stop: function(event, ui) {
3308      var draggable = $(this).data("draggable"),
3309        sourceNode = ui.helper.data("dtSourceNode") || null,
3310        targetNode = ui.helper.data("dtTargetNode") || null,
3311        mouseDownEvent = draggable._mouseDownEvent,
3312        eventType = event.type,
3313        dropped = (eventType == "mouseup" && event.which == 1);
3314//      logMsg("draggable-connectToDynatree.stop: targetNode(from event): %s, dtTargetNode: %s", targetNode, ui.helper.data("dtTargetNode"));
3315//      logMsg("draggable-connectToDynatree.stop, %s", sourceNode);
3316//      logMsg("    type: %o, downEvent: %o, upEvent: %o", eventType, mouseDownEvent, event);
3317//      logMsg("    targetNode: %o", targetNode);
3318      if(!dropped){
3319        logMsg("Drag was cancelled");
3320      }
3321      if(targetNode) {
3322        if(dropped){
3323          targetNode.tree._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
3324        }
3325        targetNode.tree._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
3326      }
3327      if(sourceNode){
3328        sourceNode.tree._onDragEvent("stop", sourceNode, null, event, ui, draggable);
3329      }
3330    }
3331  });
3332  didRegisterDnd = true;
3333};
3334
3335// ---------------------------------------------------------------------------
3336}(jQuery));
Note: See TracBrowser for help on using the repository browser.