function ajax_tree(id,varname)
{
	this.main_id = id;
	this.varname = varname;
}

ajax_tree.prototype = {
	url : '',
	items : new Array(),
	
	initObject : function()
	{
		var elem,ar,item;
		this.main = $('#'+this.main_id);
		ar = this.main.children('li.vetka');
		for(var i=0,len=ar.length;i<len;i++)
		{
			elem = ar[i];
			item =  new ajax_tree_item(elem.id);
			item.parent = this;
			item.tree = this;
			item.initObject();
			this.items[this.items.length] = item;
		}
	},
	
	loadData : function(id)
	{
		var data = 'id='+escape(id);
		var async = true;
		
		$.ajax({
			url : this.url,
			data : data,
			dataType : 'json',
			type : 'get',
			success : this.setData,
			error : this.ajaxError
		});
	},
	
	setData : function(res)
	{		
		try
		{
			elem = $('#'+res.id);
			elem[0].obj.setData(res.html);
		}
		catch (e) { }
	},
	
	ajaxError : function(xml,er,oEr)
	{
		alert('Ajax Error: '+er);
	}
}

function ajax_sub_tree(elem,tree)
{
	this.elem = elem;
	this.elem.obj = this;
	this.tree = tree;
	this.items = new Array()
	this.opened = false;
}

ajax_sub_tree.prototype = {
	animSpeed : 200,
	
	initObject : function()
	{
		var ar,e,item;
		ar = this.elem.children('li.vetka');
		for(var i=0,len=ar.length;i<len;i++)
		{
			item =  new ajax_tree_item(ar[i].id);
			item.parent = this;
			item.tree = this.tree;
			item.initObject();
			this.items[this.items.length] = item;
		}
	},
	
	hide : function()
	{
		if(this.opened)
		{
			this.opened = false;
			this.elem.slideUp(this.animSpeed,function () {$(this).hide(); });
		}
	},
	
	show : function()
	{
		if(!this.opened)
		{
			this.opened = true;
			this.elem.slideDown(this.animSpeed,function () {$(this).show(); });
		}
	}	
}

function ajax_tree_item(id)
{
	this.id = id;
	this.elem = $('#'+id);
	this.elem[0].obj = this;
}

ajax_tree_item.prototype = {
	opened : false,
	hasChild : false,
	subTree : null,
	parent : null,
	span : null,
	tree : null,
	dataLoad : false,
	
	initObject : function()
	{
		this.span = this.elem.children('span'); 
		this.span.click(function(){this.parentNode.obj.toogleSate()});
	},
	
	toogleSate : function()
	{
		if(this.opened) this.close();
		else this.open();
	},
	
	open : function()
	{
		if(!this.dataLoad) 
		{
			this.tree.loadData(this.id);
			this.span.addClass('load');
		}
		
		this.span.addClass('open');
		if(this.subTree != null) 
		{
			this.subTree.show();
		}
		this.opened = true;
	},
	
	close : function()
	{
		if(this.subTree != null) this.subTree.hide();
		this.span.removeClass('open');
		this.opened = false;
	},
	
	setData : function(html)
	{
		this.dataLoad = true;
		this.span.removeClass('load');
		this.elem.append(html);
		this.createSubtree();
		this.subTree.show();
	},
	
	createSubtree : function()
	{
		var e,m;
		e = this.elem.children('ul');
		if(e.length > 0)
		{
			m = new ajax_sub_tree(e,this.tree);
			m.initObject();
			this.hasChild = true;
			this.subTree = m;
			this.subTree.parent = this;
		}
	}
}
