/*
Enquiry Form Validation and Sending
*/

$(document).ready(function(){
	// Place ID's of all required fields here.
	required = ["name", "email", "enquiry"];
	// If using an ID other than #email or #error then replace it here
	email = $("#email");
	errornotice = $("#error");
	// The text to show up within a field when it is incorrect
	emptyerror = "Please fill out this field.";
	emailerror = "Please enter a valid e-mail.";

	$("#submit").click(function(){	
		var name = $('input[name=name]');
		var email = $('input[name=email]');
		var enquiry = $('textarea[name=enquiry]');
		var filename = $('input[name=filename]');
		var uploadedfilename = $('input[name=uploadedfilename]');
		//Validate required fields
		for (i=0;i<required.length;i++) {
			var input = $('#'+required[i]);
			if ((input.val() == "") || (input.val() == emptyerror)) {
				input.addClass("needsfilled");
				input.val(emptyerror);
				errornotice.fadeIn(750);
			} else {
				input.removeClass("needsfilled");
			}
		}
		// Validate the e-mail.
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
			email.addClass("needsfilled");
			email.val(emailerror);
		}

		//if any inputs on the page have the class 'needsfilled' the form will not submit
		if ($(":input").hasClass("needsfilled")) {
			return false;
		}
		else {
			errornotice.hide();
			//organize the data properly
			var data = 'name=' + name.val() + '&email=' + email.val()  + '&enquiry='  + encodeURIComponent(enquiry.val()) + 
				'&filename=' + filename.val() + '&uploadedfilename=' + uploadedfilename.val();
			
			//disabled all the text fields
			$('.slider').attr('disabled','true');
			
			//show the loading sign
			$('.loading').show();
			
			//start the ajax
			$.ajax({
				//this is the php file that processes the data and send mail
				url: "sendmail.php",	
				
				//GET method is used
				type: "GET",
	
				//pass the data			
				data: data,		
				
				//Do not cache the page
				cache: false,
				
				//success
				success: function (html) {				
					//if sendmail.php returned 1/true (send mail success)
					if (html==1) {					
						//hide the form
						$("#thform").hide();//fadeOut('slow');					
						
						//show the success message
						$('.done').fadeIn('slow');

					//if process.php returned 0/false (send mail failed)
					} else alert('Sorry, unexpected error. Please try again later.');				
				}		
			});
			
			//cancel the submit button default behaviours
			return false;
		}
	});
	
	// Clears any fields in the form when the user clicks on them
	$(":input").focus(function(){		
	   if ($(this).hasClass("needsfilled") ) {
			$(this).val("");
			$(this).removeClass("needsfilled");
	   }
	});
});	