// **********************************************
// JavaScript inline form validator
// @author  - Simon Pollard for Deckchair UK Ltd
// @version - 2.3
// @date    - November '09
// Requires jQuery and jQuery plugin timers (http://plugins.jquery.com/project/timers)

// inline functions
$(function() {
	// change form submission so it validates via javascript
	$("form#email_form").attr("onSubmit","return validateForm(this.id,'include/email_form.php');");
	$("form#email_form").attr("autocomplete","off");

	// on input focus
	$("input,textarea").focus(function() {
		// add class for css
		$(this).addClass("curFocus")
		
		// get the html of the containing element
		var parentName = $(this).parent();
		var htmlStr = parentName.html();
		
		// if this is a field that requires validation
		if ( ($(this).hasClass("novalid")==false) && ($(this).val()=="") )
		{
			// if there is not a span in the element
			if (htmlStr.search(/span|SPAN/)==-1)
			{
				// add a span with a class the same as the id of the input
				// its contents are the title of the input 
				$(this).parent().append("<span class='message "+$(this).attr("id")+"'>"+$(this).attr("title")+"</span>");
			}
		}
		// if showing a "this is required" msg and there is a title, show that instead
		if ( ($(this).hasClass("req")==true) && (!$(this).attr("title")=="") )
		{
			// if there is a span in the element
			if ( (htmlStr.search(/span|SPAN/)>=0) && ($("."+$(this).attr("id")).hasClass("warning")==true) && ($("."+$(this).attr("id")).hasClass("good")==false) )
			{
				// Change the msg title
				$("span."+$(this).attr("id")).html($(this).attr("title"));
				// Remove the warning class on the input
				$("span."+$(this).attr("id")+"").removeClass("warning");
				$($(this).attr("id")+"").removeClass("highlightbox_red");	
			}
		}
	});
	
	// on input blur
	$("input,textarea").blur(function() {
		// remove class for css
		$(this).removeClass("curFocus")
		// If this field is required and there is no value
		if (($(this).val()=="")&&($(this).hasClass("req")==true))
		{	
			validateReq($(this).attr("id"));
		}			
	});

	// On keydown in input/textarea field check the value
	$("input,textarea").keyup(function () {	
		// stop any timers
		$("input#"+$(this).attr("id")).stopTime();
		
		// if they have entered a value
		if (!($(this).val()==""))
		{
			// remove required class
			$(this).removeClass("highlightbox_red");
			// call function to validate value
			checkValue($(this).attr("id"));
		}
		
		})
	.change();
	
	//Clear the form values on F5 or browser refresh
	$("#email_form p input").attr("value","");
	$("#email_form textarea").attr("value","");
	//Because we are clearing the input values we need to add one back for the submit button
	$("#email_form #submit").attr("value","Send form");
	$("#email_form .subscribe").attr("value","Subscribe");
	
});

/*
inline validation check (called upon keydown)
*/
function checkValue($input_id)
{	
	// if this is an email address
	if ($("#"+$input_id).hasClass("email")==true)
	{
		validateInput($input_id,"email",$("#"+$input_id+"").val());
	}
	// if this is a phone number
	else if ($("#"+$input_id+"").hasClass("phone")==true)
	{
		validateInput($input_id,"phone",$("#"+$input_id+"").val());
	}
	// if this is a fullname
	else if ($("#"+$input_id+"").hasClass("fullname")==true)
	{
		validateInput($input_id,"fullname",$("#"+$input_id+"").val());
	}
	// if this is req
	else if ($("#"+$input_id+"").hasClass("req")==true)
	{
		validateReq($input_id);
	}
}

/*
Data Validation Functions
*/
function validateInput($input_id,$type,$input_value)
{	
	var switchType = $type;
	
	// Set the filter and error message dependant on input validation type
	switch (switchType)
	{
	case "email":
		var filter = /^.+@.+\..{2,3}$/;
		var errorMsg = "This is not a valid email";
		break;
	case "phone":
		var filter = /^([0-9 ]{7,})$/;
		var errorMsg = "This is not a valid phone number";
		break;
	case "fullname":
		// check to see if two names have been entered
		var mySplitResult = $input_value.split(" ");
		// if there is just one name
		if (!mySplitResult[1])
		{
			var filter = /^([a-zA-Z]+)$/;
		}
		// if there is more than two
		else
		{
			var filter = /^([a-zA-Z'-]+\s+){1,4}[a-zA-z'-]+$/;
			//var filter = /^([a-zA-Z])+([\sa-zA-Z])*(([\s]{1}[\']?[oO][\']?)?([\sa-zA-Z]([.-]{1}[a-zA-Z]+)?)+)?\Z/;
		}
		var errorMsg = "Please use only alphabetic characters";
		break;
		
	default:
		break;
	}
	
	// get the html of the containing element
	var parentName = $("#"+$input_id).parent();
	var htmlStr = parentName.html();
	
	
	//$input_value = $("#"+$input_id).val();
	//$input_value = $("#"+$input_id).attr("value");
	
	if (!($input_value==""))
	{	
		// if there is not a span in the element
		if (htmlStr.search(/span|SPAN/)==-1)
		{
			// start timer, after 2 seconds return error (if needed)
			$("#"+$input_id).oneTime(2000, function() {
					
				if ( !filter.test($input_value) )
				{	
					// add a span with a class the same as the id of the input
					$("#"+$input_id).parent().append("<span class='message "+$input_id+"')></span>");
					$("span."+$input_id).html(errorMsg);
					$("span."+$input_id).removeClass("message");
					$("span."+$input_id).removeClass("good");
					$("span."+$input_id).addClass("warning");
					$("#"+$input_id).addClass("highlightbox_red");
					return false;
				}
				else
				{
					// add a span with a class the same as the id of the input
					$("#"+$input_id).parent().append("<span class='message "+$input_id+"')></span>");
					$("span."+$input_id).html("Thank you");
					$("span."+$input_id).removeClass("warning");
					$("span."+$input_id).addClass("good");
					return true;
				}
			
			});
		}
		else
		{
			if ( !filter.test($input_value) )
			{	
				// start timer, after 2 seconds return error
				$("#"+$input_id).oneTime(2000, function() {
					$("span."+$input_id).html(errorMsg);
					$("span."+$input_id).removeClass("message");
					$("span."+$input_id).removeClass("good");
					$("span."+$input_id).addClass("warning");
				});
				return false;
			}
			else
			{
				$("span."+$input_id).html("Thank you");
				$("span."+$input_id).removeClass("warning");
				$("span."+$input_id).addClass("good");
				return true;
			}
		}
	}
	return true;
}

/*
Required validation checking
*/
function validateReq($input_id)
{
	//$input_value = $("#"+$input_id+"").val();
	$input_value = $("#"+$input_id+"").val();
	
	// get the html of the containing element
	var parentName = $("#"+$input_id).parent();
	var htmlStr = parentName.html();
	// if there is not a span in the element
	
	if ( $input_value=="" )
	{
		// if there is no msg span
		if (htmlStr.search(/span|SPAN/)==-1)
		{
			// add a span with a class the same as the id of the input
			$("#"+$input_id).parent().append("<span class='message "+$input_id+"')></span>");		
		}
		$("span."+$input_id).html("This is required");
		$("span."+$input_id).removeClass("message");
		$("span."+$input_id).removeClass("good");
		$("span."+$input_id).addClass("warning");
		$("#"+$input_id).addClass("highlightbox_red");
		return false;
	}
	else
	{
		// if there is a msg span
		if (htmlStr.search(/span|SPAN/)>=0)
		{
			// remove the span
			$("span."+$input_id).remove();		
		}
		return true;
	}
}



/*
Validate form upon submit
*/
function validateForm($form_id,$page_name)
{	
	// get the html of the containing element
	var parentName = $("#submit").parent();
	var htmlStr = parentName.html();
		
	// if there is a span in the element
	if (htmlStr.search(/span|SPAN/)>=0)
	{
		$("span."+$("#submit").attr("id")).remove();
	}

	// check the form validates
	$test = checkForm($form_id);
	
	if ( $test==false )
	{
		// get the html of the containing element
		var parentName = $("#submit").parent();
		var htmlStr = parentName.html();
		
		// if there is not a span in the element
		if (htmlStr.search(/span|SPAN/)==-1)
		{
			// add a span with a class the same as the id of the input
			$("#submit").parent().append("<span class='message "+$("#submit").attr("id")+"'><b>Oops!</b> There has been a problem. Please check and re-send the form</span>");
		}
		
		
		return false;
	}
	else
	{	
		return true;
	}

	return false;
}

/*
Check form validates before submision
*/
function checkForm($form_id)
{
	var validation_ok = true;
	
	// serialize the form values into a string
	var myString = $("form#"+$form_id).serialize();

	// the string pairs are seperated by &'s so split them up - input=value&input2=value2 etc...
	var mySplitResult = myString.split("&");
	
	// now run through them
	for(i = 0; i < mySplitResult.length; i++){
		// Our pairs are grouped with = so split with that - input=value etc...
		var mySplitResult2 = mySplitResult[i].split("=");
		
		// Save the input id
		$input_id = mySplitResult2[0];
		
		// Now run the required validation checks
		
		// if this is a required field and there is no value
		if ( ($("#"+$input_id+"").hasClass("req")==true) && ($("#"+$input_id+"").val()=="") )
		{
			if ( !validateReq($input_id) )
			{
				var validation_ok = false;
			}
		}
			
		// Check if there is a value
		if ( !$("#"+$input_id+"").val()=="")
		{	
			// if this is an email address
			if ($("#"+$input_id+"").hasClass("email")==true)
			{
				$test = validateInput($input_id,"email",""+$("#"+$input_id+"").val()+"");
			}
			// if this is a phone number
			if ($("#"+$input_id+"").hasClass("phone")==true)
			{
				$test = validateInput($input_id,"phone",""+$("#"+$input_id+"").val()+"");
			}
			// if this is a date
			if ($("#"+$input_id+"").hasClass("fullname")==true)
			{
				$test = validateInput($input_id,"fullname",""+$("#"+$input_id+"").val()+"");
			}
			if ( $test == false )
			{
				var validation_ok = false;
			}
		}
	}
	
	return validation_ok;
}