const firstName = document.querySelector("#fName");
const lastName = document.querySelector("#lName");
const userName = document.querySelector("#user");
const phoneNumber = document.querySelector("#phoneNum");
const city = document.querySelector("#city");
const emailAddress = document.querySelector("#emailAdd");
const startingAmount = document.querySelector("#bankAmount");
const submitButton = document.querySelector("#submitBtn");
const firstNameFormat = /^[A-Za-z][A-Za-z~'\-\s]{0,33}[A-Za-z~'\-]?$/;
const lastNameFormat = /^[A-Za-z][A-Za-z~'\-\s]{0,43}[A-Za-z~'\-]?$/;
const userNameFormat = /^\d[A-Z]{3}[a-z][\$&*@!]$/;
const phoneNumberFormat = /^\d{3}\.\d{3}\.\d{4}$/;
const cityFormat = /^[A-Za-z]{1,50}$/;
const emailAddressFormat = /^[\w.-]+@[a-zA-Z0-9-]+\.(com|ca)$/;
const startingAmountFormat = /^(?:[68]|[1-9]\d*[02468]|5000)$/;
const MONTHARR = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const fields = [firstName, lastName, userName, phoneNumber, city, emailAddress, startingAmount];
const formats = [firstNameFormat, lastNameFormat, userNameFormat, phoneNumberFormat, cityFormat, emailAddressFormat, startingAmountFormat];
const fieldNames = ["firstName", "lastName", "userName", "phoneNumber", "city", "emailAddress", "startingAmount"];
const ELEMENTS = fields.map((field, index) => ({
name: fieldNames[index],
field: field,
format: formats[index]
}));
// ------------- VALIDATION -------------
function validate(format, field) {
if (format.test(field.value)) {
field.style.backgroundColor = "#fff";
displayErrorMessage(field, false);
} else {
field.style.backgroundColor = "#f9c7c7";
displayErrorMessage(field, true);
}//if
}//validate()
function displayErrorMessage(field, valid) {
switch (field) {
case firstName:
document.querySelector("#errFName").innerText = valid ? "First name: Max 35 characters, must start with a letter, and can only contain letters, space, ~, ' and -." : '';
break;
case lastName:
document.querySelector("#errLName").innerText = valid ? "Last name: Max 45 characters, must start with a letter, and can only contain letters, space, ~, ' and -." : '';
break;
case userName:
document.querySelector("#errUserName").innerText = valid ? "Username must start with a number, followed by three uppercase letters, a lowercase letter, and end with $, &, *, @, or !." : '';
break;
case phoneNumber:
document.querySelector("#errPhoneNum").innerText = valid ? "Phone number format: ###.###.####" : '';
break;
case city:
document.querySelector("#errCity").innerText = valid ? "City name must contain only letters and have a max of 50 characters." : '';
break;
case emailAddress:
document.querySelector("#errEmail").innerText = valid ? "Email format: [email protected] or [email protected]." : '';
break;
case startingAmount:
document.querySelector("#errStartingAmount").innerText = valid ? "Amount must be between $5 and $5000, divisible by 2, and have no decimals." : '';
break;
}//switch
}//displayErrorMessage
function changeInvalidFields() {
for (let i = 0; i < fields.length; i++) {
validate(formats[i], fields[i]);
}
} //changeInvalidFields
function validateForm() {
let isValid = true;
for (let i = 0; i < fields.length; i++) {
if (!formats[i].test(fields[i].value))
isValid = false;
} //for
return isValid;
}//validateForm()
ELEMENTS.forEach(el => {
el.field.addEventListener('blur', function () { validate(el.format, el.field); }, false);
});
submitButton.addEventListener('click', function () { changeInvalidFields(); }, false);
// ---------STORING VALUES IN LOCAL STORAGE------------
let now = new Date();
let month = MONTHARR[now.getMonth()];
let day = now.getDate();
let year = now.getFullYear();
let hour = now.getHours();
let min = now.getMinutes();
let currentVisit = `${month} ${day}, ${year} at ${hour < 13 ? hour : hour - 12}:${min < 10 ? "0" + min : min} ${hour < 12 ? "AM" : "PM"}`;
function setLocalStorage() {
localStorage.setItem("currentVisit", currentVisit);
localStorage.setItem("lastVisit", currentVisit);
ELEMENTS.forEach(el => {
if (el.field.value.length > 0) {
localStorage.setItem(el.name, el.field.value);
}
})
}
function checkKeys(f) {
let stop = false;
let key;
for (let x = 0; x < localStorage.length && stop === false; x++) {
key = localStorage.key(x);
if (key === f)
return true;
}
return false;
}
function checkLocalStorage() {
if (localStorage.length > 0) {
if (fieldNames.every(checkKeys)) { // checks every key exists in localStorage
localStorage.setItem('lastVisit', localStorage.getItem('currentVisit'));
localStorage.setItem('currentVisit', currentVisit);
return true;
} else{
localStorage.setItem('firstVisit', true);
return false;
}
} else{
localStorage.setItem('firstVisit', true);
return false;
}
}
if (checkLocalStorage()){
console.log("returning user");
location.href = "game.html"; // redirects directly to game if user already exists in localStorage
}else{
console.log("first time");
}
document.querySelector("#formLayout").onsubmit = function(event){
if(validateForm()){
setLocalStorage();
return true;
}else{
return false;
}
}
// document.querySelector("#formLayout").onsubmit = validateForm;
let queryString = window.location.search;
let values = [];
queryString = queryString.substring(1);
while(queryString.indexOf("+") !== -1)
queryString = queryString.replace("+", " ");
let qArray = queryString.split("&");
for(let i = 0; i < qArray.length; i++){
let pos = qArray[i].search("=");
let keyVal = qArray[i].substring(0, pos);
let dataVal = qArray[i].substring(pos + 1);
dataVal = decodeURIComponent(dataVal);
values[keyVal] = dataVal;
}//for