function set_loading(obj, state) {
	$(obj).attr("aria-busy", state);
}

function initTable(tag, data) {
	if( data.length <= 0 ) return;
	let keys = Object.keys(data[0]);
	let header = "";
	for( let i = 0; i < keys.length; i++ ) {
		header += "<th>" + keys[i] + "</th>";
	}
	header += "<th>actions</th>";
	$($(tag).children("thead")[0]).html("<tr>"+header+"</tr>");
	for( let i = 0; i < data.length; i++ ) {
		header = "";
		let row_id = data[i]["id"];
		for( let u = 0; u < keys.length; u++ ) {
			if( keys[u].match(/is[A-Z]/gy) == null ) {
				header += "<td>" + data[i][keys[u]] + "</td>";
				continue;
			}
			let v = "";
			if( data[i][keys[u]]+"" == "true" ) {
				v = "checked";
			}
			header += "<td><input type=\"checkbox\" onclick=\"onBoolChange(this)\" data-key=\""+keys[u]+"\" " + v + "/></td>";
		}
		header += "<td><img src=\"/file/svg/trash-2.svg\" onclick=\"deleteRow(this)\"></td>";
		let tabName = tag.substring(1);
		$($(tag).children("tbody")[0]).append("<tr data-rownum=\""+row_id+"\" data-table=\""+tabName[0].toUpperCase()+tabName.substring(1)+"\">"+header+"</tr>");
	}
}

function hideModal() {
	$("dialog").prop("open", false);
}

function confirmDeletion(obj) {
	$("dialog").prop("open", false);
	$.post( "/api/delete_row", { table: $(obj).attr("data-table"), row: $(obj).attr("data-row") }, function() {
			window.location.reload();
	});
}

function deleteRow(obj) {
	$("dialog").prop("open", true);
	$("#dialog-btn").attr("data-row", $(obj).parent().parent().attr("data-rownum"));
	$("#dialog-btn").attr("data-table", $(obj).parent().parent().attr("data-table"));
}

function onBoolChange(obj) {
	$.post( "/api/update_table", { table: $(obj).parent().parent().attr("data-table"), column: $(obj).attr("data-key"), id: $(obj).parent().parent().attr("data-rownum"), val: $(obj).prop("checked") } );
}