var fields = Array("#name","#email","#message","#captcha");
var errors = new Array();
var errormsg = "";
var validated;

function validateForm(){	
	var errorCnt = 0;
	for(var i=0; i<fields.length; i++){
		var field = fields[i];
		var val = $(""+field).attr("value");
		
		if((field == "#email") && (val.length == 0)){
			// do nothing as email is optional
		} else if(field == "#email" && val.length < 5){
			errormsg += "<li>The email provided is not long enough.</li>";
			erros[errorCnt] = field;
			errorCnt++;
		} else if(field == "#email" && val.length > 50){
			errormsg += "<li>The email provided is too long.</li>";
			erros[errorCnt] = field;
			errorCnt++;
		} else if(field == "#name" && val.length < 2){
			errormsg += "<li>The name provded is not long enough.</li>";
			errors[errorCnt] = field;
			errorCnt++;	
		} else if(field == "#name" && val.length > 50){
			errormsg += "<li>The name provided is too long.</li>";
			errors[errorCnt] = field;
			errorCnt++;	
		} else if(field == "#message" && val.length < 1) {
			errormsg += "<li>The feedback/question area was left blank</li>";
			errors[errorCnt] = field;
			errorCnt++;	
		}
	}
		   
	var cap = $("#captcha").attr("value");	
	if(cap == "" || cap.length < 3 || cap.length > 6){
		errormsg += "<li>The code was neglected or entered incorrectly.</li>";
		errors[errorCnt] = "#captcha";
		errorCnt++;
		validated = false;
	}
	
	showErrors();
	errormsg = "";
	
	if(errorCnt == 0)	return true;
	else				return false;
}

function showErrors(){
	for(var i=0; i<errors.length; i++){
		$(""+errors[i]).addClass("error");
	}	
	$(".errmsg").css("display","block");
	$(".errmsg ul").html(errormsg);
}

function resetErrors(){
	for(var i=0; i<errors.length; i++){
		$(""+errors[i]).removeClass("error");
	}	
}

function activateForm(){
	for(var i = 0; i < fields.length; i++){
		$(""+fields[i]).focus(function(){$(this).addClass("focus");});
		$(""+fields[i]).blur(function(){$(this).removeClass("focus");});	
	}
}

window.onload = function(){
	activateForm();
	$("#contact").submit(function(){		
		resetErrors();
		if(validateForm()){
			return true;			
		} else {
			return false;				
		}
		return false;
  	});
};
