/*-----
AWA: Form Validation
---------------------------------------------------------------------------------
Version: 1.1
Author: Richard Stephenson
Email: richard.stephenson@awadigital.com
Website: http://www.awadigital.com
Last Modified: 26 November 2007
---------------------------------------------------------------------------------
©2007 AWA Ditital. All Rights Reserved.
No Part of this script may be reproduced without permission.
-------------------------------------------------------------------------------*/


$(document).ready(function(){
	var whichform = $("form");
	
	var formFields = $(':input').not($("[@type=submit]")).not($("[@value=http://]"));
	$("form").submit(function() {
		clearfeedback(this);
		return (validateForm(this,"submit") ? true : false);
	});
	
	function validateForm(whichform,method) {
		var errors = new Array();
		$(':input[@class*=required]',whichform).each(function() {
			if(!isFilled(this)) {
				//var feedback = " - " + $(this).siblings()[0].firstChild.nodeValue + " required";
				var feedback = " - Required";
				errors[errors.length] = new Array(feedback,this);
			} else if (this.className.indexOf("email") != -1) {
				if (!isEmail(this)) {
					var feedback = " - Valid email required";
					errors[errors.length] = new Array(feedback,this);
				}
			} else if (this.nodeName == "SELECT") {
				if (this.options[this.selectedIndex].value == 0) {
					//var feedback = " - " + $(this).siblings()[0].firstChild.nodeValue + " required";
					var feedback = " - Required";
					errors[errors.length] = new Array(feedback,this);
				}
			}			
		});
		if(errors.length != 0) {
			for(var i=0; i < errors.length; i++){
				addfeedback(errors[i][0],errors[i][1]);
			}
			if (method === "submit") {
				errors[0][1].focus();	
			}
			return false;
		} else {
			return true;	
		}
	}
	function addfeedback(feedback,field) {
		$($(field).siblings()[0]).append('<em class="feedback">' + feedback + '</em>');
		$(field).addClass('error');
		$(field).parent().addClass('error');
	}
	function clearfeedback(whichform) {
		$('em',whichform).remove(".feedback");
		$(':input[@class*=required]',whichform).removeClass('error');
		$('div.error',whichform).removeClass('error');
	}
	function isFilled(x) {
		return (x.value.length < 1 || x.value == x.defaultValue ? false : true);
	}
	function isEmail(field) {
		var regEx = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
		return (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1 || !field.value.match(regEx) ? false : true);
	}
});
