// JavaScript Document
$(document).ready(function() {
	$('#contactForm #submit').click(function() {
		// Fade in the progress bar
		$('#contactForm #formProgress').hide();
		$('#contactForm #formProgress').html('<img src="ajax-loader.gif" /> Sending&hellip;');
		$('#contactForm #formProgress').fadeIn();	
		// Disable the submit button
		$('#contactForm #submit').attr("disabled", "disabled");
		// Clear and hide any error messages
		$('#contactForm .formError').html('');
		// Set temaprary variables for the script
		var isFocus=0;
		var isError=0;
		// Get the data from the form
		var name=$('#contactForm #name').val();
		var email=$('#contactForm #email').val();
		var subject=$('#contactForm #subject').val();
		var comments=$('#contactForm #comments').val();
		var txtCaptcha=$('#contactForm #txtCaptcha').val();
		// Validate the data
		if(name=='' || name =='Full Name') {
			$('#contactForm #errorName').html('This is a required field.');
			$('#contactForm #name').focus();
			isFocus=1;
			isError=1;
		}
		if(email=='') {
			$('#contactForm #errorEmail').html('This is a required field.');
			if(isFocus==0) {
				$('#contactForm #email').focus();
				isFocus=1;
			}
			isError=1;
		} else {
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			if(reg.test(email)==false) {
				$('#contactForm #errorEmail').html('Invalid email address.');
				if(isFocus==0) {
					$('#contactForm #email').focus();
					isFocus=1;
				}
				isError=1;
			}
		}
		if(comments=='' || comments=='Comments') {
			$('#contactForm #errorComments').html('This is a required field.');
			if(isFocus==0) {
				$('#contactForm #comments').focus();
				isFocus=1;
			}
			isError=1;
		}
		if(txtCaptcha=='') {
			$('#contactForm #errorCaptcha').html('This is a required field.');
			if(isFocus==0) {
				$('#contactForm #txtCaptcha').focus();
				isFocus=1;
			}
			isError=1;
		}
		// Terminate the script if an error is found
		if(isError==1) {
			$('#contactForm #formProgress').html('');
			$('#contactForm #formProgress').hide();	
			// Activate the submit button
			$('#contactForm #submit').attr("disabled", "");
			return false;
		}
		$.ajaxSetup ({  
			cache: false  
		});
		var dataString = 'name='+ name + '&email=' + email + '&comments=' + comments + '&txtCaptcha=' + txtCaptcha;  
		$.ajax({  
			type: "POST",
			url: "submit-form.php",
			data: dataString,
			success: function(msg) {
				// Check to see if the mail was successfully sent
				if(msg=='Mail sent') {
					// Update the progress bar
					$('#contactForm #formProgress').html('<img src="ajax-complete.gif" /> Message sent.').delay(2000).fadeOut(400);
					// Clear the subject field and message textbox
					$('#contactForm #subject').val('');
					$('#contactForm #comments').val('');
				} else if(msg=='incorrect') {
					$('#contactForm #formProgress').html('');
					   img = document.getElementById('imgCaptcha'); 
					   //Change the image
					   img.src = 'create_image.php?' + Math.random();
					alert('You have entered an invalid security code. Please try again.');
				} else {
					$('#contactForm #formProgress').html('');
					   img = document.getElementById('imgCaptcha'); 
					   //Change the image
					   img.src = 'create_image.php?' + Math.random();
					alert('There was an error sending your email. Please try again.');
				}
				// Activate the submit button
				$('#contactForm #submit').attr("disabled", "");
			},
			error: function(ob,errStr) {
				$('#contactForm #formProgress').html('');
				alert('There was an error sending your email. Please try again.');
				// Activate the submit button
				$('#contactForm #submit').attr("disabled", "");
			}
		});
		return false;
	});
});

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
 if (window.XMLHttpRequest) {
    return new XMLHttpRequest(); //Mozilla, Safari ...
 } else if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP"); //IE
 } else {
    //Display our error message
    alert("Your browser doesn't support the XmlHttpRequest object.");
 }
}

//Our XmlHttpRequest object
var receiveReq = getXmlHttpRequestObject();


//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.html. 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 = updatePage; 

   //Add HTTP headers to the request
   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 our XmlHttpRequest objects state changes
function updatePage() {
 //Check if our response is ready
 if (receiveReq.readyState == 4) {
   //Set the content of the DIV element with the response text
   document.getElementById('result').innerHTML = receiveReq.responseText;
   //Get a reference to CAPTCHA image
   img = document.getElementById('imgCaptcha'); 
   //Change the image
   img.src = 'create_image.php?' + Math.random();
 }
}

//Called every time when form is perfomed
function getParam(theForm) {
 //Set the URL
 var url = 'captcha.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);
}