function validate(fields) {
    let required = true;
    for (let index = 0; index < fields.length; index++) {
       if(fields[index].value != ""){
        if(fields[index].name == "email"){
            var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
            if(fields[index].value.match(mailformat))
            {;
            }else{
                required = "invalid";
                break;
            }
        }
        
       }else{
        required = false;
       }
       
        
    }
    return required;
}

$("form#contact-form #submit").click(function(){
    var inputfields = document.querySelectorAll(".input");
    if(validate(inputfields) == false){
        document.getElementById("error").innerHTML = "All fields are required";
         return;
    }else if(validate(inputfields) == "invalid"){
        document.getElementById("error").innerHTML = "Email is invalid";
         return;
    }
    else{
        document.getElementById("error").innerHTML = "";
        sendmail();
    }
});



function sendmail()
{
    
    let elements = document.getElementsByClassName("input");
    let formdata= new FormData();
    for(let i=0; i<elements.length; i++)
    {
        formdata.append(elements[i].name,elements[i].value)
    }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'controllers/mail.php', true);
    xhr.onload = function () {
    // do something to response
    if(this.responseText==0)
    {
        Swal.fire({
            title: 'OOPS!!!',
            text: 'Something went wrong',
            icon:'error',
            showConfirmButton: false,
            timer: 2500
        })
    }
    else
    {
        Swal.fire({
            title: 'Good job!',
            text: 'We will be in touch!',
            icon:'success',
            showConfirmButton: false,
            timer: 2500
        })
    }
   
    };
    xhr.send(formdata);
}