//****************************************************************
// Keep this copyright notice:
// This copy of the script is the property of the owner of the
// particular web site you were visiting.
// Do not download the script's files from there.
// For a free download and full instructions go to:
// http://www.treeview.net
//****************************************************************
// Log of changes:
//
//      31 Jan 03 - added support for custom scripts in OnClick etc
//      22 Sep 02 - added maySelect member for node-by-node control
//                  of selection and highlight
//      21 Sep 02 - Cookie values are now separated by ncCookieCutter
//      12 Sep 02 - VERSION 4.2 - Can highlight Selected Nodes and
//                  can preserve state through external (DB) IDs
//      29 Aug 02 - Fine tune 'supportDeferral' for IE4 and IE Mac
//      25 Aug 02 - Fixes: NC_STARTALLOPEN, and multi-page frameless
//      09 Aug 02 - Fix repeated folder on Mozilla 1.x
//      31 Jul 02 - VERSION 4.1 - Dramatic speed increase for trees
//      with hundreds or thousands of nodes; changes to the control
//      flags of the ncgLnk function
//      18 Jul 02 - Changes in pre-load images function
//      13 Jun 02 - Add NC_ICONPATH var to allow for gif subdir
//      20 Apr 02 - Improve support for frame-less layout
//      07 Apr 02 - Minor changes to support server-side dynamic feeding
//                  (example: FavoritesManagerASP)
// Definition of class ncFolder
// *****************************************************************
var gDebugOn = false;

// insertAdjacentHTML(), insertAdjacentText() and insertAdjacentElement ()
// for Netscape 6/Mozilla by Thor Larholm me@jscript.dk
// Usage: include this code segment at the beginning of your document
// before any other Javascript contents.



function ncFolder(folderDescription, hreference) //constructor
{
  //constant data
  this.desc = folderDescription;
  this.hreference = hreference;
  this.customonclick = "";
  this.customStateChange = "";
  this.useCustomStateChange = false; 
  this.id = -1;
  this.xID = "";
  this.navObj = 0;
  this.iconImg = 0;
  this.nodeImg = 0;
  this.isLastNode = 0;
  this.iconSrc = NC_ICONPATH + "ftv2folderopen.gif";
  this.iconSrcClosed = NC_ICONPATH + "ftv2folderclosed.gif";
  this.children = new Array;
  this.nChildren = 0;
  this.level = 0;
  this.leftSideCoded = "";
  this.isLastNode=false;
  this.parentObj = null;
  this.maySelect=true;

  //dynamic data
  this.isOpen = false;
  this.isLastOpenedFolder = false;
  this.isRendered = 0;

  //methods
  this.initialize = ncInitializeFolder;
  this.setState = ncSetStateFolder;
  this.standardStateChange = ncStandardStateChange;
  this.addChild = ncAddChild;
  this.createIndex = ncCreateEntryIndex;
  this.escondeBlock = ncEscondeBlock;
  this.esconde = ncEscondeFolder;
  this.folderMstr = ncFolderMstr;
  this.renderOb = ncDrawFolder;
  this.totalHeight = totalHeight;
  this.subEntries = ncFolderSubEntries;
  this.linkHTML = ncLinkFolderHTML;
  this.blockStartHTML = ncBlockStartHTML;
  this.blockEndHTML = ncBlockEndHTML;
  this.nodeImageSrc = ncNodeImageSrc;
  this.iconImageSrc = ncIconImageSrc;
  this.getID = ncGetID;
  this.forceOpeningOfAncestorFolders = ncForceOpeningOfAncestorFolders;
  this.descendantByXID = ncFolder_DescendantByXID;
}

//Recursively look for a descendant with matching xID
//Also check self.
function ncFolder_DescendantByXID(aXID)
{
//alert('ncFolder_DescendantByXID(' + aXID + ')');
  var result;
  if (this.xID == aXID) {
    return (this);
  }
  try { 
    for (var i = 0; i < this.children.length; i ++) {
      try {
        try {
          if (this.children[i].xID == aXID) {     
            return(this.children[i]);
            break;
          }
        }
        catch (e)
        {
          alert('Looking in my children: ' + e.message);
        }
        
        try {
          result = (this.children[i].descendantByXID(aXID));
          if (result) {
            return result;
            break;
          }       
        }
        catch(e)
        {
          alert('Looking in my grandchildren: ' + e.message);
          alert('Bad child: ' + this.children[i].desc)
        } 
      }
      catch(e) {
        alert('Main loop: ' + e.message);
      }
    }
  }
  catch(e) {
    alert('Main body: ' + e.message);
  }
}
function ncInitializeFolder(level, lastNode, leftSide)
{
//alert('init folder start');
  var j=0;
  var i=0;
  nc = this.nChildren;
  this.createIndex();
  this.level = level;
  this.leftSideCoded = leftSide;
  if (ncBrowserVersion == 0 || NC_STARTALLOPEN==1) {
    this.isOpen=true;
  }
  if (level>0) {
    if (lastNode) {//the last child in the children array
        leftSide = leftSide + "0";
    } else {
        leftSide = leftSide + "1";
    }
  }
  this.isLastNode = lastNode;
  if (nc > 0)
  {
    level = level + 1;
    for (i=0 ; i < this.nChildren; i++)
    {
      if (i == this.nChildren-1){
        try {
            this.children[i].initialize(level, 1, leftSide);
        }
        catch (e) {
          alert(e.name + ' - ' + e.message);
        }
      }
      else {
        try {
          this.children[i].initialize(level, 0, leftSide);
        }
        catch(e) {
          alert(e.name + ' - ' + e.message);
        }
      }
    }
  }
//alert('init folder end');
}

function ncDrawFolder(insertAtObj)
{
//alert('Drawing folder ' + this.desc + ' insertAtObj = ' + insertAtObj);
  var nodeName = "";
  var auxEv = "";
  var auxEvFolder = "";
  var docW = "";

  var leftSide = ncLeftSideHTML(this.leftSideCoded);
  if (ncBrowserVersion > 0){
    auxEv = "<a baz=hidefocus href='#' "+ncLinkStyle+" onClick='"+ncWindowObj+"ncClickOnNode(\""+this.getID()+"\", true); return false;'>";
 
  } else {
    auxEv = "<a>";
  }

  nodeName = this.nodeImageSrc();

  if (this.level>0) {
    if (this.isLastNode) { //the last child in the children array
        leftSide = leftSide + "<td valign=top>" + auxEv + "<img name='ncNodeIcon" + this.id + "' id='ncNodeIcon" + this.id + "' src='" + nodeName + "' width=16 height=22 border=0></a></td>";
    } else {
      leftSide = leftSide + "<td valign=top background=" + NC_ICONPATH + "ftv2vertline.gif>" + auxEv + "<img name='ncNodeIcon" + this.id + "' id='ncNodeIcon" + this.id + "' src='" + nodeName + "' width=16 height=22 border=0></a></td>";
    }
  }
  this.isRendered = 1;

  if (ncBrowserVersion == 2) {
    if (!ncDoc.yPos){
      ncDoc.yPos=20;
    }
  }

  docW = this.blockStartHTML("ncFolder");

  docW = docW + "<tr>" + leftSide + "<td valign=top>";
  if (NC_USEICONS)
  {
    docW = docW + this.linkHTML(false);
    docW = docW + "<img id='ncFolderIcon" + this.id + "' name='ncFolderIcon" + this.id + "' src='" + this.iconImageSrc() + "' border=0></a>";
  }
  else
  {
      docW = docW + "<img src=" + NC_ICONPATH + "ftv2blank.gif height=2 width=2>";
  }
  if (NC_WRAPTEXT) {
      docW = docW + "</td><td valign=middle width=100%>";
  } else {
      docW = docW + "</td><td valign=middle nowrap width=100%>";
  }
  if (NC_USETEXTLINKS)
  {
    docW = docW + this.linkHTML(true);
    docW = docW + this.desc + "</a>";
  }
  else {
    docW = docW + this.desc;
  }
  docW = docW + "</td>";

  docW = docW + this.blockEndHTML();

  if (insertAtObj == null)
  {
//alert('No insertAtObj found');
    if (ncSupportsDeferral) {

      insertAtObj = ncGetElById("ncDomRoot");
      if (insertAtObj) {
        insertAtObj.insertAdjacentHTML("beforeEnd", docW);
      }
      else { 
//The following line fails when folders loaded dynamically. Instead, we will assume a parent element 'ncDomRoot'
//try {
//	var domRoot = document.createElement('div');
//	domRoot.id = 'ncDomRoot';
//   document.documentElement.appendChild(domRoot);
// }
// catch(e) {
// 	 alert('failed ncDomRoot: ' + e.message);
	        //There must be an ncDomRoot element available as the parent for the folder tree. 
// }

//            var domRoot = document.createElement('div');
//            domRoot.id = 'ncDomRoot';
//            insertAtObj = document.body.appendChild(domRoot);
//            insertAtObj.insertAdjacentHTML("beforeEnd",docW);
            alert ("ncTVSiteMap: ncDomRoot element not found: ");
		    return false;
      }
    }
    else {
      ncDoc.write(docW);
    }
  }
  else
  {
      insertAtObj.insertAdjacentHTML("afterEnd", docW);
  }

  if (ncBrowserVersion == 2)
  {
    this.navObj = ncDoc.layers["ncFolder"+this.id];
    if (NC_USEICONS) {
      this.iconImg = this.navObj.document.images["ncFolderIcon"+this.id];
    }
    this.nodeImg = this.navObj.document.images["ncNodeIcon"+this.id];
    ncDoc.yPos=ncDoc.yPos+this.navObj.clip.height;
  }
  else if (ncBrowserVersion != 0)
  {
    this.navObj = ncGetElById("ncFolder"+this.id);
    if (NC_USEICONS) {
      this.iconImg = ncGetElById("ncFolderIcon"+this.id);
    }
    this.nodeImg = ncGetElById("ncNodeIcon"+this.id);
  }
}


function ncSetStateFolder(isOpen)
{
  var subEntries;
  var totalHeight;
  var fIt = 0;
  var i=0;
  var currentOpen;

  if (isOpen == this.isOpen) {
    return;
  }
  //zzz
  if (this.useCustomStateChange && !this.isOpen) {
    //alert('Calling custom state change for ' + this.desc + ' isOpen = [' + this.isOpen +']');
    this.customStateChange(this);
  }
  else {
    //alert('Not calling custom state change for ' + this.desc);
    this.standardStateChange(isOpen);
   }
}

function ncStandardStateChange(isOpen)
{
    //alert('Standard State Change');
  ncFoldersTree.initialize(0, true, "");
    if (ncBrowserVersion == 2)
    {
      totalHeight = 0;
      for (i=0; i < this.nChildren; i++){
        totalHeight = totalHeight + this.children[i].navObj.clip.height;
      }
      subEntries = this.subEntries();
      if (this.isOpen){
        totalHeight = 0 - totalHeight;
      }
      for (fIt = this.id + subEntries + 1; fIt < nc_nEntries; fIt++) {
        ncIndexOfEntries[fIt].navObj.moveBy(0, totalHeight);
      }
    }
    this.isOpen = isOpen;
  
    if (this.getID()!=ncFoldersTree.getID() && NC_PERSERVESTATE && !this.isOpen) //closing
    {
       currentOpen = ncGetCookie("clickedFolder");
       if (currentOpen != null) {
           currentOpen = currentOpen.replace(this.getID()+ncCookieCutter, "");
           ncSetCookie("clickedFolder", currentOpen);
       }
    }
  
    if (!this.isOpen && this.isLastOpenedfolder)
    {
          ncLastOpenedFolder = null;
          this.isLastOpenedfolder = false;
    }
    ncPropagateChangesInState(this);
}

function ncPropagateChangesInState(folder)
{
  var i=0;

  //Change icon
  if (folder.nChildren > 0 && folder.level>0) {  //otherwise the one given at render stays
    folder.nodeImg.src = folder.nodeImageSrc();
  }

  //Change node
  if (NC_USEICONS) {
    folder.iconImg.src = folder.iconImageSrc();
  }

  //Propagate changes
  for (i=folder.nChildren-1; i>=0; i--) {
    if (folder.isOpen) {
      folder.children[i].folderMstr(folder.navObj);
    } else {
        folder.children[i].esconde();
    }
  }
}

function ncEscondeFolder()
{
  this.escondeBlock();
  this.setState(0);
}

function ncLinkFolderHTML(isTextLink)
{
  var docW = "";

  if (this.hreference)
  {
    if (NC_USEFRAMES) {
      docW = docW + "<a baz=hidefocus href='" + this.hreference + "' TARGET=\"basefrm\" ";
    } else {
      docW = docW + "<a baz=hidefocus href='" + this.hreference + "' TARGET=_top ";
    }
    if (isTextLink) {
        docW += "id=\"ncItemTextLink"+this.id+"\" ";
    }
    if ((this.customonclick) && (this.customonclick != "")) {

      if (ncBrowserVersion > 0) {
//onmouseover=\"parent.window.status=\'"+this.getID()+"\';\"
        docW = docW + " "+ncLinkStyle+" onClick=\""+ncWindowObj+"ncClickOnFolder(\'"+this.getID()+"\'); if (!"+ncWindowObj+"ncInSelectNodeByID) {"+this.customonclick+"}else{return false};\"";
      }
    }else {
      if (ncBrowserVersion > 0)
        docW = docW + " "+ncLinkStyle+" onClick='"+ncWindowObj+"ncClickOnFolder(\""+this.getID()+"\")'";
    }
    docW = docW + ">";
  } else {
    docW = docW + "<a>";
  }
  return docW;
}

function ncAddChild(childNode)
{
  this.children[this.nChildren] = childNode;
  childNode.parentObj = this;
  this.nChildren++;
  return childNode;
}

function ncFolderSubEntries()
{
  var i = 0;
  var se = this.nChildren;

  for (i=0; i < this.nChildren; i++){
    if (this.children[i].children) { //is a folder
      se = se + this.children[i].subEntries();
    }
  }
  return se;
}

function ncNodeImageSrc() {
  var srcStr = "";

  if (this.isLastNode) //the last child in the children array
  {
    if (this.nChildren == 0) {
      srcStr = NC_ICONPATH + "ftv2lastnode.gif";
    } else {
      if (this.isOpen) {
        srcStr = NC_ICONPATH + "ftv2mlastnode.gif";
      } else {
        srcStr = NC_ICONPATH + "ftv2plastnode.gif";
      }
    }
  } else {
    if (this.nChildren == 0) {
      srcStr = NC_ICONPATH + "ftv2node.gif";
    } else {
      if (this.isOpen) {
        srcStr = NC_ICONPATH + "ftv2mnode.gif";
      } else {
        srcStr = NC_ICONPATH + "ftv2pnode.gif";
      }
    }
  }
  return srcStr;
}

function ncIconImageSrc() {
  if (this.isOpen) {
    return(this.iconSrc);
  } else {
    return(this.iconSrcClosed);
  }
}

// Definition of class ncItem (a document or link inside a ncFolder)
// *************************************************************

function ncItem(itemDescription, itemLink, target) // Constructor
{
  // constant data
  this.desc = itemDescription;
  this.link = itemLink;
  this.id = -1; //initialized in initalize()
  this.navObj = 0; //initialized in render()
  this.iconImg = 0; //initialized in render()
  this.iconSrc = NC_ICONPATH + "ftv2doc.gif";
  this.isRendered = 0;
  this.isLastNode = false;
  this.level = 0;
  this.leftSideCoded = "";
  this.nChildren = 0;
  this.target = target;
  this.parentObj = null;
  this.maySelect=true;

  // methods
  this.initialize = ncInitializeItem;
  this.createIndex = ncCreateEntryIndex;
  this.escondeBlock = ncEscondeBlock;
  this.esconde = ncEscondeBlock;
  this.folderMstr = ncFolderMstr;
  this.renderOb = ncDrawItem;
  this.totalHeight = totalHeight;
  this.blockStartHTML = ncBlockStartHTML;
  this.blockEndHTML = ncBlockEndHTML;
  this.getID = ncGetID;
  this.forceOpeningOfAncestorFolders = ncForceOpeningOfAncestorFolders;
}

function ncInitializeItem(level, lastNode, leftSide)
{
  this.createIndex();
  this.level = level;
  this.leftSideCoded = leftSide;
  this.isLastNode = lastNode;
}

function ncDrawItem(insertAtObj)
{
  var leftSide = ncLeftSideHTML(this.leftSideCoded);
  var docW = "";

  var fullLink = "href=\""+this.link+"\" target=\""+this.target+"\" onClick=\""+ncWindowObj+"ncClickOnLink('"+this.getID()+"\', '"+this.link+"','"+this.target+"');return false;\"";
  this.isRendered = 1;

  if (this.level>0) {
    if (this.isLastNode) //the last 'brother' in the children array
    {
      leftSide = leftSide + "<td valign=top><img src='" + NC_ICONPATH + "ftv2lastnode.gif' width=16 height=22></td>";
    }
    else
    {
      leftSide = leftSide + "<td valign=top background=" + NC_ICONPATH + "ftv2vertline.gif><img src='" + NC_ICONPATH + "ftv2node.gif' width=16 height=22></td>";
    }
  }

  docW = docW + this.blockStartHTML("ncItem");

  docW = docW + "<tr>" + leftSide + "<td valign=top>";
  if (NC_USEICONS) {
      docW = docW + "<a baz=hidefocus " + fullLink  + " id=\"ncItemIconLink"+this.id+"\">" + "<img id='ncItemIcon"+this.id+"' " + "src='"+this.iconSrc+"' border=0>" + "</a>";
  } else {
      docW = docW + "<img src=" + NC_ICONPATH + "ftv2blank.gif height=2 width=3>";
  }

  if (NC_WRAPTEXT) {
    docW = docW + "</td><td valign=middle width=100%>";
  } else {
    docW = docW + "</td><td valign=middle nowrap width=100%>";
  }

  if (NC_USETEXTLINKS) {
    docW = docW + "<a baz=hidefocus " + fullLink + " id=\"ncItemTextLink"+this.id+"\">" + this.desc + "</a>";
  } else {
    docW = docW + this.desc;
  }

  docW = docW + "</td>";

  docW = docW + this.blockEndHTML();

  if (insertAtObj == null)
  {
      ncDoc.write(docW);
  }
  else
  {
      insertAtObj.insertAdjacentHTML("afterEnd", docW);
  }

  if (ncBrowserVersion == 2) {
    this.navObj = ncDoc.layers["ncItem"+this.id];
    if (NC_USEICONS) {
      this.iconImg = this.navObj.document.images["ncItemIcon"+this.id];
    }
    ncDoc.yPos=ncDoc.yPos+this.navObj.clip.height;
  } else if (ncBrowserVersion != 0) {
    this.navObj = ncGetElById("ncItem"+this.id);
    if (NC_USEICONS) {
      this.iconImg = ncGetElById("ncItemIcon"+this.id);
    }
  }
}


// Methods common to both objects (pseudo-inheritance)
// ********************************************************

function ncForceOpeningOfAncestorFolders() {
  if (this.parentObj == null || this.parentObj.isOpen) {
    return;
  } else {
    this.parentObj.forceOpeningOfAncestorFolders();
    ncClickOnNodeObj(this.parentObj);
  }
}

function ncEscondeBlock()
{
  if (ncBrowserVersion == 1 || ncBrowserVersion == 3) {
    if (this.navObj.style.display == "none") {
      return;
    }
    this.navObj.style.display = "none";
  } else {
    if (this.navObj.visibility == "hidden") {
      return;
    }
    this.navObj.visibility = "hidden";
  }
}

function ncFolderMstr(domObj)
{
//  if (ncBrowserVersion == 1 || ncBrowserVersion == 3) {
//    if (ncT==-1)
//      return
//    var str = new String(ncDoc.links[ncT])
//    if (str.slice(36,38) != "rh")
//      return
//  }

  if (!this.isRendered) {
     this.renderOb(domObj);
  } else {
    if (ncBrowserVersion == 1 || ncBrowserVersion == 3) {
      this.navObj.style.display = "block";
    } else {
      this.navObj.visibility = "show";
    }
  }
}

function ncBlockStartHTML(idprefix) {
  var idParam = "id='" + idprefix + this.id + "'";
  var docW = "";

  if (ncBrowserVersion == 2) {
    docW = "<layer "+ idParam + " top=" + ncDoc.yPos + " visibility=show>";
  } else if (ncBrowserVersion != 0) {
    docW = "<div " + idParam + " style='display:block; position:block;'>";
  }

  docW = docW + "<table border=0 cellspacing=0 cellpadding=0 width=100% >";

  return docW;
}

function ncBlockEndHTML() {
  var docW = "";

  docW = "</table>";

  if (ncBrowserVersion == 2) {
    docW = docW + "</layer>";
  } else if (ncBrowserVersion != 0) {
    docW = docW + "</div>";
  }

  return docW;
}

function ncCreateEntryIndex()
{
  this.id = nc_nEntries;
  ncIndexOfEntries[nc_nEntries] = this;
  nc_nEntries++;
}

// total height of subEntries open
function totalHeight() //used with ncBrowserVersion == 2
{
  var h = this.navObj.clip.height;
  var i = 0;

  if (this.isOpen) { //is a folder and _is_ open
    for (i=0 ; i < this.nChildren; i++) {
      h = h + this.children[i].totalHeight();
    }
  }

  return h;
}


function ncLeftSideHTML(leftSideCoded) {
    var i;
    var retStr = "";

    for (i=0; i<leftSideCoded.length; i++)
    {
        if (leftSideCoded.charAt(i) == "1")
        {
            retStr = retStr + "<td valign=top background=" + NC_ICONPATH + "ftv2vertline.gif><img src='" + NC_ICONPATH + "ftv2vertline.gif' width=16 height=22></td>";
        }
        if (leftSideCoded.charAt(i) == "0")
        {
            retStr = retStr + "<td valign=top><img src='" + NC_ICONPATH + "ftv2blank.gif' width=16 height=22></td>";
        }
    }
    return retStr;
}

function ncGetID()
{
  //define a .xID in all nodes (folders and items) if you want to PERVESTATE that
  //work when the tree changes. The value eXternal value must be unique for each
  //node and must node change when other nodes are added or removed
  //The value may be numeric or string, but cannot have the same char used in ncCookieCutter
  if (typeof this.xID != "undefined") {
    return this.xID;
  } else {
    return this.id;
  }
}


// Events
// *********************************************************

function ncClickOnFolder(folderId)
{
	debugStr('ncClickOnFolder() start')
    var clicked = ncFindObj(folderId);
    if (!clicked.isOpen) {
      ncClickOnNodeObj(clicked, false);
    }
    if (ncLastOpenedFolder != null && ncLastOpenedFolder != folderId) {
      ncClickOnNode(ncLastOpenedFolder, false); //sets ncLastOpenedFolder to null
    }

    if (clicked.nChildren==0) {
      ncLastOpenedFolder = folderId;
      clicked.isLastOpenedfolder = true;
    }

    if (ncIsLinked(clicked.hreference)) {
        ncHighlightObjLink(clicked);
    } 
}

function ncClickOnNode(folderId, expand)
{
  if (expand === null) { expand = true; }
  ncClickOnNodeObj(ncFindObj(folderId), expand);
}


function pausecomp(millis)
{
date = new Date();
var curDate = null;

do { var curDate = new Date(); }
while(curDate-date < millis);
}


function ncClickOnNodeObj(folderObj, expand)
{
//pausecomp(400);
  var state = 0;
  var currentOpen;
  if (expand === null) { expand = true; }

    state = folderObj.isOpen; 
  
    if (folderObj.id!=ncFoldersTree.id && NC_PERSERVESTATE)
    {
      currentOpen = ncGetCookie("clickedFolder");
      if (currentOpen == null) {
        currentOpen = "";
      }
  
      if (!folderObj.isOpen) //closing
      {
        currentOpen = currentOpen.replace(folderObj.getID()+ncCookieCutter, "");
        ncSetCookie("clickedFolder", currentOpen);
      }
      else {
        ncSetCookie("clickedFolder", currentOpen+folderObj.getID()+ncCookieCutter);
      }
    }
//alert(folderObj.id);
    if ((expand == true) || (folderObj.id == 0)) { 
        folderObj.setState(!state);//open<->close
    }

}

function ncClickOnLink(clickedId, target, windowName) {
    ncHighlightObjLink(ncFindObj(clickedId));
    if (ncIsLinked(target)) {
      window.open(target,windowName);
    }
}

function ncld  ()
{
    return document.links.length-1;
}


// Auxiliary Functions
// *******************

function ncSelectNodeByID(id) {
// Select the Node found by id in the TreeView
// This makes it easier to select a node at runtime, and ensure
// that it is visible.
  ncInSelectNodeByID = true;
  try {
    if (id == ""||id == "undefined") {
      return;
    }
    var node = ncFindObj(id.toLowerCase());
    if (node == null) {
      var node = ncFindObj(id);
    }
    if (node != null) {
      node.forceOpeningOfAncestorFolders();
      ncDoc.all["ncItemTextLink"+node.id].click();
    }
  } catch(e) {
  }
  ncInSelectNodeByID = false;
}

function ncFindObj(id)
{
  var i=0;
  var nodeObj;
  // If custom IDs are being used, find the "real" id.
  if (typeof ncFoldersTree.xID != "undefined") {
    nodeObj = ncIndexOfEntries[i];
    for(var i=0;i<nc_nEntries&&ncIndexOfEntries[i].xID!=id;i++){ //may need optimization
      ;
    }
    id = i;
  }
  if (id >= nc_nEntries) {
    return null; //example: node removed in DB
  } else {
    return ncIndexOfEntries[id];
  }
}

function ncIsLinked(hrefText) {
    var result = true;
    result = (result && hrefText !=null);
    result = (result && hrefText != '');
    result = (result && hrefText.indexOf('undefined') < 0);
    result = (result && hrefText.indexOf('parent.op') < 0);
    return result;
}

// Do highlighting by changing background and foreg. colors of folder or ncDoc text
function ncHighlightObjLink(nodeObj) {
debugStr('ncHighlightObjLink() start')
  if (!NC_HIGHLIGHT || nodeObj==null || nodeObj.maySelect==false) {//node deleted in DB
    return;
  }
  if (ncBrowserVersion == 1 || ncBrowserVersion == 3) {
    var clickedDOMObj = ncGetElById('ncItemTextLink'+nodeObj.id);
    if (clickedDOMObj != null) {
        if (ncLastClicked != null) {
            var prevClickedDOMObj = ncGetElById('ncItemTextLink'+ncLastClicked.id);
  
            //prevClickedDOMObj.style.color=ncLastClickedColor;
            //prevClickedDOMObj.style.backgroundColor=ncLastClickedBgColor;
      //alert('switched off previous highlight');
        }
        ncLastClickedColor    = clickedDOMObj.style.color;
        ncLastClickedBgColor  = clickedDOMObj.style.backgroundColor;
    //BE 18/09/06 Removed highlighting temporarily, as doesn't work consistently. See Trac #42
        //clickedDOMObj.style.color=NC_HIGHLIGHT_COLOR;
        //clickedDOMObj.style.backgroundColor=NC_HIGHLIGHT_BG;
    }
    else {
    }
  }
  ncLastClicked = nodeObj;
  if (NC_PERSERVESTATE) {
    ncSetCookie('highlightedTreeviewLink', nodeObj.getID());
  }
  }

function ncgFldNew(description, hreference, customonclick)
{
  var folder = new ncFolder(description, hreference);
  folder.customonclick = customonclick;
  return folder;
}

function ncgFld(description, hreference)
{
  var folder = new ncFolder(description, hreference);
  return folder;
}

function ncgLnk(optionFlags, description, linkData)
{
  var fullLink = "";
  var targetFlag = "";
  var target = "";
  var protocolFlag = "";
  var protocol = "";

  targetFlag = optionFlags.charAt(0);
  if (targetFlag=="B")
    target = "_blank";
  if (targetFlag=="P")
    target = "_parent";
  if (targetFlag=="R")
    target = "basefrm";
  if (targetFlag=="S")
    target = "_self";
  if (targetFlag=="T")
    target = "_top";

  if (optionFlags.length > 1) {
    protocolFlag = optionFlags.charAt(1);
    if (protocolFlag=="h")
      protocol = "http://";
    if (protocolFlag=="s")
      protocol = "https://";
    if (protocolFlag=="f")
      protocol = "ftp://";
    if (protocolFlag=="m")
      protocol = "mailto:";
  }

  fullLink = "'" + protocol + linkData + "' target=" + target;

  linkItem = new ncItem(description, protocol+linkData, target);
  return linkItem;
}

function ncInsFld(parentFolder, childFolder)
{
  return parentFolder.addChild(childFolder);
}

function ncInsDoc(parentFolder, document)
{
  return parentFolder.addChild(document);
}

function ncPreLoadIcons() {
    var auxImg;
    auxImg = new Image();
    auxImg.src = NC_ICONPATH + "ftv2vertline.gif";
    auxImg.src = NC_ICONPATH + "ftv2mlastnode.gif";
    auxImg.src = NC_ICONPATH + "ftv2mnode.gif";
    auxImg.src = NC_ICONPATH + "ftv2plastnode.gif";
    auxImg.src = NC_ICONPATH + "ftv2pnode.gif";
    auxImg.src = NC_ICONPATH + "ftv2blank.gif";
    auxImg.src = NC_ICONPATH + "ftv2lastnode.gif";
    auxImg.src = NC_ICONPATH + "ftv2node.gif";
    auxImg.src = NC_ICONPATH + "ftv2folderclosed.gif";
    auxImg.src = NC_ICONPATH + "ftv2folderopen.gif";
    auxImg.src = NC_ICONPATH + "ftv2doc.gif";
}

//Open some folders for initial layout, if necessary
function ncSetInitialLayout() {
  if (ncBrowserVersion > 0 && !NC_STARTALLOPEN) {
    ncClickOnNodeObj(ncFoldersTree);
  }

  if (!NC_STARTALLOPEN && (ncBrowserVersion > 0) && NC_PERSERVESTATE) {
    ncPersistentFolderOpening();
  }
}

//Used with NS4 and NC_STARTALLOPEN
function ncRenderAllTree(nodeObj, parent) {
  var i=0;
  nodeObj.renderOb(parent);
  if (ncSupportsDeferral) {
    for (i=nodeObj.nChildren-1; i>=0; i--) {
      ncRenderAllTree(nodeObj.children[i], nodeObj.navObj);
    }
  } else {
    for (i=0 ; i < nodeObj.nChildren; i++) {
      ncRenderAllTree(nodeObj.children[i], null);
    }
  }
}

function ncHideWholeTree(nodeObj, hideThisOne, nodeObjMove) {
  var i=0;
  var heightContained=0;
  var childrenMove=nodeObjMove;

  if (hideThisOne) {
    nodeObj.escondeBlock();
  }

  if (ncBrowserVersion == 2) {
    nodeObj.navObj.moveBy(0, 0-nodeObjMove);
  }

  for (i=0 ; i < nodeObj.nChildren; i++) {
    heightContainedInChild = ncHideWholeTree(nodeObj.children[i], true, childrenMove);
    if (ncBrowserVersion == 2) {
      heightContained = heightContained + heightContainedInChild + nodeObj.children[i].navObj.clip.height;
      childrenMove = childrenMove + heightContainedInChild;
    }
  }

  return heightContained;
}


// Simulating inserAdjacentHTML on NS6
// Code by thor@jscript.dk
// ******************************************

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
    HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode)
    {
        switch (where){
        case 'beforeBegin':
            this.parentNode.insertBefore(parsedNode,this);
            break;
        case 'afterBegin':
            this.insertBefore(parsedNode,this.firstChild);
            break;
        case 'beforeEnd':
            this.appendChild(parsedNode);
            break;
        case 'afterEnd':
            if (this.nextSibling) {
                this.parentNode.insertBefore(parsedNode,this.nextSibling);
            } else { this.parentNode.appendChild(parsedNode); }
            break;
        }
    };

    HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr)
    {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement(where,parsedHTML);
    };
}

function ncGetElById(idVal) {
  if (document.getElementById != null) {
    if (document.getElementById(idVal) == null) {
      return ncDoc.getElementById(idVal);
    } else {
      return document.getElementById(idVal);
    }
  }
  if (document.all != null) {
    if (document.all[idVal] == null) {
      return ncDoc.all[idVal];
    } else {
      return document.all[idVal];
    }
  }

  alert("Problem getting element by id");
  return null;
}


// Functions for cookies
// Note: THESE FUNCTIONS ARE OPTIONAL. No cookies are used unless
// the NC_PERSERVESTATE variable is set to 1 (default 0)
// The separator currently in use is ^ (chr 94)
// ***********************************************************

function ncPersistentFolderOpening()
{
  var stateInCookie;
  var fldStr="";
  var fldArr;
  var fldPos=0;
  var id;
  var nodeObj;
  stateInCookie = ncGetCookie("clickedFolder");
  ncSetCookie('clickedFolder', ""); //at the end of function it will be back, minus null cases

  if(stateInCookie!=null)
  {
    fldArr = stateInCookie.split(ncCookieCutter);
    for (fldPos=0; fldPos<fldArr.length; fldPos++)
    {
      fldStr=fldArr[fldPos];
      if (fldStr != "") {
        nodeObj = ncFindObj(fldStr);
        if (nodeObj!=null) { //may have been deleted
          if (nodeObj.setState) {
            nodeObj.forceOpeningOfAncestorFolders();
            ncClickOnNodeObj(nodeObj);
          }
          else {
            alert("Internal id is not pointing to a folder anymore. Consider using external IDs");
          }
        }
      }
    }
  }
}

function ncStoreAllNodesInClickCookie(treeNodeObj)
{
  var currentOpen;
  var i = 0;

  if (typeof treeNodeObj.setState != "undefined") //is folder
  {
    currentOpen = ncGetCookie("clickedFolder");
    if (currentOpen == null) {
      currentOpen = "";
    }

    if (treeNodeObj.getID() != ncFoldersTree.getID()) {
      ncSetCookie("clickedFolder", currentOpen+treeNodeObj.getID()+ncCookieCutter);
    }

    for (i=0; i < treeNodeObj.nChildren; i++) {
        ncStoreAllNodesInClickCookie(treeNodeObj.children[i]);
    }
  }
}

function ncCookieBranding(name) {
  if (typeof ncFoldersTree.treeID != "undefined") {
    return name+ncFoldersTree.treeID; //needed for multi-tree sites. make sure treeId does not contain ncCookieCutter
  } else {
    return name;
  }
}

function ncGetCookie(name)
{
  name = ncCookieBranding(name);

    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;

    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return ncGetCookieVal (j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0){ break;}
    }
    return null;
}

function ncGetCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
      endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

function ncSetCookie(name, value)
{
    var argv = ncSetCookie.arguments;
    var argc = ncSetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    //var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    var path = "/"; //allows the tree to remain open across pages with diff names & paths

  name = ncCookieBranding(name);

    document.cookie = name + "=" + escape (value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

function ncExpireCookie (name)
{
    var exp = new Date();
    exp.setTime (exp.getTime() - 1);
    var cval = ncGetCookie (name);
  name = ncCookieBranding(name);
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}


//To customize the tree, overwrite these variables in the configuration file (demoFramesetNode.js, etc.)
var NC_USETEXTLINKS = 1;
var NC_STARTALLOPEN = 0;
var NC_USEFRAMES = 1;
var NC_USEICONS = 1;
var NC_WRAPTEXT = 0;
var NC_PERSERVESTATE = 0;
var NC_ICONPATH = '';
var NC_HIGHLIGHT = 0;
var NC_HIGHLIGHT_COLOR = 'white';
var NC_HIGHLIGHT_BG    = 'blue';


//Other variables
var ncInSelectNodeByID = false;
var ncLastClicked = null;
var ncLastClickedColor;
var ncLastClickedBgColor;
var ncIndexOfEntries = new Array;
var nc_nEntries = 0;
var ncBrowserVersion = 0;
var ncSelectedFolder=0;
var ncLastOpenedFolder=null;
var ncT=5;
var ncDoc = document;
var ncSupportsDeferral = false;
var ncCookieCutter = '^'; //You can change this if you need to use ^ in your xID or treeID values
var ncWindowObj = ''; // e.g. "parent." if current window then leave blank.
var ncLinkStyle = ''; // e.g. "className" if none leave blank.

ncDoc.yPos = 0;

// Main function
// *************

// This function uses an object (navigator) defined in
// ua.js, imported in the main html page (left frame).
function ncInitialiseDocument()
{
  ncPreLoadIcons();
  
  switch(navigator.family)
  {
    case 'ie4':
      ncBrowserVersion = 1; //Simply means IE > 3.x
      break;
    case 'nn4':
      ncBrowserVersion = 2; //NS4.x
      break;
    case 'gecko':
      ncBrowserVersion = 3; //NS6.x
      break;
    default:
      ncBrowserVersion = 0; //other, possibly without DHTML
      break;
  }
  ncSupportsDeferral = ((ncBrowserVersion == 1 && navigator.version >= 5 && navigator.OS != "mac") || ncBrowserVersion == 3);
  if (!NC_USEFRAMES && ncBrowserVersion == 2) {
      ncBrowserVersion = 0;
  }
  
  // Create the ncDomRoot if not already created
  if (ncSupportsDeferral) {
    if (!document.getElementById('ncDomRoot')) {
        ncDoc.write("<div id=ncDomRoot></div>"); //transition between regular flow HTML, and node-insert DOM DHTML
    }
  }  
 

  //eval(String.fromCharCode(116,61,108,100,40,41))

  //If NC_PERSERVESTATE is on, NC_STARTALLOPEN can only be effective the first time the page
  //loads during the session. For subsequent (re)loads the NC_PERSERVESTATE data stored
  //in cookies takes over the control of the initial expand/collapse
  if (NC_PERSERVESTATE && ncGetCookie("clickedFolder") != null) {
    NC_STARTALLOPEN = 0;
  }
  //ncFoldersTree (with the site's data) is created in an external .js (demoFramesetNode.js, for example)
  

  ncFoldersTree.initialize(0, true, "");

  if (ncSupportsDeferral && !NC_STARTALLOPEN) {

      ncFoldersTree.renderOb(null); //delay construction of nodes

  } 
  else {
    ncRenderAllTree(ncFoldersTree, null);
    if (NC_PERSERVESTATE && NC_STARTALLOPEN) {
      ncStoreAllNodesInClickCookie(ncFoldersTree);
    }

    //To force the scrollable area to be big enough
    if (ncBrowserVersion == 2) {
      ncDoc.write("<layer top=" + ncIndexOfEntries[nc_nEntries-1].navObj.top + ">&nbsp;</layer>");
    }

    if (ncBrowserVersion != 0 && !NC_STARTALLOPEN) {
      ncHideWholeTree(ncFoldersTree, false, 0);
    }
  }
  ncSetInitialLayout();
  if (NC_PERSERVESTATE && ncGetCookie('highlightedTreeviewLink')!=null  && ncGetCookie('highlightedTreeviewLink')!="") {
    var nodeObj = ncFindObj(ncGetCookie('highlightedTreeviewLink'));
    if (nodeObj!=null){
      nodeObj.forceOpeningOfAncestorFolders();
      ncHighlightObjLink(nodeObj);
    } else {
      ncSetCookie('highlightedTreeviewLink', '');
    }
  }
}
 
function debugStr(s)
{
  if (gDebugOn) {	
	var debugEl = document.getElementById('ncDebug');
	if (debugEl) {
		debugEl.innerHTML = debugEl.innerHTML + s + '<br />';
	}
  }
}

function debugClear()
{
	var debugEl = document.getElementById('ncDebug');
	if (debugEl) {
		debugEl.innerHTML = '';
	}
}



