var captcha_number = "";
var form = "";


// With this function it is possible to check if the entered captcha-number
// is correct or not without submitting the form (and loosing the form-data).
// Return:
// true =  The entered captcha-number is correct.
// false = No number or a wrong number entered by the user.
function captcha_isValid(a_captcha_number, a_form) {
	captcha_number = a_captcha_number;
	form = a_form;
	if((undefined == captcha_number) || ("" == captcha_number)) {
		alertError_wrongCaptchaNumber(form);
		return false;
	}

	onValidCaptcha_submit();

	// Don't submit the form here.
	// The form-submit will be fired in the function
	return false;
}


function onValidCaptcha_submit() {
	var params = "action=captcha_isValid&arg1="+captcha_number;
	sndReq(params, "onValidCaptcha_submit2");
}
function onValidCaptcha_submit2() {
	if(4 == ajax.readyState) {
		var response = ajax.responseText;

		switch(response) {
			case "1": {
				// Submit the form.
				form.submit();
				return true;
				break;
			}
			case "0": {
				alertError_wrongCaptchaNumber(form);
				break;
			}
			default: {
				alert(response);
				break;
			}
		}

	}
	return false;
}


function alertError_wrongCaptchaNumber() {
	form.captcha_number.focus();
	alert("Le code n'est pas correct!");
}



////
// AJAX functions
//
// Source: http://rajshekhar.net/blog/archives/85-Rasmus-30-second-Ajax-Tutorial.html
//
var ajax = createRequestObject();
ajax_rpc = "http://www.ligerz.ch/CAPTCHA/rpc.php";
onreadystatechange_func = "";


function createRequestObject() {
	var tmpXmlHttpObject;
	
	//depending on what the browser supports, use the right way to create the XMLHttpRequest object
	if (window.XMLHttpRequest) { 
		// Mozilla, Safari would use this method ...
		tmpXmlHttpObject = new XMLHttpRequest();
	} else if (window.ActiveXObject) { 
		// IE would use this method ...
		tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return tmpXmlHttpObject;
}


function sndReq(params, a_onreadystatechange_func) {
	ajax.open("get", ajax_rpc +"?"+ params);
	ajax.onreadystatechange = onValidCaptcha_submit2;
	ajax.send(null);
}



