/* 
 * Copyright 2008 Scott Douglass, all rights reserved.
 *   http://swdouglass.com/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * on the World Wide Web for all details:
 * 
 *   http://www.fsf.org/licensing/licenses/gpl.txt
 * 
 */

// create the base SWD object if it does not exist.
if (!SWD) {
  var SWD = {};
}

var treeCookie = "SWDTreeCookie";
var nodeList = "";
var updateCookie = 1;

if (!SWD.Tree) {

  SWD.Tree = {
    expand : function(node) {
      // add node to list of those to expand on page load
      if (nodeList) {
        nodeList = nodeList + "," + node.tree.id + ":" + node.index;
      } else {
        nodeList = node.tree.id + ":" + node.index;
      }
      // replace the cookie
      document.cookie = treeCookie + "=" + nodeList;
    },
   
    collapse : function(node) {
      //alert(node.index + " was collapsed");
      // remove node from list
      var nodeIds = [];
      nodeIds = nodeList.split(",");
      nodeList = ""; // reset list of nodes
      var rmNode = node.tree.id + ":" + node.index;
      for (i = 0; i < nodeIds.length; i++) {
        if (rmNode != nodeIds[i]) {
          if (nodeList) {
            nodeList = nodeList + "," + nodeIds[i];
          } else {
            nodeList = nodeIds[i];
          }
        }
      }
      // replace the cookie      
      document.cookie = treeCookie + "=" + nodeList;
    },
    
    expandTrees : function() {
      // tell the trees which nodes to expand
      nodeList = readCookie(treeCookie);
      if (nodeList) {
        updateCookie = 0;
        var nodeIds = nodeList.split(",");
        for (i = 0; i < nodeIds.length; i++) {
          var treeNode = nodeIds[i].split(":");
          if (YAHOO.widget.TreeView.getNode(treeNode[0],treeNode[1])) {
            YAHOO.widget.TreeView.getNode(treeNode[0],treeNode[1]).expand();
          }
        }
        updateCookie = 1;
      }
    }
  }; 

}
/* http://www.quirksmode.org/js/cookies.html */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


