function getXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}


function validaform()
{
	var datiEmail=document.forms[0];
	var nomeCampo;
	for (var i=0;i<datiEmail.length;i++)
	{
		nomeCampo=controllaCampo(datiEmail[i]);
		if (!nomeCampo) return false;
	}
		
}

function ControllaMail(email)
{
	 Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	  if (Filtro.test(email)) return true;
  	  else
      {
      	alert("Indirizzo e-mail non corretto. Controllare e riprovare");
        return false;
      }
   }


function controllaCampo(dato)
{
	var nome=new String(dato.name);
	var valore=new String(dato.value);
	
	if (nome=="_email")
	{ 
		if (!ControllaMail(valore)) return false;
	}
	

	if (nome.charAt(0)=="_")
	{
		if (valore.length<=2)
		{
			alert("Attenzione, compilare tutti i campi obbligatori.");
			return false
		}
		else
		{
			if (nome=="_captcha") verificaCaptcha(valore);
			return nome.substring(1,nome.length);
		}
	}
	else
	{
		return nome;
	}
}

function stateChanged() {
	if(xmlHttp.readyState == 4) {
		//Stato OK
		if (xmlHttp.status == 200) {
			var resp = xmlHttp.responseText;
			if (resp=="ok") document.forms[0].submit();
			if (resp=="errore") 
			{
				var ele=document.getElementById("invia_form");
				ele.removeAttribute("disabled");
				alert('Attenzione, il codice Captcha non corrisponde. Riprovare');
			}
		
		}
		waiting = false;
	}
}


function verificaCaptcha(valore) {
	if (xmlHttp && !waiting) {
		var ele=document.getElementById("invia_form");
		ele.setAttribute("disabled","disabled");
		xmlHttp.open("GET", 'controllaCaptcha.php?cap=' + valore, true);
		xmlHttp.onreadystatechange = stateChanged;
		xmlHttp.send(null);
		waiting = true;
	}
}

var xmlHttp = getXmlHttpObject();
var waiting = false;
