Event.observe(window, 'load', function() {
	if ($('tree')) {
		new Ajax.Request('/service/expandNode.php', {
			method: 'get',
			parameters: {id: 0},
			onLoading: function(transport) {
				new Insertion.Bottom($('tree'), '<ul><li class="load"><span class="infos">Chargement...</li></ul>');
			},
			onSuccess: function(transport) {
				$('tree').update(transport.responseText);
				new Insertion.Bottom($('tree'), '<div class="clear">&nbsp;</div>');
				applyEvents('tree');
				if(document.location.hash)
					$(document.location.hash.replace('#', '')).scrollTo();
			}
		});
	}
});

function applyEvents(node) {
	
	// Expand events
	$$('#'+node+' img.expand').each( function(element) {
		Event.observe(element, 'click', function(event) {
			var elmId = element.ancestors()[0];
			new Ajax.Request('/service/expandNode.php', {
				method: 'get',
				parameters: {id: elmId.id.replace('ouv', '')},
				onLoading: function(transport) {
					new Insertion.Bottom(elmId, '<ul><li class="load"><span class="infos">Chargement...</li></ul>');
				},
				onSuccess: function(transport) {
					elmId.update(transport.responseText);
					applyEvents(elmId.id);
				}
			});
		});
		Event.observe(element, 'mouseover', function() {
			element.addClassName('pointer');
		}),
		Event.observe(element, 'mouseout', function() {
			element.removeClassName('pointer');
		});
	});
	
	// Collapse events
	$$('#'+node+' img.collapse').each( function(element) {
		Event.observe(element, 'click', function(event) {
			var elmId = element.ancestors()[0];
			elmId.firstDescendant().remove();
			new Ajax.Request('/service/collapseNode.php', {
				method: 'get',
				parameters: {id: elmId.id.replace('ouv', '')}
			});
			var childs = elmId.getElementsBySelector('ul')
			for (var i=0; i < childs.length; i++) {
				childs[i].remove();
			}
			new Insertion.Top(elmId, '<img src="images/btn_expand.png" alt="Expand" class="expand" />');
			applyEvents(elmId.id);
		});
		Event.observe(element, 'mouseover', function() {
			element.addClassName('pointer');
		}),
		Event.observe(element, 'mouseout', function() {
			element.removeClassName('pointer');
		});
	});
	
	// Manage document tooltip displaying
	$$('#'+node+' .docref img').each( function(element) {
		var tooltip = element.ancestors()[0].select('div.tooltip')[0];
		Event.observe(element, 'mouseover', function() {
			tooltip.show();
		}),
		Event.observe(element, 'mouseout', function() {
			tooltip.hide();
		});
	});
	$$('#'+node+' div.tooltip').each( function(element) {
		element.hide();
		Event.observe(element, 'mouseover', function() {
			element.show();
		}),
		Event.observe(element, 'mouseout', function() {
			element.hide();
		});
	});
}