// requires file js_xmlhttprequest.js to be called first
//Our XmlHttpRequest object - created when page with form is called or refreshed
// if browser is not right version and var cannot by created, rest of fns on this page will not run
var receiveReq = createXMLHttpRequest();

//Called from an event in the form; will POST a value to the URL indicated in fn, to evaluate captcha
function getParam(theForm) {
 //Set the URL
 var url = 'captcha_response.php';
 //Set up the parameters of our AJAX call
 var postStr = theForm.txtCaptcha.name + "=" + encodeURIComponent( theForm.txtCaptcha.value );
 //Call the function that initiate the AJAX request
 makeRequest(url, postStr);
}

//Initiate the AJAX request
function makeRequest(url, param) {
//If our readystate is either not started or finished, initiate a new request
 if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
   //Set up the connection to captcha_test.htm (or page containing form). True sets the request to asyncronous(default) 
   receiveReq.open("POST", url, true);
   //Set the function that will be called when the XmlHttpRequest objects state changes
   receiveReq.onreadystatechange = updateResponse; 

   receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   receiveReq.setRequestHeader("Content-length", param.length);
   receiveReq.setRequestHeader("Connection", "close");

   //Make the request
   receiveReq.send(param);
 }   
}

//Called every time the response is requested and our XmlHttpRequest objects state changes
function updateResponse() {
 //Check if our response is ready
 if (receiveReq.readyState == 4) {
   //Set the content of the DIV element with the response text
   document.getElementById('captcha_output_result').innerHTML = receiveReq.responseText;
 }
}

//Called every time our image is clicked and XmlHttpRequest objects state changes
function updateCaptchaImage() {
 //Check if our response is ready
 if (receiveReq) {
   //Get a reference to CAPTCHA image
   img = document.getElementById('imgCaptcha'); 
   //Change the image
   img.src = 'captcha_create_image.php?' + Math.random();
 }
}