const form = document.getElementById('form');
const username = document.getElementById('username');
const password = document.getElementById('password');

form.addEventListener('submit', e => {
    e.preventDefault();

    checkInputs();
    printForm();
});

const setErrorFor = (element, message) => {
    const inputControl = element.parentElement;

    inputControl.classList.add('error');
    inputControl.classList.remove('success');
}

const setSuccessFor = (element) => {
    const inputControl = element.parentElement;

    inputControl.classList.add('success');
    inputControl.classList.remove('error');
};



function checkInputs() {
    // trim to remove the whitespaces
    const usernameValue = username.value.trim();
    const passwordValue = password.value.trim();

    if (usernameValue === '') {
        setErrorFor(username, 'Username cannot be blank');
    }
    else {
        setSuccessFor(username);
    }

    if (passwordValue === '') {
        setErrorFor(password, 'Password cannot be blank');
    }
    else if(passwordValue.length < 8) {
        setErrorFor(password, 'Password must be at least 8 characters');
    }
    else {
        setSuccessFor(password);
    }

    if (usernameValue === 'admin' && passwordValue === 'admin') {
        window.location.href = 'http://localhost:8080/WEB/Welcome.html';
    }
}

//Open a new blank page and print the usename and password

function printForm() {
    var myWindow = window.open("", "MsgWindow", "width=200,height=100");
    myWindow.document.write("Username: " + username.value + "<br>Password: " + password.value);
}

