/* How to create shochu-csv
https://www.mext.go.jp/b_menu/toukei/mext_01087.html
# code,prefcode,shcoolname
nkf -Sw /tmp/221222-mxt-mxt_chousa01-1000011635_2.csv \
| awk -F, '$1 ~ /^[BC]/ {printf("%s,%s,%s\n",$1,substr($2,1,2),$3) }' \
| awk -F, '$2>1 && $2<=7 || $2==15 {print}' > out
*/
window.addEventListener(
"DOMContentLoaded",
async function () {
var schools, filterbox, nameptn, prefradio;
var schoolcsv = "./shochu-tohoku-niigata.csv";
var prefcsv = "./pref.csv", prefs={};
var getapp = "./getapp.rb";
var requiredNames = [
"schoolname", "name", "hiraname", "fm", "birthday", "grade",
"seatnum", "pname", "address", "phone", "email",
"interview", "motive", "interest", /* "issues", */ "selfintro"
];
var today = new Date(),
year = today.getFullYear(),
youngest = 12, oldest = youngest+3;
var isOlderJS = false;
async function loadurl(url) {
// return await fetch(url).then((resp) => {return resp.text()});
return new CSV(await fetch(url).then((resp) => {return resp.text()}),
{header: true}).parse();;
}
// https://developer.mozilla.org/ja/docs/Web/API/SubtleCrypto/digest
async function digestMessage(message) {
// encode as (utf-8) Uint8Array
const msgUint8 = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
// convert buffer to byte array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray.map(
b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
// alert(await digestMessage("foo"));
async function checkMid() {
var email, mid, dig;
if (document.URL.match(/\?email=(.*?)\+mid=(.*)/)) {
email = unescape(RegExp.$1),
mid = RegExp.$2,
dig = (await digestMessage(email)).substr(0, 10);
}
// alert(dig.substr(0,10));
console.log("email="+email);
console.log("dig="+dig);
console.log("mid="+mid);
if (email && dig && dig == mid) {
document.getElementById("email").value = email;
document.getElementById("email2").textContent = email;
// ei.disabled = true;
} else {
// alert("no match");
// window.location.replace("getapp.rb");
window.location.href = getapp ;
}
}
function validate(ev) {
// Check only if it is not empty
var nEmpty = 0, firstEmpty;
let f = document.forms[0];
for (let rn of requiredNames) {
let e = f.querySelector('*[name="' + rn + '"]');
if (e.value != null && e.value == "") {
ev.preventDefault(); // Cancel SUBMIT!
e.style.background = "pink";
nEmpty++;
if (!firstEmpty) firstEmpty = e;
} else {
e.style.background = "";
}
}
if (nEmpty > 0) {
if (firstEmpty.scrollIntoView) {
let option = {behavior: "smooth"};
if (!isOlderJS) option.block = "center";
try { // Scroll to last updated row
firstEmpty.scrollIntoView(option);
alert("空欄を埋めてください");
} catch (e1) {}
}
return true;
}
}
function setgrade(ev) {
var b = ev.target.value,
youngest = 12, oldest = youngest+3;
if (b.match(/(\d\d\d\d)[-/](\d\d)[-/](\d\d)/)) {
let y = RegExp.$1, m = RegExp.$2, d = RegExp.$3,
by = parseInt(y),
bw = document.getElementById("birthwarn"),
past = year - by, e;
if (m+"-"+d <= "04-01") past++;
if (past < youngest || past > oldest) {
bw.textContent = "中1から中3までの方のみです。";
ev.target.style.background = "pink";
return;
}
bw.textContent = "";
ev.target.style.background = null;
e = document.forms[0].querySelectorAll(
'select[name="grade"] option');
console.log(`e.len=${e.length}`);
console.log(`past=${past}, youngest=${youngest}`);
console.log(`p-y=${past-youngest}`);
e[past-youngest-1].selected = true;
}
}
function genlist(schoolcsv) {
let dl = document.getElementById("schoollist");
for (let school of schoolcsv) {
if (school["code"].match(/^C/)) { // Junior-High School
let opt = document.createElement("option");
opt.value = school["schoolname"];
dl.appendChild(opt);
}
}
}
function init() {
isOlderJS = !("insertAdjacentElement" in document.body);
checkMid();
// load
fetch(schoolcsv).then((resp) => {
return resp.text().then((text) => {
genlist(new CSV(text, {header: true}).parse());
})})
prefradio = document.forms[0].pref; // get name="pref" nodeList
let birthday = document.forms[0].birthday;
if (birthday) {
console.log(`min=${year-oldest}-04-02, max=${year-youngest}-04-01`);
birthday.addEventListener('input', setgrade, false);
birthday.setAttribute("min", `${year-oldest}-04-02`);
birthday.setAttribute("max", `${year-youngest+1}-04-01`);
birthday.value = `${year-youngest}-04-01`;
console.log(`val=${birthday.getAttribute("value")}`);
}
// Set validaters
for (let i of document.querySelectorAll('input[type="submit"]')) {
i.addEventListener("click", validate, false);
}
}
function updateSchool(e) {
// alert("YES");
var nm = document.getElementById("schoolname"),
id = document.getElementById("schoolid");
// nm.value = document.forms[0].school.value;
nm.value = e.target.nextSibling.textContent;
id.value = e.target.value;
}
init();
}, false);