
//global variable to allow console inspection of tree:
var blogTree;

//anonymous function wraps the remainder of the logic:
(function() {

    var tt, contextElements = [];
    function treeInit() {
        buildRandomTextNodeTree();
        tt = new YAHOO.widget.Tooltip("tt", { 
                    context: contextElements 
        });
    }
    
    //Function  creates the tree and 
    //builds between 3 and 7 children of the root node:
    function buildRandomTextNodeTree() {
        //instantiate the tree:
        var isOpen=false;
        blogTree = new YAHOO.widget.TreeView("categoriesTreeDiv");
        for( i=0; i<blogTreeDatas.menu.length; i++ ) {
            //set last is open
            if((i+1)==blogTreeDatas.menu.length) {
                isOpen=true;
            } else {
                isOpen=false;
            }
            var tmpNode = new YAHOO.widget.TextNode( blogTreeDatas.menu[i] , blogTree.getRoot(), isOpen );
            // save the element id for Tooltip
            contextElements.push(tmpNode.labelElId);
            buildLargeBranch( tmpNode , blogTreeDatas.menu[i].number );
        }

       // Expand and collapse happen prior to the actual expand/collapse,
       // and can be used to cancel the operation
       blogTree.subscribe("expand", function(node) {
          // return false; // return false to cancel the expand
       });

       blogTree.subscribe("collapse", function(node) {
       });

       // Trees with TextNodes will fire an event for when the label is clicked:
       blogTree.subscribe("labelClick", function(node) {
       });

        //The tree is not created in the DOM until this method is called:
        blogTree.draw();
    }

    //function builds 10 children for the node you pass in:
    function buildLargeBranch( node , number ) {
        if (node.depth < 10) {
            var i=0;
            var tmpNode;
            var itemInfos={};
            eval( "itemInfos = blogTreeDatas.item"+number );
            
            while( typeof itemInfos[i] != "undefined" ) {
                tmpNode = new YAHOO.widget.TextNode( itemInfos[i], node, false );
                contextElements.push(tmpNode.labelElId);
                i++;
            }
        }
    }

    //Add an onDOMReady handler to build the tree when the document is ready
    YAHOO.util.Event.onDOMReady(treeInit);

})();