/* Trigger actions for the menu */

/* Initialization */
var b = document.getElementById('light-menu').getElementsByTagName('a')
for(var i = 1; i < b.length; i++) {
	b[i].setAttribute('onfocus', "this.setAttribute('f', 'true');");
	b[i].setAttribute('onblur', "this.setAttribute('f', 'false');");
}

var trigger_menu = function(active) {
	var display = function(element) {
		element.classList.add('opened');
	}
	var hide = function(element) {
		element.classList.remove('opened');
	}

	var menu = document.getElementById('menu');
	var buttons = document.getElementById('light-menu').getElementsByTagName('li');
	var menus = document.getElementById('menu').getElementsByTagName('div');

	if(active == -1 || buttons[active].classList.contains('opened')) {
		hide(menu);
		for(i = 0; i < buttons.length; i++) {
			hide(buttons[i]);
		}
	}
	else {
		for(i = 0; i < buttons.length; i++) {
			if(i != active) {
				hide(buttons[i]);
				hide(menus[i]);
			}
		}
		display(buttons[active]);
		display(menus[active]);
		display(menu);
	}
}

var mouse_trigger = function(event) {
	var menu = document.getElementById('menu');
	var buttons = document.getElementById('light-menu').getElementsByTagName('li');

	if(!menu.contains(event.target)) {
		var active = -1;

		for(i = 0; i < buttons.length; i++) {
			if(buttons[i].contains(event.target))
				active = i;
			buttons[i].getElementsByTagName('a')[0].blur();
		}

		trigger_menu(active);
	}
}

var keyboard_trigger = function(event) {
	var menu = document.getElementById('menu');
	var buttons = document.getElementById('light-menu').getElementsByTagName('li');

	if(event.keyCode == 13) {
		for(var i = 0; i < buttons.length; i++) {
			if(buttons[i].getElementsByTagName('a')[0].getAttribute('f') == 'true') {
				trigger_menu(i);
			}
		}
	}
}

document.onclick = mouse_trigger;
document.onkeypress = keyboard_trigger;
