/* Trigger actions for the menu */

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

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

	let menu = document.querySelector('#menu');
	let buttons = document.querySelectorAll('#light-menu li');
	let menus = document.querySelectorAll('#menu > 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);
	}
}

let mouse_trigger = function(event) {
	let menu = document.querySelector('#menu');
	let buttons = document.querySelectorAll('#light-menu li');

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

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

		trigger_menu(active);
	}
}

let keyboard_trigger = function(event) {
	let menu = document.getElementById('menu');
	let buttons = document.querySelectorAll('#light-menu li');

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

document.addEventListener("click", mouse_trigger);
document.addEventListener("keydown", keyboard_trigger);
