$(function () {
    $("#sendEmailWidget").submit(function() {      
        var formError = "";        
        var uemail = $("input#okta-signin-email").val(); 
        var phone = $("input#okta-signin-phone").val();
        var enquiry = $("select#okta-signin-enquiry").val();
        var phn_error = validPhone(phone);

        if (!validEmail(uemail)) 
            formError = "Kindly enter a valid email: abc@domain.xyz";
        else if (phn_error !== "")
            formError = phn_error;        
        else if (!validEnquiry(enquiry)) 
            formError = "Please select the nature of your enquiry."
        
        if (formError !== "") {
            $("p#form-error").html(formError);
            return false;
        }   
        $("p#form-error").hide();
        var unames = $("input#okta-signin-username").val().split(" ");
        $("p#send-success").html("<em>" + unames[0] + "</em>, your enquiry has been received.");
        
        setTimeout(() => { return true; }, 4000);
        
    });

    $("#sendEmail").submit(function() {
        var enquiry = $("select#enquiry_nature").val();

        if (!validEnquiry(enquiry)) {
            $("li#enq-error").show();
            return false;
        } else 
            $("li#enq-error").hide();

        var email = $("input#emailaddress").val();
        
        if (!validEmail(email)) {
            $("li#email-error").show();
            return false;
        } else 
            $("li#email-error").hide();
        
        var phone = $("input#phone").val();
        var phn_error = validPhone(phone);

        if (phn_error != "") {
            $("li#phone-error").html(phn_error);
            $("li#phone-error").show();
            return false;
        } else
            $("li#phone-error").hide();
            
        var fname = $("input#firstname").val();
        $("input#submitContact").hide();
        $("p#enquiry-success").html("Dear <strong>" + fname + "</strong>, you will get a response  concerning <em>" + enquiry + "within the hour.");
    });
});

function validEmail (email) {
    var pattern = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/;
    if (!(pattern.test(email)))
        return false;
    return true;
}

function validEnquiry (enquiry) {
    if (enquiry == "0")
        return false;
    return true;
}

function validPhone (phone) {
    var error = "";

    if (phone.length != 10) 
        error = "Kindy confirm phone has 10 digits.";
    else if (phone.charAt(0) != "0" || (phone.charAt(1) != "1" && phone.charAt(1) != "7")) 
        error = "Kindly ensure phone starts with \"07\" or \"01\".";
    else {
        for (var i=2; i<10; i++) {            
            if (isNaN(parseInt(phone.charAt(i)))) 
                error = "Kindly ensure phone is numbers only.";
        }
    }   
    return error;
}