
var xmlHttp = createXmlHttpRequestObject(); // save a instance of XMLHttpRequest
var showErrors = false; // shows errors if flag is true

// this function validate an input field and give the result - xml back to the
// serverresponse handling script
function validate(inputValue, fieldID) { 

	if(xmlHttp) { // only next steps, if XMLHttpRequest Object exists & is not empty
		
		if(fieldID) { // if fieldID is not NULL
			inputValue = encodeURIComponent(inputValue); // encode the input value
			fieldID = encodeURIComponent(fieldID); // encode the fieldname
			parameters = "inputValue=" + inputValue + "&fieldID=" + fieldID;
		}

		try { // server-connection & send data to validate	
			if((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)) { // check the XMLHttpRequest state (not bussy) and and the queue not empty
				xmlHttp.open("POST", 'modules/validate.php?' + parameters, true); // open server connection
				xmlHttp.onreadystatechange = handleRequestStateChange;
				xmlHttp.send(parameters); // send url to serverscript
			}
		
		} catch (e) { alert(e.toString()); } // error if server-connection not possible

	}

}


function handleRequestStateChange() { // handle the server response 
	if(xmlHttp.readyState == 4) { // if response have status 4, read it!
		if(xmlHttp.status == 200){ // only go forward if http-status is ok (200)
			try { readResponse(); // read server response
			} catch (e) { displayError(e.toString()); }
		} else displayError(xmlHttp.statusText); 
	}
}


function readResponse() { 
	var response = xmlHttp.responseText; // read server-response
	if(response.indexOf("ERRNO") >=0 || response.indexOf("error:") >= 0 || response.length == 0) throw(response.length == 0 ? "Server zur Zeit nicht erreichbar:" : response);
	responseXml = xmlHttp.responseXML; // save xml answer in responseXml

	xmlDoc = responseXml.documentElement;	
	result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
	fieldID = xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;
	// check to set the correct validae class for source form element
	if($(fieldID).tagName == 'SELECT') var classExt = 'Select';
	else if($(fieldID).tagName == 'TEXTAREA') var classExt = 'Textarea';
	else var classExt = '';

	$(fieldID + 'Failed').className = (result == 0) ? 'validateError' +  classExt : 'elHide';
	
}


function displayError($message) { // show errors
	if(showErrors) { // only display if showErrors = true
		showErrors = false;
		alert("Fehler gefunden: \n" + $message);
		setTimeout("validate();", 10000); // try next validation after 10 seconds
	}
}

