/********************************************************************** 
 * License information ( the MIT license)
 *
 * Copyright (c) 2006 Catherine Beauheim; Stanford University
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *********************************************************************/

/** 
  *  try to open and read an xml file of an ontology so I can practice processing & displaying it
  */

/* icon status */

var HAS_EXPANDED = 2;     /* has queried for its children */


/* icon status  does it need the ... or not */
var BLANK = 10;  
var HAS_MORE = 11;
var IS_LEAF  = 12;

var childCache = new Array();

  function OntologyTreeBrowser(uid) {
      this.tree = new YAHOO.widget.TreeView ('treediv'+uid);
      this.uid = uid;
      /** now there is a div to store the highlighted id as in div id='highlight'+uid, value= **/
      
  }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.initTopNode = function (rootNodeId, ontologyId, rootNodeLabel, uid ) {

     if (rootNodeId ==0 ) {
        query = "?func=getRootTerms&ontologyId=" + ontologyId + "&uid=" + uid;
     }
     else {
        query = "?func=getChildren&ontologyId="+ ontologyId + "&termId=" + rootNodeId +"&uid="+uid;
     }
       this.rootNodeLabel = rootNodeLabel;
       this.initTree (query ); 
     } 
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
    OntologyTreeBrowser.prototype.initTree = function (query ) {

         var s;
         var ret = smdService.sendRequest (query, "GET", smdService.buildTreeFromRootsResponse );
         if (ret == 0 ) {
             s = setTimeout ('OntologyTreeBrowser.prototype.initTree(\''+query+'\')', 50 );
         }
         else {
              doDebug ("" );
          }

     } 

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     /* from the tree */
     OntologyTreeBrowser.prototype.queryForChildren = function (parent, uid ) {
        this.loadNewChildren (parent, 0, uid);
     }
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
  /*  expanding **/
     OntologyTreeBrowser.prototype.dynamicLoad = function (parent) {

     if (parent == null ) 
           return;

       if (parent.hasChildren() )  {     
          parent.showChildren();
       }
      else  { 
          try {
              var query = "?func=getChildren&ontologyId="+ parent.data["ontId"] + "&termId=" + parent.data["id"]+ "&uid=" + parent.uid;
              smdService.sendRequest ( query,"GET", smdService.getNewChildrenResponse );
              } catch (e) {
                  doDebug ("load new children exception " + e );
              }
          }
     }


  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
   * called when no term has been selected as a starting point.  
   * need to take into account those ontologies which have more than one starting point
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.buildTreeFromRootsResponse  = function ( xmldoc, rootNodeId,uid ) {


        var ele = getElement('treediv'+uid);
        var ontId = ele.getAttribute ('ontId'+uid );
        var childList = parseTermList (xmldoc, ontId);
        
        var treediv = getElement ('treediv'+uid);
        var treeid = treediv.getAttribute ('treeId');
        var tree = YAHOO.widget.TreeView.getTree (treeid);
  
        var rootNode = tree.getRoot();
        var parent = rootNode;
        var iconStatus;
        var rootData = new Array();
        var allRoots = new Array();
        parent.ontId = ontId+uid;

        if (rootNodeId != 0 ) {
           rootData["id"] = rootNodeId;
           rootData["label"] = this.rootNodeLabel;
           rootData["name"] = this.rootNodeLabel;
           rootData["uid"] = uid;
           rootData["sourceId"] = 0;
           //rootData["iconStatus"]=0;
           rootData["parentId"]=0;
           rootData["nchildren"] = childList.length;
           var n = new YAHOO.widget.MyNode (rootData, parent, 1, BLANK, uid );
           parent = n;
           for (var i = 0; i < childList.length; i++ ) {
              iconStatus = getIconStatus (childList[i].nchildren, 0);
              var node = new YAHOO.widget.MyNode (childList[i], parent, 0, iconStatus, uid );
           }
        }
        else {  //query for the children of the root 
           if (childList.length == 0 )
              alert ("We are currently working on this ontology and we cannot show it to you at this time");
           for (var i=0; i < childList.length; i++) {
              allRoots[i] = new Array();
              allRoots[i]["id"] = childList[i].id;
              allRoots[i]["name"] = childList[i].name;
              allRoots[i]["label"] = childList[i].label;
              allRoots[i]["uid"] = uid;
              allRoots[i]["sourceId"] = 0;
              allRoots[i]["parentId"]=0;
              allRoots[i]["nchildren"] = childList.length;
              n = new YAHOO.widget.MyNode (allRoots[i], parent, 1, BLANK, uid );
              n.collapse();
           }
        }
        if (rootNodeId != 0 ) {
           parent.collapse(); 
        }

          this.getTree (uid ).draw();
     }

  
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.getTree = function (uid ) {
       
        var treediv = getElement ('treediv'+uid);
        var treeid = treediv.getAttribute ('treeId');
        var tree = YAHOO.widget.TreeView.getTree (treeid);
        return tree;

     }
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
   * building from the top down or the bottom up ?
   *  blank, has_more or leaf.
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
   getIconStatus = function (nchildren, nshowing ) {
      var iconStatus = BLANK;

            if (nchildren == 0 )
               iconStatus =  IS_LEAF;
            
            else if (nchildren == nshowing )
               iconStatus = BLANK;

            /* no children are showing, but there are children.  should be a + */


             else if (nchildren > 0 && nshowing == 0 )
                iconStatus = BLANK;


            /** in the ancestor query, all but the last one, the chosen one has_more **/
            /** if there are more children than are currently showing **/
            else if (nchildren > nshowing )
               iconStatus =  HAS_MORE;  
  
           
            return iconStatus;
   }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
   OntologyTreeBrowser.prototype.sortChildren = function (children ) {


  try {
     var i = 0;
     var j = i + 1;
     while (i < children.length ) {
          if (j < children.length ) {
             if (children[i].data["name"] > children[j].data["name"] ) {
                 var temp = children[i];
                 children[i] = children[j];
                 children[j] = temp;
             }
             else {  // it is settled now
                //reset the previous and next sibling I think.
          /*??*/  /*   i=children.length; */
             }
          }
      i++;
      j++;
     }
     for (var i = 0; i < children.length ; i++ ) {
         if (i > 0)
            children[i].previousSibling = children[i-1];
         else
            children[i].previousSibling = 0;
         if (i < children.length-1 ) {
            children[i].nextSibling = children[i+1];
         }
         else {
            children[i].nextSibling = 0;
         }
      
     }
   } catch (e) {
       doDebug (e ) ;
       }

   };


  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
   OntologyTreeBrowser.prototype.isDuplicate  = function (children, id ) {

     var i = 0;
     var flag = false;
     while (i < children.length && !flag) {
         if (children[i].data.id == id ) {
             return (children[i]) ;
         }
         else {
             i++;
         }
     }
     return null;
   }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 
   *  this is an attempt to correct the case where I know that the term has more terms, but
   *  they have not been created.  That means that the tree does not know that there are 
   *  children.  This particularly shows up when a term is selected  from the list and then
   *  the tree is opened to show all the ancestors of this term.  The correct icon should be
   *  + to indicate that there are children.  No ... icon which is supposed to mean that there
   * are more children than the one child that is showing.  
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */

     OntologyTreeBrowser.prototype.stashChildren = function (xmldoc, rootNodeId, uid ) {
          
        var parent;
        var moreparents = new Array();
        var childList;
        var iconStatus;
        var ele = getElement ('highlight'+uid);
        var highlightId = ele.getAttribute ('value');

        var treediv = getElement ('treediv'+uid);
        var treeid = treediv.getAttribute ('treeId');
        var tree = YAHOO.widget.TreeView.getTree (treeid);
        var ontId = treediv.getAttribute ('ontId');

        if (xmldoc.hasChildNodes() && xmldoc.childNodes[0].nodeName == "TermList" ) {
            sourceId = xmldoc.childNodes[0].getAttribute ("sourceId"); 
            if (sourceId == 0 ) {
               parent = tree.getRoot();
            }
            else {
                parent = this.findClickedTerm (tree.getRoot(), sourceId, uid);
           }
           if (parent ) {
               //var sibs = 0;
               var idx = parent.data["id"];
               childCache["id"] = idx;
               childCache[idx] = new Array();
               childList = parseTermList (xmldoc, ontId );
               for (var i = 0; i < childList.length; i++) {
                  //is this one already here, if so, skip it.
                  childCache[idx][i] = childList[i] ;
                  var dup = this.isDuplicate ( parent.children, childList[i].id ); 
                  if ( dup == null ) {
                      iconStatus = getIconStatus (childList[i].nchildren, 0 );
                      var node = new YAHOO.widget.MyNode (childList[i], parent, 0, iconStatus, uid );
                      //if by chance this one is highlighted somewhere else in the tree
                      if (childList[i].id == highlightId ) {
                          node.labelStyle="highlight";
                          node.updateCheckHtml();
                      }
                      childList[i].index = node.index;
                  }
                  // add the children to all the instances of this
                }
               parent.expanded = true;
               parent.checkState = BLANK;
               this.sortChildren (parent.children);
           }
           
           //but there may be other parents other than the one that was clicked.  So I need to
           //duplicate the childList in all the places, but not show them right now.  that is
           //do not expand the parent, but all these new children.  

          /********  not doing this right now
           moreparents = this.tree.getNodesByProperty ('id', sourceId);
           for (var i = 0; i < moreparents.length; i++) {
              if (moreparents[i].index != parent.index) {
                  moreparents[i].checkState = BLANK;
                  moreparents[i].expanded = false;
                  for (var j=0; j < childList.length; j++) {
                      var dup = this.isDuplicate (moreparents[i].children, childList[j].id);
                      if (dup == null ) {
                          iconStatus = getIconStatus (childList[j].nchildren, 0);
                          var node = new YAHOO.widget.MyNode (childList[j], moreparents[i], 0, iconStatus, uid );
                          childList[j].index = node.index;
                      }
                     
                  } 
              }
           }   ****************/
           tree.draw();
        }
     }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 
   * button has been expanded.  query has been made for children and the xmldoc
   * is returned here. I know a tree exists.  I don't know if there are child nodes
   * exist for this query.  
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
 
     OntologyTreeBrowser.prototype.getNewChildrenResponse = function (xmldoc, rootNodeId, uid ) {

       var treediv = getElement ('treediv'+uid);
       var treeid = treediv.getAttribute ('treeId');
       var tree = YAHOO.widget.TreeView.getTree (treeid);
       var ontId = treediv.getAttribute ('ontId');

       //var parent;
       var sourceId;
       var childList = [];
       var allParents = [];
       var iconStatus;
      
       if (xmldoc.hasChildNodes() && xmldoc.childNodes[0].nodeName == "TermList" ) {
          sourceId = xmldoc.childNodes[0].getAttribute ("sourceId"); 

          if (sourceId == 0 ) {
             allParents[0] = tree.getRoot();
          }
          else {   //find the tree node with this sourceId  
             allParents = tree.getNodesByProperty ("id", sourceId);

             /* I have a source id, but no tree.  */
             if (allParents.lenth == 0 ) {
                  allParents[0] = tree.getRoot();
             }
          } 
          childList = parseTermList (xmldoc, ontId);

          var ta = getElement('TA' + uid);
          var termId = ta.getAttribute ('termId');
          for (var i = 0; i < allParents.length; i++ ) {
              for (var j = 0; j < childList.length; j++) {
                  var node = new YAHOO.widget.MyNode (childList[j], allParents[i], 0, BLANK, uid);
              }
              if (allParents[i].node_clicked ) {
                 allParents[i].expand()  ;
              }
           }
           this.updateHighlighting (termId, uid);
           tree.draw();
         }
      }
                    
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
  /* get the parents of this node and then the siblings through the parent       */
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */

    OntologyTreeBrowser.prototype.onComplete = function () {

        var treediv = getElement ('treediv'+uid);
        var treeid = treediv.getAttribute ('treeId');
        var tree = YAHOO.widget.TreeView.getTree (treeid);
        var ontId = treediv.getAttribute ('ontId');
        tree.draw();
  
    }
   

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
   * response from the server for get all the ancestors
   * if there is a rootNodeId (like for MGED), don't go all the way to the root, but
   * just to this node.
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.getAncestorResponse  = function (xmldoc, rootNodeId, uid) {
   
        var treediv = getElement ('treediv'+uid);
        var ontId = treediv.getAttribute ('ontId');

        var hashtable = new Hashtable();
        var sourceId;
        var parentId, parent;
      
        var termList = parseTermList(xmldoc, ontId);

        sourceId = termList[0].sourceId;
        for (var i=0; i < termList.length; i++) {
           hashtable.put (termList[i].id, termList[i] );
        }

        //create child links
        var topNodeId = rootNodeId;
        for (var i = 0; i < termList.length; i++) {
           var oneterm = termList[i];
           if (rootNodeId == 0 && oneterm.parentList == 0  ) {
               topNodeId = oneterm.id;
           }
           else {
               for (var j = 0; j < oneterm.parentList.length; j++) {
                  parentId = oneterm.parentList[j];
                  parent = hashtable.get (parentId);
                  if (parent ) {
                     if (parent.childList == null)
                         parent.childList = new Array();
                     parent.childList[parent.childList.length] = oneterm.id;
                  }
                else
                  doDebug (" no parent found in hashtable? " + parentId + " " + oneterm.id + ", " +oneterm.name);
               }
           }
        }
        this.createTree (hashtable, topNodeId, sourceId, uid);

     }
  
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     cloneNode = function (myterm ) {
        //copy the child data for the tree
        var clone =  new Array();
        clone.name = myterm.name;
        clone.id = myterm.id;
        clone.label = myterm.label;
        clone.accession = myterm.accession;
        clone.sourceId = myterm.sourceId;
        clone.ondId = myterm.ontId;
        clone.nchildren = myterm.nchildren;
        clone.iconstatus = myterm.iconstatus;
        clone.uid = myterm.uid;
        clone.childList= new Array();
        for (var k = 0; k < myterm.childList.length; k++) 
           clone.childList[k] = child.childList[k];
                 
        clone.parentList = new Array();
        for (var l = 0; l < myterm.parentList.length; l++)
             clone.parentList[l] = myterm.parentList[l];
         return clone;

    }
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
   * use the associate array properties of java script to search by property.
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
 
     OntologyTreeBrowser.prototype.changeLabels = function ( oldId, newId, uid ) {

        var oldNodes = new Array();
        var newNodes = new Array();
        var treediv = getElement ('treediv'+uid);
        var treeid = treediv.getAttribute ('treeId');
        var tree = YAHOO.widget.TreeView.getTree (treeid);

        oldNodes = tree.getNodesByProperty ('id', oldId);
        newNodes = tree.getNodesByProperty ('id', newId);

        for (var i = 0; i < oldNodes.length ; i++ ) {
           oldNodes[i].labelStyle="lbl";
           oldNodes[i].updateCheckHtml();
        }

        for (var i = 0; i < newNodes.length ; i++ ) {
            newNodes[i].labelStyle="highlight";
            newNodes[i].updateCheckHtml();
        }

     }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.updateHighlighting = function (  newId, uid ) {

         var highele = getElement ('highlight'+uid);
         var oldId = highele.getAttribute ('value');
         
         this.changeLabels ( oldId, newId, uid);
         highele.setAttribute ('value', newId);
         
/****
         var treediv = getElement ('treediv'+uid);
         var treeid = treediv.getAttribute ('treeId');
         var tree = YAHOO.widget.TreeView.getTree (treeid);
         tree.draw(); ****/

     }
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
   *  createTree is only called from the Ancestor query.  This is the bottom up query.
   *  the assignment of icons is pretty straight-forward then.  because each
   *  ancestor has one child showing or will have just one child show.  
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */

     OntologyTreeBrowser.prototype.createTree = function (hashtable, topid, sourceId, uid) {

        var topNode = hashtable.get (topid );
        var queue = new Array();
        var myparent = null;
        queue[queue.length] =  topNode;
        var treediv = getElement ('treediv'+uid);
        var treeid = treediv.getAttribute ('treeId');
        var tree = YAHOO.widget.TreeView.getTree (treeid);

        var rootnode = tree.getRoot();
        var iconStatus = getIconStatus (topNode.nchildren, 1);
        var treenode = new YAHOO.widget.MyNode (topNode, rootnode, 1,iconStatus, uid);
        topNode.index = treenode.index;
        var count = 1;

        var cur = 0;
        while (cur < queue.length ) {
            var node = queue[cur];
            var parentTreenode = tree.getNodeByIndex (node.index);

            for (var i =0; i < node.childList.length; i++ ) {
                child = hashtable.get (node.childList[i]);
                var clone = cloneNode (child);
                if (child.nchildren == 0 )
                    iconStatus = IS_LEAF;
                else if (child.nchildren == 1 || clone.id == sourceId)
                    iconStatus = BLANK;
                else
                    iconStatus = HAS_MORE            
                if (clone.id != sourceId ) {
                    treenode = new YAHOO.widget.MyNode (clone, parentTreenode, 1, iconStatus, uid);
                    count++;
                    clone.index = treenode.index;
                }
                else {   //sourceId = this one
                    //the node should be closed, but expandable if it has children
                    treenode = new YAHOO.widget.MyNode (clone, parentTreenode, 0, iconStatus, uid);
                    myparent = parentTreenode;  //this is to be sure that the siblings are displayed.
                    count++;
                           
                }
                queue[queue.length]   = clone;
              }
              cur++;
            }
              this.updateHighlighting (sourceId, uid);
       tree.draw();
     }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
  /* This is responded to the checkState clicks correctly.                                   */
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.loadNewChildren  = function (parentNode, onComplete, uid ) {

     if (parentNode == null ) {
        doDebug (" 105 parent was null " );
      }
 
     if (parentNode.hasChildren() && parentNode.checkState == BLANK)  {     
        parentNode.showChildren();
      }
     else  { 
        if (parentNode.data.node_clicked == true  || parentNode.checkState == HAS_MORE) {
              // first check the child cache
            var ele = getElement ('highlight'+uid);
            var highlightId = ele.getAttribute ('value');
            if ( this.useChildCache ( parentNode.data["id"]) ){
                var idx = parentNode.data["id"];
                for (var i = 0; i < childCache[idx].length; i++) {
                //is this one already here, if so, skip it.
                    var dup = this.isDuplicate ( parentNode.children, childCache[idx][i].id );
                    if ( dup == null ) {
                       iconStatus = getIconStatus (childCache[idx][i].nchildren, 0 );
                       var node = new YAHOO.widget.MyNode (childCache[idx][i], parentNode, 0, iconStatus,
uid );
                         //if by chance this one is highlighted somewhere else in the tree
                         if (childCache[idx][i].id == highlightId ) {
                             node.labelStyle="highlight";
                             node.updateCheckHtml();
                         }
                         childCache[idx][i].index = node.index;
                     }
                     // add the children to all the instances of this
                }
               parentNode.expanded = true;
               parentNode.checkState = BLANK;
               this.sortChildren (parentNode.children);
               // draw the tree
               this.getTree (uid ).draw();
              }
              else {
              try {
                  parentNode.data.node_clicked = true;
                  var query = "?func=getChildren&ontologyId="+ parentNode.data["ontId"] + "&termId=" + parentNode.data["id"]+ "&uid=" + parentNode.uid;
                  smdService.sendRequest ( query,"GET", smdService.stashChildren );
              } catch (e) {
                  doDebug ("load new children exception " + e );
                  }
             }
          }
       }
     }

  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.useChildCache = function (id) {

         if (childCache[id] && childCache[id].length > 0 )
            return true;
         return false;
     }
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
  /* node_clicked is a property of a tree node.  Use it to discover what node was clicked    */
  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
     OntologyTreeBrowser.prototype.findClickedTerm = function (treenode, sourceId, uid) {
        
       var clickedNodes = new Array();
       var clickedNode;
       var treediv = getElement ('treediv'+uid);
       var treeid = treediv.getAttribute ('treeId');
       var tree = YAHOO.widget.TreeView.getTree (treeid);
       clickedNodes = tree.getNodesByProperty ('node_clicked', true );
       for (var i=0; i < clickedNodes.length; i++ ) {
           if (clickedNodes[i].data.id != sourceId )
              clickedNodes[i].data.node_clicked = false;
           else
               clickedNode = clickedNodes[i];
       }
       if (clickedNode ) {
           return clickedNode;
       }
       return null;
     }


  /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
   * parse the xml doc and pluck out the fields we need to save                  *
   * *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
   
     parseTermList = function ( xmldoc, ontId ) {

        var childTerms = new Array();
        var i = 0;
        var sourceId = 0;
        var parentId = 0;
        var parentList = null;
        var nchildren;
        var iconStatus;

        if (xmldoc.hasChildNodes() && xmldoc.childNodes[0].nodeName == "TermList" ) {
            sourceId = xmldoc.childNodes[0].getAttribute ("sourceId"); 
            uid = xmldoc.childNodes[0].getAttribute ("uid" );
        } 
        var termList = xmldoc.getElementsByTagName ("Term" );
        var id, name, accession;
        for (var i=0; i < termList.length; i++) {
            var onenode = termList.item(i);
            var id = onenode.getAttribute ('id');
            var pids = 0;
            for (var j=0; j < onenode.childNodes.length; j++) {
                var node = onenode.childNodes.item(j);
                if (node.nodeName == "name" ) {
                   name = node.childNodes.item(0).nodeValue;
                }
                else if (node.nodeName == "accession") {
                   accession = node.childNodes.item(0).nodeValue;
                }
                else if (node.nodeName == "nChildren") {
                   nchildren = node.childNodes.item(0).nodeValue;
                   if (nchildren == 0 )
                      iconStatus = IS_LEAF;
                   else if (nchildren == 1 )
                      iconStatus = BLANK;  
                   else if (nchildren > 1)
                      iconStatus = HAS_MORE;
                }
                else if (node.nodeName == "parentId" ) {
                    parentId = node.childNodes.item(0).nodeValue;              
                }
                else if (node.nodeName == "parentIds" ) {
                    pids = node.childNodes.item(0).nodeValue;
                    parentList = new Array();
                    parentList = pids.split(", ");
                }
            }
        var oneterm = new Array();
            oneterm["id"] = id;
            oneterm["name"] = name;
            oneterm["label"] = name + " " + accession;
            oneterm["accession"] = accession;
            oneterm["sourceId"] = sourceId;
            oneterm["uid"] = uid;
            oneterm["ontId"] = ontId;
            oneterm["nchildren"] = nchildren;
            oneterm["iconstatus"] = iconStatus;
            oneterm["parentId"] = parentId;
            oneterm["node_clicked"] = false;
            if (pids != 0 ) {
               oneterm["parentList"] = new Array();
               oneterm["parentList"] = parentList;
             }
             else {
               oneterm["parentList"] = new Array();
               oneterm["parentList"][0] = 0;
             }
        
            oneterm["childList"] = new Array();
            childTerms[i] =  oneterm;
        }
        return childTerms;
        
     }


/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ 
   printList = function (termList) {

       for (var i = 0; i < termList.length; i++ ) {
            doDebug (termList[i].id + "  " + termList[i].name + " " + termList[i].accession );
            if (termList[i].parentList) {
               for (var j = 0; j < termList[i].parentList[j]; j++)
                   doDebug ("--------parents " + termList[i].parentList[j]);
            }
       }
   }
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ 
   OntologyTreeBrowser.prototype.clearTree = function (uid) {

      var treediv = getElement ('treediv'+uid);
      if (treediv == null ) {
          return;
      }
      var treeid = treediv.getAttribute ('treeId');
      var tree = YAHOO.widget.TreeView.getTree (treeid);
      var root = tree.getRoot();
      for ( var i = 0; i < root.nchildren; i++ )
          tree.removeChildren (root.children[i] );

      tree.draw();
      tree = new YAHOO.widget.TreeView('treediv'+ uid);
       
   }




