window.addEventListener("load", ()=>{
    const form = document.getElementById("contactForm");

    const txtFirstName = form.querySelector("[name=firstName]");
    const txtLastName = form.querySelector("[name=lastName]");
    const txtEmail = form.querySelector("[name=email]");
    const txtComments = form.querySelector("[name=comments]");
    // console.log(txtComments, txtEmail,txtLastName, txtLastName);
    

    const vFirstName = form.querySelector("#vFirstName");
    const vLastName = form.querySelector("#LastName");
    const vEmail = form.querySelector("#vEmail");
    const vComments = form.querySelector("#vComments");
    // console.log(vComments,vEmail, vLastName, vFirstName);

    txtFirstName.focus();
    
    form.addEventListener("submit", (evt)=>{
        if(validate()){
            console.log("SEND.........");
            
        }else{
            evt.preventDefault();
        }
    })
    
    const validate = ()=>{
        
        let focusOn;

        let isValid = true;

        form.querySelectorAll(".validation").forEach((span)=>{
            span.innerHTML = ""});

        if(!txtFirstName.value){
            isValid = false;
            vFirstName.innerHTML = "First name is required";
            focusOn = txtFirstName;
        }
        if(!txtLastName.value){
            isValid = false;
            vLastName.innerHTML = "Last name is required";
            focusOn = focusOn || txtLastName;
        }
        if(!txtEmail.value){
            isValid = false;
            vEmail.innerHTML = "Email required";
            focusOn = focusOn || txtEmail;
        }else if(!validateEmailAddress(txtEmail.value)){
            isValid = false;
            vEmail.innerHTML = "Email not valid";
            focusOn = focusOn || txtEmail;
        }
        if(!txtComments.value){
            isValid = false;
            vComments.innerHTML = "Comments are required";
            focusOn = focusOn || txtComments;
        }

        if(focusOn){
            focusOn.focus();
        }

        return isValid;
    }

    function validateEmailAddress(email){
        var regExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
          return regExp.test(email);
    }


    
});