var objLocalTree = null;

function jsTree() {
    this.root = null;      
    this.nodes = new Array;       
    objLocalTree = this;
}

jsTree.prototype.createRoot = function(strName, strVal) {    
    this.root = new jsTreeNode(strName, strVal);    
    this.root.id = "root";   
    this.nodes["root"] = this.root;       
    this.root.expanded = true;    
    return this.root;
}

function jsTreeNode(strName, strVal) {    
    this.nodename = strName;          
    this.nodeval = strVal;            
    this.childNodes = new Array;    
}

jsTreeNode.prototype.addChild = function (strName, strVal) {    
    var objNode = new jsTreeNode(strName, strVal);   
    objNode.id = this.id + "_" + this.childNodes.length;    
    objNode.indent = this.indent + 1;    
    this.childNodes[this.childNodes.length] = objNode;    
    objLocalTree.nodes[objNode.id] = objNode;    
    return objNode;
}

jsTree.prototype.popCat2 = function(list,field,str,index) {      

    if(list) {     
	    while (list.options.length > 0) {                   
	       var eachGroup = list.firstChild;       
	       if(eachGroup != null && 'OPTGROUP' == eachGroup.tagName) {           
	           list.removeChild(eachGroup);  
	       } else {
	         list.remove(0);
	       }
	    }
	    list.options.length = 0; 
	}    
    
    this.root.findNode(list,field,str,0,3);   
}

function fillValues(list,field,node) {
   var hasOptGroups = false;
   var optGroup = null;

   for (var i=0; i < node.childNodes.length; i++) {          	
        nodeName = node.childNodes[i].nodename;
        nodeValue = node.childNodes[i].nodeval;       

        if(list != null && nodeName.indexOf("head")!=-1) {
            hasOptGroups = true;
            optGroup = document.createElement('optgroup');
            optGroup.label = nodeValue;
            list.appendChild(optGroup);            
        } else {
            if(nodeName.indexOf("cdata")!=-1) { 
            	if(field.value == "") field.value = nodeValue;
            	return;
            } else if(list != null) {   
	            var objOption = new Option(nodeValue,nodeName);
	            if(hasOptGroups)
	                optGroup.appendChild(objOption);
	            else            
	                list.options[list.options.length]=objOption;
	        }
        }            
        fillValues(list,field, node.childNodes[i]);        
    }    
}

jsTreeNode.prototype.findNode = function (list,field,nodeName,actDepth,maxDepth) {    
    if(this.nodename == nodeName) {                
        fillValues(list,field,this);
        return this;
    }
    
    if(actDepth < maxDepth){
        actDepth = actDepth + 1;
        for (var i=0; i < this.childNodes.length; i++) {
            if(this.childNodes[i].findNode(list,field,nodeName,actDepth,maxDepth) != null) {
                return this;   
            }
        }
    }
    return null;
}