var maintree_node=$.ajax({
	  url: "js_wrapper.php?mod=maintree",
	  async: false
	 }).responseText;

var Tree = Ext.tree;
	
var tree = new Tree.TreePanel({
	id:'domains-tree',
	autoScroll:true,
	animate:false,
	region:'west',
	title:'Главное меню',
	split:true,
	width: 230,
	minSize: 175,
	maxSize: 400,
	collapsible: true,
	margins:'5 0 5 0',
	rootVisible: false,
	loader: new Tree.TreeLoader({
		dataUrl: 'wrapper.php?mod=maintree&act=get'
	}),	
	stateEvents : ['collapsenode', 'expandnode'],
    stateId : 'tree-panel-state-id',
    stateful : true,
    getState : function () {
        var nodes = [];
        this.getRootNode().eachChild(function (child) {
            var storeTreeState = function (node, expandedNodes) {
                if(node.isExpanded() && node.childNodes.length > 0) {
                    expandedNodes.push(node.getPath());
                    node.eachChild(function (child) {
                        storeTreeState(child, expandedNodes);
                    });
                }
            };
            storeTreeState(child, nodes);
        });
        return {
            expandedNodes : nodes
        };
    },
	onContextClick: function(node){
			var items = null;
			var id = Ext.decode(node.id);
			var parent_id = Ext.decode(node.parentNode.id);
			
			if (items !== null) {
				this.menu = new Ext.menu.Menu({
					id: 'tree-ctx',
					items: items
				});
				
				this.menu.show(node.ui.getAnchor());
			}
	}
	
});



var filter = new Ext.tree.TreeFilter(tree, {
	clearBlank: true,
	autoClear: true
});
var hiddenPkgs = [];
	
function filterTree(e){
	var text = e.target.value;
	Ext.each(hiddenPkgs, function(n){
		n.ui.show();
	});
	if (!text) {
		filter.clear();
		return;
	}
	tree.root.expand(true);
	
	var re = new RegExp(Ext.escapeRe(text), 'i');
	filter.filterBy(function(n){
		return !n.isLeaf() || re.test(n.text);
	});
	
	hiddenPkgs = [];
	tree.root.cascade(function(n){
	});
} 

 tree.on('contextmenu',tree.onContextClick,tree);

var sm = tree.getSelectionModel();

sm.on('selectionchange', function(sm, node){

	sm.unselect(node);	
	
	if (node&&node.id!="{object: 'domains'}") {
		if(node.id){
			var id = Ext.decode(node.id);
		}
		if(node.parentNode.id){
			var id_parent = Ext.decode(node.parentNode.id);
		}
		eval(maintree_node);
				
	}
});

var root = new Tree.AsyncTreeNode({
	text: 'Базы',
	draggable:false,
	id:'domains-root'
});

tree.setRootNode(root);

tree.getLoader().on('load', function () {
	var cookie = Ext.state.Manager.get('tree-panel-state-id');
	if(cookie){
		var nodes = cookie.expandedNodes;
		for(var i = 0; i < nodes.length; i++) {
			if(typeof nodes[i] != 'undefined') {
				tree.expandPath(nodes[i]);
			}
		}
	}
});