Event.observe(window, 'load', function() {
    var isle = $('categorytree'); //first <ol>
    var childs = isle.select('li');

    for (var index = 0, len = childs.length; index < len; ++index) {
	var item = childs[index];

	item.observe('click', treeEntryClicked);
    }
});

function treeEntryClicked(event)
{
    var e = Event.element(event);

    //event must bubble to the top
    if(e.tagName == 'A')
    {
    	return true;
    }
    //we are the event handler, so stop bubbling
    else if(e.tagName == 'LI')
    {
	    Event.stop(event);
    }


    var id = this.firstDescendant().readAttribute('id');
    id = id.substring( id.indexOf('_')+1 );

    //Ist das naechste auf dieser ebene ein OL?
    //Wenn ja, dann ist die Kategorie aufgeklappt
    var childs = this.childElements();

    if(childs.length > 1 && childs[1].nodeName == 'OL')
    {
    	this.removeClassName('treeicon_minus');
	this.addClassName('treeicon_plus');
	childs[1].remove();
    }
    else
    {
	this.addClassName('treeicon_loading');

	new Ajax.Request('/tree.php',
    	{
		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		parameters: {category: id},

		onSuccess: function(transport) {
	    		var json = transport.responseText.evalJSON(true);
	    		var target = $('catlink_'+json.id).parentNode;

	    		target.removeClassName('treeicon_loading');

			var level = -1;
			target.classNames().each(function(name, index) {
				var loc = name.indexOf('level_');
				if(loc != -1)
				{
					level = parseInt(name.substring(loc+6));
					++level;
				}
			});


			if(json.childs.length > 0)
			{
				target.removeClassName('treeicon_plus');
				target.removeClassName('treeicon_arrow');
				target.addClassName('treeicon_minus');

		 		var ol = new Element('ol');
		    		for( var i = 0; i < json.childs.length; ++i)
		    		{
					var el = json.childs[i];

					var treeicon = (el.ccount > 0) ? 'treeicon_plus' : 'treeicon_arrow';
					var isactive = (parseInt(el.is_active) > 0) ? ' cat_is_active' : '';

					var li = new Element('li');
					li.addClassName('categorielisting');
				        li.addClassName('level_' + level);
					li.addClassName(treeicon);
				        li.addClassName(isactive);

					//li.classNames().each(function(name, index) { alert(name); });
					
					var a = new Element('a', {
			    			id: 'catlink_' + el.id,
			    			href: el.link
					});
					a.addClassName(isactive);

					a.update(el.name);
					li.insert(a);
					li.observe('click', treeEntryClicked);

					ol.insert(li);
		    		}

		    		target.insert(ol);
			}
			else
			{
		    		//alert("keine Unterkategorien gefunden!");
			}
		},
		onFailure: function(){ alert('Something went wrong...') }
    	});
    }
}
