/*
 * jQuery Form Validator
 *
 * Forms with the class 'validate' are validated.
 * Form must have an id or validation won't work
 * Form Elements to be validated should have any of the following classes to set their valid content
 *
 *   novalidate     - Ignore this field, do not validate - Can be used to temporarily prevent validation of an element
 *   reqnotempty    - Field must not be empty
 *   reqemail       - Must be a valid email address
 *   reqphone       - Must be a valid telephone no
 *   reqalphanum    - Must only be 'A-Z 0-9 ,.+-'*:()=/'
 *   reqalphonly    - Must be 'A-Z ,.-'
 *   reqstrictalpha - ONLY A-Z
 *   reqnum        - '0-9.-' 
 *
 */

		var valid;
		var started=false;
		var running=false;
		var finished=false;
		var finishedAjax=true;
		var verifyInterval=false;

$(document).ready(function() {
	$("form.validate").live('submit', function(e) {
		if(!started)
		{
			valid = true;
			finished=false;
			finishedAjax=true;
			//console.log('initialising');
		}
		if(!started)
		{
		if(verifyInterval!=false)
		{
			//console.log('clearing existing interval ');
			clearInterval(verifyInterval);
		}			
			var tmpid=$(this).attr('id')
			//console.log('setting up interval'+tmpid);
			verifyInterval=window.setInterval("verifyForm('"+tmpid+"')", 1000);
		}
		if(!finished || !finishedAjax || !valid)
		{
			//console.log('finished initialising');
			e.preventDefault();
			return false;
		}
		});
	});

	
function verifyForm(target) {
	if(running)
	{
		//console.log('aborting already running');
		return;
	}
	running=true;
	started=true;
	if(finished && finishedAjax && !valid)
	{
		//console.log('failed verfication');
		window.clearInterval(verifyInterval);
		verifyInterval=false;
		//$('#'+target).preventDefault();
		started=false;
		running=false;
		return false;
	}
	if(finished && finishedAjax && valid)
	{
		//console.log('submit '+target);
		clearInterval(verifyInterval);
		$('#'+target).submit();
		return true;
	}
	//console.log('starting verification');
	//var target=($(e.target).attr('id'));
	//console.log('checking (1x) '+target);
	
	$("body").find("#"+target).find("input,textarea,select").not("[type=hidden]").not(".novalidate").each(function() {
	//console.log('checking (2) '+target);
		var filter=new Array();
		var errors=new Array();
		filter['unique']=/^always fail$/;
	//console.log('checking (3) '+target);
		errors['unique']='';			
		filter['reqnotempty']=/^.+$/m;
		errors['reqnotempty']='This field cannot be left blank';
		filter['reqemail']=/^(.+@.+\..{2,3}){0,1}$/;
		errors['reqemail']='Please enter a valid e-mail';
		filter['reqctact']=/^(.+@.+\..{2,3}){0,1}$/;
		errors['reqctact']='Please enter a valid e-mail';			
		filter['reqphone']=/^((\+{0,1}[0-9]{0,2}){0,1} {0,1}\({0,1}[0-9]{4,5}\){0,1} {0,1}[0-9]{5,8}){0,1}$/;
		errors['reqphone']='Please enter a valid phone no';
		filter['reqalphanum']=/^[\na-zA-Z0-9 \,\.\+\-\'\*\/\:\(\)\=]*$/;
		errors['reqalphanum']='Please use only alpha-numeric characters';
		filter['reqalphaonly']=/^[\na-zA-Z \,\.\-\']*$/;
		errors['reqalphaonly']='Please only use the characters A to Z.';
		filter['reqstrictalpha']=/^[\na-zA-Z ]*$/;
		errors['reqstrictalpha']='Please only use the characters A to Z.';
		filter['reqnum']=/^[\n0-9\-\.]*$/;
		errors['reqnum']='Please only use numbers';
		//used for external validation if the class forcefailvalidation is set it will always fail
		//console.log('checking (4) '+$(this).attr("id"));
		if(!finished)
		{
			//console.log('here we go');
			var thisonesvalid=true;
			for(var i in filter)
			{
				if($(this).hasClass(i))
				{
					if(i=='unique')
					{
						finishedAjax=false;
						//console.log('found unique form field');
						var dataVal=$(this).attr("rel");
						$.ajaxSetup ({ cache: false	});
						var ajax_load = '<div style="text-align:center;">Checking...</div>';
						var loadUrl = "ajaxuniquecheck.php";	
						$(".ajaxmsg_"+$(this).attr("id")).html(ajax_load).load(loadUrl+'?data='+encodeURI(dataVal)+'&unique_id='+encodeURI($(this).val()), $("#settings").serialize(), function(response, status, xhr)
						{
							//console.log('running callback');
							finishedAjax=true;
							if (status == "error")
							{
								var msg = "Sorry but there was an error: ";
								$(this).html(msg + xhr.status + " " + xhr.statusText);
							}
							if($(this).html()=='Value has already been used')
							{
								//console.log('invalid');
								var tmp=$(this).attr("class").split(" ");
								for(var j in tmp)
								{
									if(tmp[j].indexOf('ajaxmsg_')>=0)
									{
										$("#"+tmp[j].replace('ajaxmsg_','')).addClass("ajaxfailedvalidation");
										$("label[for="+tmp[j].replace('ajaxmsg_','')+"]").addClass("ajaxfailedvalidation");
									}
								}
								$(this).addClass('formvalidatormsg');
								valid = false;		
								thisonesvalid=false;			
							}
							else
							{
								//console.log('valid');
								var tmp=$(this).attr("class").split(" ");
								for(var j in tmp)
								{
									if(tmp[j].indexOf('ajaxmsg_')>=0)
									{
										$("#"+tmp[j].replace('ajaxmsg_','')).removeClass("ajaxfailedvalidation");
										$("label[for="+tmp[j].replace('ajaxmsg_','')+"]").removeClass("ajaxfailedvalidation");
									}
								}							
								$(this).removeClass('formvalidatormsg').html("");
							}
						});
					}
					else if(filter[i].test($(this).val())) 
					{
						//console.log($(this).attr("id")+' passed');
						if(thisonesvalid)
						{
							$(this).removeClass("failedvalidation");
							if($(this).attr("id").length>0) $("label[for="+$(this).attr("id")+"]").removeClass("failedvalidation");
							if($(this).attr("id").length>0) $(".msg_"+$(this).removeClass("formvalidatormsg").attr("id")).html("");
						}
					}
					else
					{
						//console.log($(this).attr("id")+' failed');
						valid = false;		
						thisonesvalid=false;			
						$(this).addClass("failedvalidation");
						if($(this).attr("id").length>0) $("label[for="+$(this).attr("id")+"]").addClass("failedvalidation");
						if(errors[i]!='' && $(this).attr("id").length>0) $(".msg_"+$(this).attr("id")).addClass("formvalidatormsg").html(errors[i]);
					}
				}
			}
		}
		//console.log('finished checking');
	}
	
	);
	finished=true;
	running=false;
}

 

