$(document).ready(function()
	{
		$("body").prepend('<img id="spinner" src="templates/Glassy/img/spinner.gif" style="display:none;" alt="Loading ..." />');
	}
);

$.fn.categoryTree = function(params)
{
	var i = 0;
	return this.each(
		function()
		{
			i++;
			var tree = $(this);
			
			str = '';
			if($.browser.opera)
			{
				str += "<form>";
			}
			str += '<ul class="'+params.treeClass+'">';
			str += '<li>';
			str += '<a href="javascript:void(0)" onclick="getCategoryChildren(\'0\')" class="no"><img style="margin-bottom:3px;height:9px;width:9px" src="templates/Glassy/img/plus.png" id="im_0" /> <img style="margin-bottom:3px;height:12px;width:16px" src="templates/Glassy/img/folder.gif" id="imf_0" /></a>';
			str += '<input type="radio" path=" " title="ROOT" name="categories[]" onclick="treeCallback(this)" class="treeItem_1" value="0" id="labelcat0" />';
			str += '<label for="labelcat0">ROOT</label>';
			str += '<div id="category_0" style="display:none;"></div>'
			str += '</li>';
			str += '</ul>';
			if($.browser.opera)
			{
				str += "</form>";
			}
			tree.html(str);
		}
	);
}

function getCategoryChildren(catid, state)
{
	params = {widget:'radio'}
	var act = $("#action").val();
	var c = "#category_"+catid;

	imsrc = $('#im_' + catid).attr("src");

	// if the node is expanded then collapse
	if(-1!=imsrc.indexOf("minus.png"))
	{
		$('#im_' + catid).attr("src", 'templates/Glassy/img/plus.png');
		$('#imf_' + catid).attr("src", 'templates/Glassy/img/folder.gif');
		$(c).hide();
		
		return;
	}
	else
	{
		var x = $(c).attr("class");
		$('#im_' + catid).attr("src", 'templates/Glassy/img/minus.png');	
		$('#imf_' + catid).attr("src", 'templates/Glassy/img/open_folder.gif');
		
		// if class contains _tree_loaded but not marked as reloadTree then show already loaded
		// otherwise tree must be reloaded (e.g if type of the tree is changed)
		if(x && x.match(/_tree_loaded/))
		{
			$(c).show();
		
			return;
		}
	}

	var pars = 'id='+catid;
	pars += '&widget='+params.widget;
	pars += "&callback=treeCallback";
		
	$(c).before($("#spinner"));
	$("#spinner").show();

	$.get("get-categories.php?"+pars,
		function(data)
		{
			$(c).html(data).show();
			// mark the node as loaded see above code
			$(c).addClass("_tree_loaded");
			$("#spinner").hide();
		});
}
