  
  var treeenable = false; // We need to disable the tree at the beginning then enable it

  /** Recursive function to return a tree */
  function getCommunity(community,communityid)
    {
	if(community.id == communityid)
      {
 	  return community;
      } 
	
	var communities = community.communities;
	for(var i=0;i<communities.length;i++)
      {
	  community = getCommunity(communities[i],communityid); 
	  if(community)
	     {
		 return community;
	     }
      }
	return null;
    }
  
  /** Return the branch of a tree */
  function getBranch(tree,communityid,webroot,data)
    {
	// This is not the fastest way to get the tree but should be good enough
	 var communities = data.communities;
	 var community = null;
	 for(var i=0;i<communities.length;i++)
       {
	   community = getCommunity(communities[i],communityid); 
	   if(community)
	     {
		 break; 
	     }
       }
    
	if(community)
	  {
      // Display the communities
      var coms = community.communities;
      for(var i=0;i<coms.length;i++)
        {
    	var com = coms[i];
        tree.create({ attributes: {id: 'com_'+com.id, num: com.id, title: com.fullname, href: webroot+"community/view/"+com.id}, 
        			data : {title : com.name, attributes : {href: webroot+"community/view/"+com.id}}, state: 'closed'},'#com_'+communityid);
        tree.get_node('#com_'+com.id).removeClass('leaf');
        }
      
      // Display the collections
      var cols = community.collections;
      for(var i=0;i<cols.length;i++)
        {
    	var col = cols[i];
        tree.create({ attributes: {id: 'col_'+col.id, num: col.id, title: col.fullname, href: webroot+"collection/view/"+col.id}, 
        			data : {title : col.name, icon : webroot+"images/file.gif", attributes : {href: webroot+"collection/view/"+col.id}}},
        			'#com_'+communityid);
        }
	  }   
    }

  /** Generate the initial tree*/
  function generateTree(webroot,data,initialtree,nodeselected)
    {
    $("#tree_html").tree({
  	  ui : {
   	    theme_name : "apple"
   	  },
   	  /*plugins : { 
 			cookie : { prefix : "jstree_" }
    		},*/
   	  types : {
 			// all node types inherit the "default" node type
 			"default" : {
 				deletable : false,
  				renameable : false,
  				draggable : false,
  				max_children: -1,
  				max_depth: -1
  			}
    	  },
         data : { 
    		type: "json",
			async : false
    	 },
    	 selected : [nodeselected],
    	 callback : { 
 			// Make sure static is not used once the tree has loaded for the first time
 			onload : function (t) { 
 				t.settings.data.opts.static = false; 
 			},
 			// Take care of refresh calls - n will be false only when the whole tree is refreshed or loaded of the first time
 			beforedata : function (n, t) { 
 				if(n == false) 
 			      {
 				  t.settings.data.opts.static = initialtree; 
 			      }
 			},
 			onselect: function(n) {
 			      if(treeenable) {document.location.href = $(n).attr("href");}
 			    },
 			onopen: function (n, t) { // On open add the new nodes
 			    var num = $(n).attr("num");
 			    if($(n).children().length==1)
 			      {
 			      getBranch(t,num,webroot,data);
 			      }
 			    } 	
              
 		}
      }  
      );
      }
    
    
    /** Get just the recursive branch */
    function getBranchChildren(webroot,resource,parents)
      {
      var children = new Array();
      
      // List the communities
      if(resource.communities)
        {
	    var communities = resource.communities;
	    for(var i=0;i<communities.length;i++)
	      {
		  var community = communities[i];
			
		  var node = new Object();
		  node.data = new Object();
	      node.data.title = community.name;
	      node.data.attributes = new Object();
	      node.data.attributes.href= webroot+"community/view/"+community.id;
	    	
		  if(parents && parents[0]==community.id)
		    {
		    parents.shift();
		    node.state = 'open';
		    node.children = getBranchChildren(webroot,community,parents);
		    }
		  else
		    {	
		    node.state = 'closed';
		    }
		  var attribute = new Object();
		  attribute.id = "com_"+community.id;
		  attribute.num = community.id;
		  attribute.href = webroot+"community/view/"+community.id;
		  attribute.title = community.fullname;
		  node.attributes = attribute;
		  children.push(node);
		  }
        }
      
      // List the collections
      var collections = resource.collections;
      if(collections)
	    { 
	    for(var i=0;i<collections.length;i++)
	      {
		  var collection = collections[i];
			
		  var node = new Object();
		  var data = new Object();
		  data.title = collection.name;
		  data.icon =  webroot+"images/file.gif";
		  data.attributes = new Object();
	      data.attributes.href= webroot+"collection/view/"+collection.id;
		  node.data = data;
		  	
		  var attribute = new Object();
		  attribute.id = "col_"+collection.id;
		  attribute.num = collection.id;
		  attribute.href = webroot+"collection/view/"+collection.id;
		  attribute.title = collection.fullname;
		  node.attributes = attribute;
		  children.push(node);
		  }
	    }
	  return children;
      }
    
    /** Generate the initial tree*/
    function getInitialTree(webroot,data,parents,resourceid,resourcetype)
      {
      var initTree = new Array();	
      if(!data)
        {
    	return initTree;  
        }
    	
      var communities = data.communities;
      if(!communities)
        {
    	return initTree;  
        }
      
      for(var i=0;i<communities.length;i++)
      	{
    	var community = communities[i];
  	
    	var node = new Object();
    	node.data = new Object();
    	node.data.title = community.name;
    	node.data.attributes = new Object();
    	node.data.attributes.href= webroot+"community/view/"+community.id;
    	
    	if(parents && parents[0]==community.id)
    	  {
    	  parents.shift();		
    	  node.state = 'open';
    	  node.children = getBranchChildren(webroot,community,parents);
       	  }
    	else
    	  {	
    	  node.state = 'closed';
    	  }
    	var attribute = new Object();
    	attribute.id = "com_"+community.id;
    	attribute.num = community.id;
    	attribute.href = webroot+"community/view/"+community.id;
    	attribute.title = community.fullname;
      	node.attributes = attribute;
    	initTree.push(node);
      	}
      return initTree;	
      }
    
    
    /** When the page loads */
    $(document).ready(function()
      {
      var webroot = $("#full_url").html(); // should be renamed webroot	
      
      if($("#nonavigationtree").length)
        {
    	return;  
        }
      
      $('#tree_html').html('<img src="'+webroot+'images/loading.gif"/>');
      var resourceid = $('#resourceid').val();
      var resourcetype  = $('#resourcetype').val();
      
      $.ajax({url: webroot+"browse/get_tree/", dataType: 'json', success: function(data) {
    	
      var parents = $('#resourceparents').val();
      var parents = eval(parents);
    	  
      var initialtree = getInitialTree(webroot,data,parents,resourceid,resourcetype);
    	  
      var idname = '#col_'+resourceid;
      // If it's an item the resourceid is the collection
      if(resourcetype == 2)
        { 
        resourceid = parents[parents.length-1];
        idname = '#col_'+resourceid;
        }
      else if(resourcetype == 4)
        {
    	idname = '#com_'+resourceid;
    	}
      generateTree(webroot,data,initialtree,idname);
      treeenable = true;
      }});
    });

