var fix_utf8 = function (string) {
	var _string = string;
	
	_string = _string.replace(/%E0/g, String.fromCharCode(224)); // à
	_string = _string.replace(/%E4/g, String.fromCharCode(228)); // ä
	_string = _string.replace(/%E8/g, String.fromCharCode(232)); // è
	_string = _string.replace(/%E9/g, String.fromCharCode(233)); // é
	_string = _string.replace(/%F6/g, String.fromCharCode(246)); // ö
	_string = _string.replace(/%FC/g, String.fromCharCode(252)); // ü
	
	_string = _string.replace(/%C3%A0/g, String.fromCharCode(224)); // à
	_string = _string.replace(/%C3%A4/g, String.fromCharCode(228)); // ä
	_string = _string.replace(/%C3%A8/g, String.fromCharCode(232)); // è
	_string = _string.replace(/%C3%A9/g, String.fromCharCode(233)); // é
	_string = _string.replace(/%C3%B6/g, String.fromCharCode(246)); // ö
	_string = _string.replace(/%C3%BC/g, String.fromCharCode(252)); // ü
	
	return _string || string;
}

document.observe('dom:loaded', function () {
	//console.log('menu.js initialised');
	if ($$('.leftmenu').first()) {
		//console.log('.leftmenu exists');
		var areas = $$('.leftmenu').first(),
			menu = areas.down('ul'),
			items = menu.select('li > a'),
			subleftmenu = menu.select('ul > li > ul');
		
		//subleftmenu.invoke('remove');
		var leftmenu = menu.select('ul');
		var leftmenuchild = menu.select('ul > li > ul');
		var leftmenuchildchild = menu.select('ul > li > ul > ul > li');

		//console.log('leftmenu', leftmenu);
	
		leftmenu.invoke('wrap', 'div', { className: 'leftmenu' }).invoke('hide');
		
		if (typeof Vx === 'undefined') {
			var location_regex = /([^\/]+?)\/([^\/]+?)\.([A-Za-z0-9]+?)(?:#[a-z0-9]+?)?$/;
			var window_location, folder_name, file_name;
			
			fix_utf8(window.location.href).gsub(location_regex, function (match) {
				window_location = match[0];
				folder_name = match[1];
				file_name = match[2];
			});
			
			var active_leftmenu = items.inject($A(), function (accumulator, element) {
				element.readAttribute('href').gsub(location_regex, function (match) {
					
					if (window_location === match[0]) {
						element.addClassName('selected');
						accumulator.push(element.next('div.leftmenu') || element.up('div.leftmenu') || element);
					} else {
						if (match[2] === folder_name && match[1] !== folder_name) {
							if (element.up('div.leftmenu')) {
								element.addClassName('selected');
								accumulator.push(element.next('div.leftmenu') || element.up('div.leftmenu') || element);
							}
							accumulator.push(element.up('div.leftmenu') || element);							
						}
					}
				});
				
				return $A(accumulator);
			});
						
			active_leftmenu.invoke('show');
		}
	}
});