function inviaEmail()
{
	var corpoMessaggio=costruisciCorpo();
	if ((corpoMessaggio))
	{
		invia(corpoMessaggio);	
	}
}

function costruisciCorpo()
{
	var datiEmail=document.forms[0];
	var body=new Array();
	var nomeCampo;
	for (var i=0;i<datiEmail.length;i++)
	{
		nomeCampo=controllaCampo(datiEmail[i]);
		if (nomeCampo)
		{
			var dato=encodeURIComponent(nomeCampo);
			dato+="=";
			dato+=encodeURIComponent(datiEmail[i].value);
			dato=dato.replace(/%0A/g,"#acapo#");
			body.push(dato);
		}
		else
		{
			return false;
		}
	}
	return body.join("&");
}
	
function controllaCampo(dato)
{
	var nome=new String(dato.name);
	var valore=new String(dato.value);
	if (nome.charAt(0)=="_")
	{
		if (valore.length<=2)
		{
			alert("Attenzione, compilare tutti i campi obbligatori.")
			return false
		}
		else
		{
			return nome.substring(1,nome.length);
		}
	}
	else
	{
		return nome;
	}
}

function invia(corpo)
{
	var xmlhttp=creaOggettoXMLHttp();
	xmlhttp.open("post","spedisci.php",false);
	document.body.style.cursor="wait";
	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4)
		{
			if (xmlhttp.status==200)
			{
				document.body.style.cursor="default";
				alert(xmlhttp.responseText);
				pulisciForm();
			}
			else
			{
				alert("Errore durante l'invio del messaggio(" + xmlhttp.statusText + "). Riprovare in un secondo momento, grazie.")
			}
		}
	};
	xmlhttp.send(corpo);
}

function creaOggettoXMLHttp()
{
	
	if (typeof XMLHttpRequest != "undefined")
	{
		return new XMLHttpRequest();
	}
	else 
	{
	
		var versioni = [ "MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp","Microsoft.XMLHttp"]; 
		
		for (var i=0; i<versioni.length; i++)
		{
			try
			{
				var oggetto=new ActiveXObject(versioni[i]);
				return oggetto;			
			}
			catch(errore)
			{
				//evito che l'errore blocchi la ricerca dell'oggetto giusto
			}
		}
		
	}
	throw new Error("La libreria MSXML non è installata");
}

function pulisciForm()
{
	var elementi=document.forms[0];
	for (var i=0;i<elementi.length;i++)
	{
		elementi[i].value="";
	}
}

function resettaForm()
{
	pulisciForm();
}