var email_error;
var form_error;
var xmlHttp;
var email;
window.onload=function(){
inparr = document.ctform.getElementsByTagName('input');
document.ctform.email.value="";
document.getElementById("answer").innerHTML = "";
listener();
}

function listener(){
document.ctform.onsubmit = function(){check_fields();setTimeout("submit_form()",1000); return false;};
document.ctform.email.onchange = function(){check_mail();};
document.ctform.onreset = function(){	document.ctform.name.className="true";
	document.ctform.message.className="true";document.ctform.email.className="true";document.getElementById("answer").innerHTML="";}
}

function submit_form(){
	if(form_error==0&&email_error==0){
		document.ctform.submit();
	}
}

function check_fields(){
	form_error=0;
	document.ctform.name.className="true";
	document.ctform.message.className="true";
	check_field(document.ctform.name);
	check_field(document.ctform.message);
	if(form_error==1){
	check_field(document.ctform.email);
	document.getElementById("answer").innerHTML='Please check all fields marked in <span class="error">red</span>';
	}
	if(form_error==0){
	check_mail()
	}

}

function check_mail(){
	email_error=0;
	document.getElementById("answer").innerHTML="Validating email&hellip;";
	strmail = document.ctform.email;
	strmail.className="true";
	var formatter = /^[a-zA-Z0-9._+&*#-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/;
	if(formatter.test(strmail.value)){
		remote_validation();
	}
	else{
	email_error=3;
	strmail.className="error";
	document.getElementById("answer").innerHTML='Email is <span class="error">not</span> formatted properly';
	}

}

function check_field(check_obj){
	if(check_obj.value==0){
	form_error=1;
	check_obj.className="error";
	return false;
	}
}

/*---------------------------------------------------------*/
 function createXMLHttpRequest() {
   try {return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try {return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   try {return new XMLHttpRequest(); } catch(e) {}
   return null;
 }

function remote_validation() {
document.getElementById("answer").innerHTML="validating email...";
email=document.ctform.email.value;
xmlHttp = createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("POST", "phprestricted/remote_val.php");
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send("email="+email);
}

function handleStateChange() {
		if(xmlHttp.readyState == 4) {
			if(xmlHttp.status == 200) {
					if(xmlHttp.responseText=="true"){
					document.getElementById("answer").innerHTML="The email address is valid";
					email_error=0;
					return true;
					
					}
					else{
						email_error=2;
						document.getElementById("answer").innerHTML='The email address <span class="error">&ldquo;'+document.ctform.email.value+'&rdquo;</span> is not valid';
						document.ctform.email.className="error";
						return false;
						
					}

			}
		}
}
