Ext.namespace("Ext.ux");

Ext.ux.StatefulTreePanelPlugin = function (config){

	return {
		
		init: function(tree){
			this.tree = tree;
			this.height = tree.getSize().height; //For make work: http://extjs.com/forum/showthread.php?p=212359
			if(false !== tree.stateful) {
				tree.expandedNodes = {};
				tree.stateEvents = ['expandnode', 'collapsenode'];
				tree.getState = function() {
					return {expandedNodes:this.expandedNodes};
				};
				tree.on({
			    	scope: this,
					render: this.onRender,
					show: this.restoreState, //For make work: http://extjs.com/forum/showthread.php?p=212359
					beforeexpandnode: this.beforeExpandNode,
					beforecollapsenode: this.beforeCollapseNode
				});										  
				
			}	
		},
		onRender: function(){ //In this event must be restoreState but not not work: http://extjs.com/forum/showthread.php?p=212359
			this.tree.setVisible(false);
			this.tree.setVisible.defer(1, this.tree, [true]);
		},
		restoreState: function() {											 
			for(var id in this.tree.expandedNodes) {
				if(this.tree.expandedNodes.hasOwnProperty(id)) {
					this.tree.expandPath(this.tree.expandedNodes[id]);
				}
			}
			this.tree.setHeight(this.height); //For make work: http://extjs.com/forum/showthread.php?p=212359
		},
		beforeExpandNode:function(n) {
			if(n.id) {
				this.tree.expandedNodes[n.id] = n.getPath();
			}
		},
		beforeCollapseNode:function(n) {
			if(n.id) {
				delete(this.tree.expandedNodes[n.id]);
				n.cascade(function(child) {
					if(child.id) {
						delete(this.tree.expandedNodes[child.id]);
					}
				}, this);
			}
		}
	}
}