const password = document.getElementById('password');
const password2 = document.getElementById('password2');
password2.addEventListener('change', checkPassword);

const form = document.getElementById('marmeladenLadenRegisterForm');
form.addEventListener('submit', register);

async function register(event) {
    event.preventDefault();

    //check password with checkPassword function
    if (checkPassword()) {
        //get form data
        const formData = new FormData(form);
        //create object with form data
        const data = {};
        formData.forEach((value, key) => data[key] = value);
        //log data on console
        datastring = JSON.stringify(data);
        console.log(data);
        console.log(datastring);
        //send data to php with Ajax
        $.ajax({
            url: '../logic/registerLogic.php',
            type: 'POST',
            data: datastring,
            cache: false,
            datatype: 'text',
            success: function (response) {
                if (response == 'success') {
                    $('#mmlMainContent').load('../components/login.html');
                } else {
                    alert(response);
                }
            }
        });
    }
}

async function checkPassword() {
    if (password.value != password2.value) {
        password2.setCustomValidity('Passwords do not match');
        return false;
    } else {
        password2.setCustomValidity('');
        return true;
    }
}