var XHR;

function addEvent(object, eventType, functionToCall){
	if(object.addEventListener){
		//will run on Mozilla based browsers
		object.addEventListener(eventType, functionToCall, false);
		return true;
	}else if(object.attachEvent){
		//will run on IE
		var x = object.attachEvent("on"+eventType, functionToCall);
		return x;
	}else{
		//the browser doesnt support either method
		return false;
	}
}

function createXHR(type, url, data, functionToCall, async){
	if(window.XMLHttpRequest){
		XHR = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		XHR = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(XHR){
		XHR.onreadystatechange = function(){functionToCall();};
		XHR.open(type, url, true);
		XHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		XHR.send(data);
	}
}

function setup(){
	addEvent(document.getElementById('email'), 'focus', clearField);
	
	//change the form action
	var signupForm = document.getElementById('signup');
	addEvent(signupForm, 'submit', addAddress);
	signupForm.onsubmit = function() {return false;}
}

function clearField(){
	document.getElementById('email').select();
}

function addAddress(){
	//hide the form and show the response box
	document.getElementById('signup').style.display = "none";
	document.getElementById('message').style.display = "none";
	document.getElementById('responsebox').style.display = "block";
	
	//create the XHR
	createXHR('get', 'signup.php?ajax=1&email='+document.getElementById('email').value, '', addResponse, true)
}

function addResponse(){
	var xhr = XHROk();
	if(xhr){

		document.getElementById('message').innerHTML = xhr.responseText;
		setTimeout(showForm, '1000');
	}
}

function showForm(){
	document.getElementById('message').style.display = "block";
	document.getElementById('signup').style.display = "block";
	document.getElementById('responsebox').style.display = "none";
}

function XHROk(){
	try{
		if(XHR.readyState==4){
			if(XHR.status==200){
				//XHR was successfull - reset the timer and return true
				result = XHR;
				XHR = null;
				return result;
			}else{
				//XHR failed - add request back to the queue and reset the timer for 30 secs to give time for any errors in the network to be corrected
				handleXHRError();
			}		
		}
	}catch(e){
		//XHR failed - add request back to the queue and reset the timer for 30 secs to give time for any errors in the network to be corrected
		handleXHRError();
	}
	return 0;
}

/*
*
*	@Method:	handleXHRError
*	@Parameters:	0
*	@Description:	Function run to handle an XHR error
*
*/
function handleXHRError(){
	document.getElementById('signup').style.display = "block";
	document.getElementById('message').style.display = "block";
	document.getElementById('responsebox').style.display = "none";
}

addEvent(window, 'load', setup);