/*
@Name: Form Validator.
@Author: Porta
@Requires: Prototype 1.5.0
@Description: 
	Validates alll fields based on their class and value,.
	Validation type comes defined on each form element class
	Options are:
		mandatory: There's need to be some text entered or selected by the user.
		email; A valid email adress
*/
/*Regexes for classname matching*/
var mandatory = /.*mandatory.*/;
var email = /.*email.*/;
var result;
var params = '';

/*Final result. if notify runs at lest onve, checkConditions will return false.*/
function checkForm(form) {
	result = true;
	var a = document.getElementsByClassName('errorMessage');
	a.each(function(e) {
		e.remove();
	});
	var fields = form.getElements();
	fields.each(function(f,index) {
		//group params for ajax updater form send.
		//if (f.value != '') {};
		if (f.type == 'hidden'){
			params += f.name + "=" + f.value + "&";
		};
		if (f.type == 'submit'){
			params += f.name + "=" + f.value + "&";
		};
		if (f.type == 'select-one'){
			if (f.selectedIndex == 0 && mandatory.test(f.className)) {
				notify(' Please Choose one ',f); 
			}else{
				params += f.name + "=" + f.value + "&";
			};
		};
		if (f.type == 'text'){ 
			if (f.value == '' && mandatory.test(f.className)) {
				notify(' You need to enter some text here ',f); 
			};
			if (f.value != '' && email.test(f.className)) {
				var filter=/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$/;
				if (!(filter.test(f.value))) {
					notify(' Not a valid email address ',f); 
				}else{
					params += f.name + "=" + f.value + "&";
				}
			}else{
				params += f.name + "=" + f.value + "&";
			};
		};
	});
	if (result == true) {
		form.submit();
	}else{
		params='';
	};
	return false;
 }


/*Error message styles
@Note: the class "errorMessage" needs to be on the span element in order to remove the error message if the function runs again.
*/
 var color ="color:#FF0000;";
 var size = "font-size:11px;";
 var background ="#DDDDDD;";
 
 function notify(message,f){
		var msg = "<span class='errorMessage' style='"+color+size+background+"'>"+message+"</span>";
		new Insertion.After(f,msg);
		result = false;
}
