function invioMail(){
    var captcha = document.getElementById('captcha').value;
    var nome = document.getElementById('nome').value;
    var azienda = document.getElementById('azienda').value;
    var telefono = document.getElementById('telefono').value;
    var email = document.getElementById('email').value;
    var testo = document.getElementById('testo').value;
    var to = document.getElementById('to').value;
    var regE = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var regT = /^([0-9\.\- \+])+$/;
    //inizio controlli
    if(!regE.test(email)){
        alert('Inserire un indirizzo email valido.');
        return false;
    }else if(nome == ''){
        alert('Inserire un nome valido.');
        return false;
    }else if(azienda == ''){
        alert('Inserire un nome azienda valido.');
        return false;
    }else if(!regT.test(telefono)){
        alert('Inserire un telefono valido.');
        return false;
    }else{
        document.mail.submit();
    }
}

function controlloCaptcha(){
    var captcha = document.getElementById('captcha').value;
    if(!captcha){
        alert('Ricopiare il codice di sicurezza nel campo apposito.');
        cambiaCodice();
        return false;
    }else{
        var r = Math.random();
        myRequest = CreateXmlHttpReq(function() {myVerificaHandler()});
        myRequest.open("GET", "scripts/php/checkCaptcha.php?r=" + escape(r) + "&captcha=" + escape(captcha));
        myRequest.send(null);
    }
}
function myVerificaHandler() {
    if (myRequest.readyState == 4 && myRequest.status == 200) {
        if(myRequest.responseText == 'ok'){
            invioMail();
        }else{
            alert('Il codice di sicurezza inserito risulta errato.');
            cambiaCodice();
        }
    }
}

function cambiaCodice(){
    var r = Math.random();
    document.getElementById('captchaDiv').innerHTML = '<img src="captcha/immagine.php?r=' + escape(r) + '" alt="Captcha" title="Captcha"><br />se il codice ' + decodeURIComponent('&egrave;') + ' illeggibile, <a href="#" onclick="cambiaCodice();">[clicca qui]</a>';
}
function CreateXmlHttpReq(handler) {
    var xmlhttp = null;
    try {
        xmlhttp = new XMLHttpRequest();
    }catch(e){
        try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    xmlhttp.onreadystatechange = handler;
    return xmlhttp;
}