// **********************************************
// JavaScript inline form validator
// @author  - Simon Pollard for Deckchair UK Ltd
// @version - 2.1
// @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#mail_form").attr("onSubmit","return validateForm(this.id,this.action);");

	// 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")==false) && ($("."+$(this).attr("id")).hasClass("good")==false) )
			{
				// Change the msg title
				$("."+$(this).attr("id")).html($(this).attr("title"));
				// Remove the warning class on the input
				$("span."+$(this).attr("id")+"").removeClass("warning");
			}
		}
	});
	
	// on input blur
	$("input,textarea").blur(function() {
		// remove class for css
		$(this).removeClass("curFocus")
		// If there is no value in the field
		if ($(this).val()=="")
		{
			// If this is a required field
			if ($(this).hasClass("req")==true)
			{
				// get the html of the containing element
				var parentName = $(this).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
					// its contents are the title of the input 
					$(this).parent().append("<span class='message "+$(this).attr("id")+"'></span>");
				}
				// Change the span to a required msg
				$("span."+$(this).attr("id")+"").html("This is required");
				$("span."+$(this).attr("id")+"").removeClass("message");
				$("span."+$(this).attr("id")+"").removeClass("good");
				$("span."+$(this).attr("id")+"").addClass("warning");
				$(this).addClass("highlightbox_red");
			}
			else
			{
				// get the html of the containing element
				var parentName = $(this).parent();
				var htmlStr = parentName.html();
				// if this contains a span
				if (htmlStr.search(/span|SPAN/)>-1)
				{
					// remove the span
					$("span."+$(this).attr("id")).remove();
				}
			}
		}			
	});

	// 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
	$("#mail_form input").attr("value","");
	$("#mail_form textarea").attr("value","");
	$("#mail_form #submit").attr("value","Send");
	
});

// inline validation check
function checkValue($input_id)
{	
	// if this is an email address
	if ($("#"+$input_id).hasClass("email")==true)
	{
		validateInput($input_id,"email");
	}
	// if this is a phone number
	else if ($("#"+$input_id+"").hasClass("phone")==true)
	{
		validateInput($input_id,"phone");
	}
	// if this is a fullname
	else if ($("#"+$input_id+"").hasClass("fullname")==true)
	{
		validateInput($input_id,"fullname");
	}
	// if this is req
	else if ($("#"+$input_id+"").hasClass("req")==true)
	{
		validateReq($input_id);
	}
}

/*
Data Validation Functions
*/
function validateInput($input_id,$type)
{
	$input_value = $("#"+$input_id).val();
	
	//alert($input_value);
	
	var switchType = $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":
		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();
	// if there is not a span in the element
	
	if (!($input_value==""))
	{	
		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
				{
					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;
			}
		}
	}
}

// Required validation checking
function validateReq($input_id)
{
	$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 (htmlStr.search(/span|SPAN/)==-1)
	{
		if ( $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("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
		{
			return true;
		}
	}
	else
	{
		if ( $input_value=="" )
		{
			// start timer, after 2 seconds return error
			$("#"+$input_id).oneTime(2000, function() {
				$("span."+$input_id).html("This is required");
				$("span."+$input_id).removeClass("message");
				$("span."+$input_id).removeClass("good");
				$("span."+$input_id).addClass("warning");
			});
			return false;
		}
		else
		{
			$("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
	if ( !checkForm($form_id) )
	{
		// 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.<br />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)
			{
				if ( !validateInput($input_id,"email") )
				{
					var validation_ok = false;
				}
			}
			// if this is a phone number
			if ($("#"+$input_id+"").hasClass("phone")==true)
			{
				if ( !validateInput($input_id,"phone") )
				{
					var validation_ok = false;
				}
			}
			// if this is a date
			if ($("#"+$input_id+"").hasClass("fullname")==true)
			{
				if ( !validateInput($input_id,"fullname") )
				{
					var validation_ok = false;
				}
			}
			
		}
	}
	
	return validation_ok;
}
