// Register Service Worker
if ("serviceWorker" in navigator) {
	navigator.serviceWorker.register(
		new URL("service-worker.js", import.meta.url), { type: "module" }
	).then( (registration) => {
		console.log('ServiceWorker registration successful with scope: ', registration.scope);
	}, (err) => {
		console.log('ServiceWorker registration failed: ', err);
	});
} else {
	console.error("Service workers are not supported.");
}


/*
 * import libraries
 */

const bs = require("../../node_modules/bootstrap/js/dist/modal.js");
const $ = require("../../node_modules/jquery/dist/jquery.js");


/*
 *	constants definitions
 */

const DAMAGE_PENALTY = [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4];
const DAMAGE_NIVEAU = ["", "L", "M", "S", "D"];

const COMBATANT_TABLE_ROW = [
'<tr class="combatant-row" data-true-ini="" data-augmented-ui="tl-scoop bl-clip-y tr-clip-y br-scoop">\n', //TODO: add data-damage-* attributes with initial damage levels
	'<td class="combatant-name" title="Combatant\'s name" data-bs-toggle="modal" data-bs-target="#combatant-modal" data-augmented-ui="tl-scoop bl-clip-y both"></td>\n',
	'<td class="combatant-ini" title="Effective initiative (w/ wound penalties)" data-bs-toggle="modal" data-bs-target="#combatant-modal" data-augmented-ui="both"></td>\n',
	'<td class="combatant-dice-and-rea" title="Iniative dice and reaction" data-bs-toggle="modal" data-bs-target="#combatant-modal" data-augmented-ui="both"><span class="combatant-dice"></span>D+<span class="combatant-rea"></span></td>\n',
	'<td class="combatant-actions" data-augmented-ui="tr-clip-y br-scoop both">\n',
		'<button type="button" class="sr2-button act-button" title="Act and reduce ini by 10"><svg class="icon" viewBox="0 0 512 512"><path d="M 0 272 h 96 v 64 h -96 Z" /><path d="M 160 64 h 64 v 384 h -64 v -296 l -64 64 l -40 -40 Z" /><path d="M 352 64 h 96 l 64 64 v 256 l -64 64 h -96 l -64 -64 v -256 l 64 -64 l 32 64 h 32 l 32 32 v 192 l -32 32 h -32 l -32 -32 v -192 l 32 -32" fill-rule="evenodd" /></svg></button>\n',
		'<div class="damage-dropdown">\n',
			'<button type="button" class="sr2-button damage-button" title="Take damage"><svg class="icon" viewBox="0 0 512 512"><path d="M 0 288 L 144 224 L 64 32 L 224 128 L 272 0 L 336 144 L 480 96 L 400 224 L 512 304 L 384 352 L 432 512 L 272 416 L 128 512 L 160 352 L 0 288 L 166 267 L 222 290 L 211 346 L 262 312 L 318 346 L 301 290 L 346 273 L 306 245 L 334 200 L 284 217 L 262 166 L 245 211 L 189 178 L 217 245 L 166 267" fill-rule="evenodd" /></svg></button>\n',
		'</div>\n',
		'<div class="actions-dropdown">\n',
			'<button type="button" class="sr2-button actions-button" title="More actions"><svg class="icon" viewBox="0 0 512 512"><polygon points="32 32 480 32 256 480" /></svg></button>\n',
			'<div class="actions-menu" data-augmented-ui="tl-scoop bl-clip-y tr-clip-y br-scoop both">\n',
				'<button type="button" class="sr2-button edit-button" title="Edit combatant" data-bs-toggle="modal" data-bs-target="#combatant-modal" tabindex="-1"><svg class="icon" viewBox="0 0 512 512"><polygon points="0 512 0 352 224 128 384 288 160 512" /><polygon points="352 0 512 160 416 256 256 96" /></svg></button>\n',
				'<button type="button" class="sr2-button clone-button" title="Clone combatant" data-bs-toggle="modal" data-bs-target="#combatant-modal" tabindex="-1"><svg class="icon" viewBox="0 0 512 512"><rect x="0" y="0" width="512" height="128" /><rect x="0" y="384" width="512" height="128" /><polygon points="128 192 384 192 256 320" />/svg></button>\n',
				'<button type="button" class="sr2-button remove-button" title="Remove combatant" data-bs-toggle="modal" data-bs-target="#confirm-modal" tabindex="-1"><svg class="icon" viewBox="0 0 512 512"><polygon points="96 0 416 0 416 64 480 64 480 128 32 128 32 64 96 64" /><path d="M 64 512 H 448 V 160 H 64 V 512 L 128 480 V 192 H 192 V 480 H 224 V 192 H 288 V 480 H 320 V 192 H 384 V 480 H 128" fill-rule="evenodd" /></svg></button>\n',
			'</div>\n',
		'</div>\n',
	'</td>\n',
'</tr>'].join("");

const DAMAGE_MONITOR_HTML = [
'<div class="damage-monitor" data-augmented-ui="tl-scoop bl-clip-y tr-clip-y br-scoop both">\n',
	'<table>\n',
		'<tr><td><button type="button" class="damage-stun active" title="Light stun damage" tabindex="-1">L</button></td><td><button type="button" class="damage-physical active" title="Light physical damage" tabindex="-1">L</button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" tabindex="-1"></button></td><td><button type="button" class="damage-physical active" tabindex="-1"></button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" title="Medium stun damage" tabindex="-1">M</button></td><td><button type="button" class="damage-physical active" title="Medium physical damage" tabindex="-1">M</button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" tabindex="-1"></button></td><td><button type="button" class="damage-physical active" tabindex="-1"></button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" tabindex="-1"></button></td><td><button type="button" class="damage-physical active" tabindex="-1"></button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" title="Severe stun damage" tabindex="-1">S</button></td><td><button type="button" class="damage-physical active" title="Severe physical damage" tabindex="-1">S</button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" tabindex="-1"></button></td><td><button type="button" class="damage-physical active" tabindex="-1"></button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" tabindex="-1"></button></td><td><button type="button" class="damage-physical active" tabindex="-1"></button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" tabindex="-1"></button></td><td><button type="button" class="damage-physical active" tabindex="-1"></button></td></tr>\n',
		'<tr><td><button type="button" class="damage-stun active" title="K.O." tabindex="-1"><img src="zzz.png" height="16" /></button></td><td><button type="button" class="damage-physical active" title="dead" tabindex="-1"	><img src="cross.png" height="16"/></button></td></tr>\n',
	'</table>\n',
'</div>'].join("");

const STUN_BADGE_HTML = '<sup><span class="badge bg-warning position-absolute translate-middle stun-badge" title="Stun damage niveau"></span></sup>';
const PHYSICAL_BADGE_HTML = '<sub><span class="badge bg-danger position-absolute translate-middle physical-badge" title="Physical damage niveau"></span></sub>';


/*
 *	helper functions
 */

// roll for initiative with the given reaction and number of ini dice  
function rollForInitiative(dice, rea) {
	let diceRolls = Array.from({ length: parseInt(dice) }, () => Math.ceil(Math.random() * 6));
	return diceRolls.reduce((a, b) => a + b, 0) + parseInt(rea);
}

// figure out whose action comes first out of two combatants a and b
function whoGoesFirst(a, b) {
	// check for K.O./death
	let tmpA = $(a).hasClass("ko-or-dead") ? -1 : parseInt($(a).find(".combatant-ini").text()) || 0;
	let tmpB = $(b).hasClass("ko-or-dead") ? -1 : parseInt($(b).find(".combatant-ini").text()) || 0;
	// compare ini
	let compIni = tmpB - tmpA;
	if (compIni != 0) {
		return compIni;
	}
	// tie; compare reaction
	else {
		if ($(a).find(".combatant-rea").text() == "" || $(b).find(".combatant-rea").text() == "") {
			return 0;
		} else {
			return parseInt($(b).find(".combatant-rea").text()) - parseInt($(a).find(".combatant-rea").text());
		}
	}
}

// compute a combatant's effective ini value (modified by wound penalties)
function getEffectiveIni(tr) {
	// return -1 if combatant is K.O. or dead
	if ($(tr).hasClass("ko-or-dead")) {
		return -1;
	}
	// otherwise compute effective ini (true ini minus wound penalties)
	let effectiveIni = parseInt($(tr).attr("data-true-ini")) - DAMAGE_PENALTY[parseInt($(tr).attr("data-damage-stun")) || 0] - DAMAGE_PENALTY[parseInt($(tr).attr("data-damage-physical")) || 0];
	return Math.max(effectiveIni, 0);
}

// add test combatant for testing purposes (duh)
function addTestCombatant() {
	// Eclipse
	$("#add-combatant-button").click();
	$("#combatant-modal-name").val("Eclipse");
	$("#combatant-modal-dice").val(3);
	$("#combatant-modal-rea").val(6);
	//	$("#combatant-modal-ini").val(12);
	addCombatant();
//	setTimeout( () => $("#combatant-modal-add-ok-button").click(), 500);
}


/*
 *	Event handler functions
 */

// click handler for act buttons; reduces ini by 10
function handleActButtonClick(e) {
	// reduce ini by 10 but not lower than 0
	let ini = Math.max(parseInt($(e.target).parents(".combatant-row").attr("data-true-ini")) - 10, 0);
	// set new ini value
	$(e.target).parents(".combatant-row").attr("data-true-ini", ini);
	// resort table
	sortTable();
}

// click handler for add buttons
function handleAddButtonClick(e) {
	// restyle modal
	$("#combatant-modal .modal-title").text("Add Combatant");
	$("#combatant-modal-add-ok-button, #combatant-modal-add-apply-button").removeClass("d-none");
	$("#combatant-modal-edit-ok-button").addClass("d-none");
	// set default values
	$("#combatant-modal-name").val("Goon 1");
	$("#combatant-modal-dice").val("2");
	$("#combatant-modal-rea").val("7");
	// set damage sliders to zero
	$("#combatant-modal-stun, #combatant-modal-physical").val("0");
	// add handler for enter key
	$("#combatant-modal input[id*='combatant-modal']").off("keydown");
	$("#combatant-modal input[id*='combatant-modal']").on("keydown", (e) =>	{ if (e.which == 13 || e.which == 10) { addCombatant(e); } });
}

// click handler for clone buttons -> like handleAddButtonClick but with a pre-filled modal
function handleCloneButtonClick(e) {
	// find current table row
	let $tr = $(e.target).parents(".combatant-row");
	// hide actions menu
	$tr.find(".actions-menu").removeClass("seen");	
	// restyle modal
	$("#combatant-modal .modal-title").text("Clone Combatant");
	$("#combatant-modal-add-ok-button, #combatant-modal-add-apply-button").removeClass("d-none");
	$("#combatant-modal-edit-ok-button").addClass("d-none");
	// populate modal with values from row
	$("#combatant-modal-name").val($tr.find(".combatant-name").text());
	$("#combatant-modal-dice").val($tr.find(".combatant-dice").attr("data-combatant-dice"));
	$("#combatant-modal-rea").val($tr.find(".combatant-rea").attr("data-combatant-rea"));
	$("#combatant-modal-ini").val($tr.attr("data-true-ini"));
	$("#combatant-modal-stun").val($tr.attr("data-damage-stun") || "0");
	$("#combatant-modal-physical").val($tr.attr("data-damage-physical") || "0");
	// add handler for enter key
	$("#combatant-modal input[id*='combatant-modal']").off("keydown");
	$("#combatant-modal input[id*='combatant-modal']").on("keydown", (e) => { if (e.which == 13 || e.which == 10) { addCombatant(e); } });
}

// click handler for damage buttons; basically toggles visibility of table.damage-monitor
function handleDamageButtonClick(e) {
	// get visibility status at click time
	let seenAtClick = $(e.target).parents(".damage-dropdown").find(".damage-monitor").hasClass("seen");
	// hide all damage monitors and actions menus
	$(".damage-monitor.seen, .actions-menu.seen").removeClass("seen").find("button").attr("tabindex", "-1");
	// if targeted dm was hidden before, show it now
	if (! seenAtClick) {
		$(e.target).parents(".damage-dropdown").find(".damage-monitor").addClass("seen").find("button").attr("tabindex", "0");
	}
	return false;
}

// click handler for edit buttons
function handleEditButtonClick(e) {
	// find current table row
	let $tr = $(e.target).parents(".combatant-row");
	// restyle modal
	$("#combatant-modal .modal-title").text("Edit Combatant");
	$("#combatant-modal-edit-ok-button").removeClass("d-none");
	$("#combatant-modal-add-ok-button, #combatant-modal-add-apply-button").addClass("d-none");
	// populate modal with values from row
	$("#combatant-modal-name").val($tr.find(".combatant-name").text());
	$("#combatant-modal-dice").val($tr.find(".combatant-dice").attr("data-combatant-dice"));
	$("#combatant-modal-rea").val($tr.find(".combatant-rea").attr("data-combatant-rea"));
	$("#combatant-modal-ini").val($tr.attr("data-true-ini"));
	$("#combatant-modal-stun").val($tr.attr("data-damage-stun") || "0");
	$("#combatant-modal-physical").val($tr.attr("data-damage-physical") || "0");
	// mark which row is being edited
	$("#combatant-modal").data("row", $(".combatant-row").index($tr)); // here it's okay to use the jQuery data() function (which is not the same as using a data attribute) b/c this value is used only in this script and not via HTML or CSS
	// add handler for enter key
	$("#combatant-modal input[id*='combatant-modal']").off("keydown");
	$("#combatant-modal input[id*='combatant-modal']").on("keydown", (e) => { if (e.which == 13 || e.which == 10) {	editCombatant(e); }	});
}

// click handler for the more-actions menus
function handleMoreActionsButtonClick(e) {
	// get visibility status at click time
	let seenAtClick = $(e.target).parents(".actions-dropdown").find(".actions-menu").hasClass("seen");

	// hide all damage monitors
	$(".actions-menu.seen, .damage-monitor.seen").removeClass("seen").find("button").attr("tabindex", "-1");
	// if targeted dm was seen before, show it now
	if (! seenAtClick) {
		$(e.target).parents(".actions-dropdown").find(".actions-menu").addClass("seen").find("button").attr("tabindex", "0");
	}

	return false;
}

function handleNewRoundButton(e) {
	// restyle modal
	$("#confirm-modal .modal-title").text("Start new Round");
	$("#confirm-modal-new-round-ok-button").removeClass("d-none");
	$("#confirm-modal-remove-combatant-ok-button").addClass("d-none");
}

// click handler for remove buttons
function handleRemoveButtonClick(e) {
	// restyle modal
	$("#confirm-modal .modal-title").text("Remove Combatant");
	$("#confirm-modal-remove-combatant-ok-button").removeClass("d-none");
	$("#confirm-modal-new-round-ok-button").addClass("d-none");
	// mark which row is being removed
	$("#confirm-modal").data("row", $(".combatant-row").index($(e.target).parents(".combatant-row"))); // here it's okay to use .data() b/c HTML/CSS does not care about this value
}


/*
 *	Main functions
 */

// add new combatant 
function addCombatant(e) {
//	e.preventDefault();
	// validate form
	if (!validateCombatant()) {
		return false;
	}
	// roll for initiative if necessary
	let ini = $("#combatant-modal-ini").val().trim();
	ini = (ini != "") ? ini : rollForInitiative($("#combatant-modal-dice").val(), $("#combatant-modal-rea").val());
	// construct jQuery object for table row
	let $tr = $($.parseHTML(COMBATANT_TABLE_ROW));
	$tr.find(".damage-dropdown").append($.parseHTML(DAMAGE_MONITOR_HTML));
	// populate table row with values from modal 
	$tr.attr("data-true-ini", ini);
	$tr.find(".combatant-name").text($("#combatant-modal-name").val().trim());
	$tr.find(".combatant-dice").attr("data-combatant-dice", $("#combatant-modal-dice").val().trim());
	$tr.find(".combatant-rea").attr("data-combatant-rea", $("#combatant-modal-rea").val().trim());
	// retrieve initial damage levels 
	$tr.attr("data-damage-stun", $("#combatant-modal-stun").val() || "0");
	$tr.find(".damage-stun").addClass("active").slice(0, parseInt($tr.attr("data-damage-stun")) || 0).removeClass("active");
	$tr.attr("data-damage-physical", $("#combatant-modal-physical").val() || "0");
	$tr.find(".damage-physical").addClass("active").slice(0, parseInt($tr.attr("data-damage-physical")) || 0).removeClass("active");
	// add event handlers  
	$tr.find("button.act-button").on("click", handleActButtonClick);
	$tr.find("button.damage-button").on("click", handleDamageButtonClick);
	$tr.find("button.actions-button").on("click", handleMoreActionsButtonClick);
	$tr.find("button.edit-button, .combatant-name, .combatant-ini, .combatant-dice-and-rea").on("click", handleEditButtonClick);
	$tr.find("button.clone-button").on("click", handleCloneButtonClick);
	$tr.find("button.remove-button").on("click", handleRemoveButtonClick);
	// add event handler to damage monitor
	$tr.find(".damage-stun, .damage-physical").on("click", applyDamage);
	// append row to table and sort
	$(".combatants-table").append($tr);
	sortTable();
}

// apply damage to combatant
function applyDamage(e) {
	let $btn = $(e.target).is("button") ? $(e.target) : $(e.target).parent();
	// retrieve new damage level and type from button position and "damage-[type]" class
	let damageLevel = $btn.parent().parent().index();
	if ( $btn.hasClass("active") ) {
		damageLevel += 1;
	}
	let damageType = $btn.attr("class").split(" ").filter(cls => cls.substr(0, 7) == "damage-" ? cls : false).toString().substr(7);
console.log("damageType is", damageType);
	// add damage level to table row as as data attribute
	$btn.parents("tr.combatant-row").attr("data-damage-" + damageType, damageLevel);
	// select/unselect damage buttons above/below
	$btn.toggleClass("active");
	$btn.parent().parent().prevAll().find("button.damage-" + damageType).removeClass("active");
	$btn.parent().parent().nextAll().find("button.damage-" + damageType + ":not(.active)").addClass("active");
	sortTable();
}

// edit combatant
function editCombatant(e) {
console.log("editing combatant …")
	//	e.preventDefault();
	// validate form
	if (!validateCombatant()) {
		return false;
	}
	// get values
	let name = $("#combatant-modal-name").val().trim();
	let ini = $("#combatant-modal-ini").val().trim();
	let dice = $("#combatant-modal-dice").val().trim();
	let rea = $("#combatant-modal-rea").val().trim();
	// roll for initiative if ini is empty
	ini = (ini != "") ? ini : rollForInitiative(dice, rea);
	// get correct row
	let index = parseInt($("#combatant-modal").data("row"));
console.log("row index is", index);
	let $tr = $("tr.combatant-row").eq(index);
console.log("row is", $tr);	
	// set new values
	$tr.attr("data-true-ini", ini);
	$tr.find(".combatant-name").text(name);
	$tr.find(".combatant-dice").attr("data-combatant-dice", dice);
	$tr.find(".combatant-rea").attr("data-combatant-rea", rea);
	$tr.attr("data-damage-stun", $("#combatant-modal-stun").val() || "0");
	$tr.find(".damage-stun").addClass("active").slice(0, parseInt($tr.attr("data-damage-stun")) || 0).removeClass("active");
	$tr.attr("data-damage-physical", $("#combatant-modal-physical").val() || "0");
	$tr.find(".damage-physical").addClass("active").slice(0, parseInt($tr.attr("data-damage-physical")) || 0).removeClass("active");
	// sort table
	sortTable();
	// clean up
	$("#combatant-modal").data("row", "");
}

// remove combatant
function removeCombatant(e) {
	e.preventDefault();
	// remove correct row
	let index = parseInt($("#confirm-modal").data("row"));
	$(".combatant-row").eq(index).remove();
	sortTable();
	// clean up
	$("#confirm-modal").data("row", "");
}

// start a new combat round
function startNewRound(e) {
	e.preventDefault();
	// are there rows at all?
	if ($(".combatant-row").length == 0) {
		return;
	}
	// reset ini values 
	$(".combatant-row").each(function () {
		if ($(this).find(".combatant-dice").attr("data-combatant-dice") == "") {
			$(this).attr("data-true-ini", 1);
		} else {
			$(this).attr("data-true-ini", rollForInitiative(parseInt($(this).find(".combatant-dice").attr("data-combatant-dice")), parseInt($(this).find(".combatant-rea").attr("data-combatant-rea"))));
		}
	});
	// resort table
	sortTable();
}

// sort combatants by ini value and add contextual classes 
function sortTable() {
	// do some clean up: remove previous classes from rows, disable act buttons, remove effective ini and damage badges
	$(".combatant-row").removeClass("ko-or-dead max-ini zero-ini"); //REGULAR_INI 
	$(".combatant-row").find(".act-button").prop("disabled", true).attr("aria-disabled", "true");
	$(".combatant-ini").empty();
	// mark KO or death with class
	$(".combatant-row").each(function() {
		if (parseInt($(this).attr("data-damage-stun")) == 10 || parseInt($(this).attr("data-damage-physical")) == 10) {
			$(this).addClass("ko-or-dead");
		}
	});
	// compute highest effective ini
	let iniMax = Math.max.apply(null, $.map($(".combatant-row"), function (tr, i) {
		// write current effective ini to table row
		$(tr).find(".combatant-ini").text($(tr).hasClass("ko-or-dead") ? 0 : getEffectiveIni($(tr)));
		return $(tr).find(".combatant-ini").text();
	}));
	// add damage badges and contextual classes
	$(".combatant-row").each(function () {
		// damage badges
		if ($(this).attr("data-damage-stun") && $(this).attr("data-damage-stun") != "0") {
			$(this).find(".combatant-ini").append($.parseHTML(STUN_BADGE_HTML));
			$(this).find(".stun-badge").append(DAMAGE_NIVEAU[DAMAGE_PENALTY[$(this).attr("data-damage-stun")]]);
		}
		if ($(this).attr("data-damage-physical") && $(this).attr("data-damage-physical") != "0") {
			$(this).find(".combatant-ini").append($.parseHTML(PHYSICAL_BADGE_HTML));
			$(this).find(".physical-badge").append(DAMAGE_NIVEAU[DAMAGE_PENALTY[$(this).attr("data-damage-physical")]]);
		}
		// K.O./dead -> don't add anything
		if ($(this).hasClass("ko-or-dead")) {
			return true;
		}
		// ini = zero
		if (parseInt($(this).find(".combatant-ini").text()) == 0) {
			$(this).addClass("zero-ini");
			return true;
		}
		// ini = max and non-zero 
		if (parseInt($(this).find(".combatant-ini").text()) == iniMax && iniMax > 0) {
			$(this).addClass("max-ini").find(".act-button").prop("disabled", false).removeAttr("aria-disabled");
			return true;
		}
	})
	// sort rows and append them in new order
	let $rows = $(".combatant-row").toArray().sort(whoGoesFirst);
	for (let i = 0; i < $rows.length; i++) {
		$(".combatants-table").append($rows[i]);
		$($rows[i]).css("z-index", 50-i).css("position", "relative"); 
	}
	return;
}

// validate a combatant row form by checking for all conditions, including regular HTML5 validation
function validateCombatant() {
	// get input elements
	let inputElements = {
		name: $("#combatant-modal-name").get(0),
		ini: $("#combatant-modal-ini").get(0),
		dice: $("#combatant-modal-dice").get(0),
		rea: $("#combatant-modal-rea").get(0)
	};
	// do standard HTML5 form validation first
	// (makes sure that name is not empty and that all other values are numbers within their individual ranges) 
	let valid = true;
	Object.values(inputElements).forEach( input => {
		if (!input.reportValidity()) { valid = false; }
	})
	if (!valid) { return false; }
	// now for some custom validation; first we need to get the input values
	let ini = inputElements["ini"].value.trim();
	let dice = inputElements["dice"].value.trim();
	let rea = inputElements["rea"].value.trim();
	// invalidate if ini, dice and rea are all empty
	if (ini == "" && (dice == "" || rea == "")) {
		inputElements["ini"].setCustomValidity("Requiring values for ini dice and reaction, or initiative, or all three");
		inputElements["ini"].reportValidity();
		inputElements["ini"].setCustomValidity("");
		return false;
	}
	// invalidate if dice or rea is empty but not both
	if ((dice == "") != (rea == "")) {
		inputElements["dice"].setCustomValidity("Values required for both dice and reaction, or none (in which case ini is required)");
		inputElements["dice"].reportValidity();
		inputElements["dice"].setCustomValidity("");
		return false;
	}
	// ok then
	return true;
}


/*
 *	Initialize document
 */

$(document).ready(function () {
	// add event handlers to navbar buttons
	$("#add-combatant-button").on("click", handleAddButtonClick);
	$("#new-round-button").on("click", handleNewRoundButton);
	// add event handlers to modal buttons
	$("#combatant-modal-add-ok-button, #combatant-modal-add-apply-button").on("click", addCombatant);
	$("#combatant-modal-edit-ok-button").on("click", editCombatant);
	$("#confirm-modal-new-round-ok-button").on("click", startNewRound);
	$("#confirm-modal-remove-combatant-ok-button").on("click", removeCombatant);

	// add event listeners to damage sliders in combatant modal
	$("#combatant-modal-stun").on("change", () => {
		if ($("#combatant-modal-stun").val() == "10") {
			$("#combatant-modal-penalty-stun").text("(K.O.)");
		} else {
			$("#combatant-modal-penalty-stun").text("(wound penalty -" + DAMAGE_PENALTY[$("#combatant-modal-stun").val()] + ")");
		}
	});
	$("#combatant-modal-physical").on("change", () => {
		if ($("#combatant-modal-physical").val() == "10") {
			$("#combatant-modal-penalty-physical").text("(dead)");
		} else {
			$("#combatant-modal-penalty-physical").text("(wound penalty -" + DAMAGE_PENALTY[$("#combatant-modal-physical").val()] + ")");
		}
	});

	// always focus name input field when combatant modal appears
	$('#combatant-modal').on('shown.bs.modal', () => $('#combatant-modal-name').focus());
	// always empty input fields when combatant modal disappears
	$("#combatant-modal").on('hidden.bs.modal', () => $("input[id*='combatant-modal']").val(""));
	// Hide damage monitors after click somewhere else
	$("html").on("click", (e) => {
		if ($(e.target).parents(".damage-monitor").length == 0) {
			$(".damage-monitor.seen").removeClass("seen");
		}
	});
	addTestCombatant();
});

module.exports = { rollForInitiative, validateCombatant };