/**
 * @author jontj1
 */
 var serverAddressUsername = "../includes/ajaxCheckUsername.php";
 var tickGif = '../img/green_tick.gif';
 var crossGif = '../img/red_cross.gif';
 var currentKeyword = "";											
 var oCache = new Array();											
 var debugMode = false;											
 var xmlHttpUsername = createXmlHttpRequestObjectUsername();
 
 function initCheckUsername(){
	currentKeyword = document.getElementById('usernameRegisterForm').value;
	checkCache();
 }
 
 function createXmlHttpRequestObjectUsername(){
 	var xmlHttp;
	//this should work for all browsers except IE6 and older
	try{
		//try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}catch(e){
		//assume IE6 or older when try block fails
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
										"MSXML2.XMLHTTP.5.0",
										"MSXML2.XMLHTTP.4.0",
										"MSXML2.XMLHTTP.3.0",
										"MSXML2.XMLHTTP",
										"Microsoft.XMLHTTP");
		//try every prog id until one works
		for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++){
			try{
				//try to create XMLHttpRequest object
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			}catch(e){};
		}
	}
	//return the created object or display an error message
	if(!xmlHttp){
	//alert('timmy');
		displayError("Error creating the XMLHttpRequest object");
	}else{
		return xmlHttp;
	}
 }
 
 //initiate HTTP request to retrieve suggestions for the current keyword
 function sendRequest(){
	//if the keyword isnt in the cache make an HTTP request
	try{
		//dont start another operation if one is already in progress
		if (xmlHttpUsername.readyState == 4 || xmlHttpUsername.readyState == 0 && oCache.length>0) {
			var cacheEntry = oCache.shift();
			var valueString = 'enteredName='+cacheEntry;
			xmlHttpUsername.open("POST", serverAddressUsername, true);
			xmlHttpUsername.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlHttpUsername.onreadystatechange = handleServerResponseUsernameCheck;
			xmlHttpUsername.send(valueString);
		}
	}catch(e){
		displayError("Cant connect to server:\n"+e.toString());
	}
 }
 
 //hanldes the servers response containing the suggestions
 function handleServerResponseUsernameCheck(){
 	//when readyState is 4 we are ready to read the server response
	if(xmlHttpUsername.readyState==4){
		//continue only if HTTP status is OK
		if(xmlHttpUsername.status==200){
			try{
				checkResponseUsername();
			}catch(e){
				//display error message
				displayError(e.toString());
			}
		}else{
			//display error message
			displayError("There was a problem retrieving the data:\n"+xmlHttpGetSuggestions.statusText);
		}
	}
 }
 
 //function that processes the servers response
 function checkResponseUsername(){
 	//retrieve the servers response
	var response = xmlHttpUsername.responseText;
	//server error?
	if(response.indexOf("ERRNO")>=0 || response.indexOf("error:")>=0 || response.length==0){
		throw(response.length == 0 ? "Server error." : response);
	}
	//retrieve the document element
	var xmlDocUsername = xmlHttpUsername.responseXML.documentElement;
	//initialise the new array of function names
	var resultUsername = xmlDocUsername.getElementsByTagName("resultUsername")[0].firstChild.data;
	displayResultsUsername(resultUsername);
 }
 
 function displayResultsUsername(resultUsername){
	var feedbackDiv = document.getElementById('usernameCheckFeedback');
	if(resultUsername=='yes'){
		//error present
		var html = "<img src='"+crossGif+"' alt='red cross' style='position:relative;top:5px;' /> <span class='red'>Username in use</span>";
	}else{
		//error NOT present
		var html = "<img src='"+tickGif+"' alt='green tick' style='position:relative;top:5px;' /> <span class='green'>Username available</span>";
	}
	if(currentKeyword==''){
		feedbackDiv.innerHTML = '';
	}else{
		feedbackDiv.innerHTML = html;
	}
 }
 
 //function that periodically checks to see if the typed keyword has changed
 function checkCache(){
	setTimeout("checkCache();", 500);
	//check to see if there were any changes
	if(oCache.length>0){
		//sendRequest();
	}
 }
 
 //function that adds to a keyword an array of values
 function addToCache(value){
	if(oCache.length>0){
		oCache = new Array();
		oCache.push(value);
	}else{
		oCache.push(value);
	}
	sendRequest();
 }
 
 //function that handles the keys that are pressed
 function checkUsername(field){
	//check that the current keyword is a different to the input value keyword, if so add to cache and check the db
	var currentFieldValue = field.value;
	if(currentFieldValue!=currentKeyword){
		currentKeyword = currentFieldValue;
		addToCache(currentFieldValue);
	}
 }
 
 //function that displays an error message
 function displayError(message){
 	//display error message, with more technical details if debugMode is true
	alert("Error accessing server!"+(debugMode ? "\n"+message : ""));
 }

