//validate each field of a form according to their class name
//to launch the validation, write 'validate' as the class name of the form
//several options for the checking process can be written in the class name:

/*
** validate         -> check the form for the defined required fields
** immediatly        -> the required fields will be checked onblur, onchange
** onsubmit        -> the required fields will be checked when the submit button is pressed
** append         -> will append a red * after the input (could be whatever you want if you change the var)
** highlight      -> will highlight the field as per the user defined highlight class (background-color && color)
*/

//full checking will give:
//class='validate onsubmit immediatly append highlight', order doesn't matter

//checking types to be written in each required fields

/*
** required         -> check for empty value
** mail             -> check email address
** zip              -> check the japanese zip code
** equality         -> check that the field is equal to the precedent one (submit mode only)
** alphaNum         -> check that the field is alphanumeric
** numeric          -> check that the field is numeric
*/


function validateForm(currentForm) {
	var is_valid = true;
	var	RadioObj={};
 	var	RadioName=[];
	var	i=0;

	//let's look for the input tags and check them
 	var inputs = currentForm.getElementsByTagName("input");
	for (var inputNumber = 0; inputNumber < inputs.length; inputNumber++) {
		if (inputs[inputNumber].type == "text" || inputs[inputNumber].type == "hidden" ||
			inputs[inputNumber].type == "password") {
			if (inputs[inputNumber].className.indexOf("required",0)!=-1) {
	
				if (isEmpty(inputs[inputNumber]) ) {
					is_valid = false;
				}
			}
			else if (inputs[inputNumber].className.indexOf("mail",0)!=-1) {
 				if (!isEmail(inputs[inputNumber]) ) {
 					is_valid = false;
				}
			}
			else if (inputs[inputNumber].className.indexOf("zip",0)!=-1) {
 				if (!isZip(inputs[inputNumber]) ) {
 					is_valid = false;
				}
			}
			else if (inputs[inputNumber].className.indexOf("equality",0)!=-1) {
 				if (!areFieldsEqual(inputs[inputNumber],inputs[inputNumber-1]) ) {
 					is_valid = false;
				}
			}
			else if (inputs[inputNumber].className.indexOf("alphaNum",0)!=-1) {
 				if (!isAlphaNum(inputs[inputNumber]) ) {
 					is_valid = false;
				}
			}
			else if (inputs[inputNumber].className.indexOf("numeric",0)!=-1) {
 				if (!isNum(inputs[inputNumber]) ) {
 					is_valid = false;
				}
			}
		}

		//collect each required radio || checkbox inputs in one object
		//count the number of checked items
		if ((inputs[inputNumber].type == "radio" || inputs[inputNumber].type == "checkbox") && 
			inputs[inputNumber].className.indexOf("required",0)!=-1) {

			var field=inputs[inputNumber].name;

			if (RadioName.indexOf(field)==-1) {
					RadioName[RadioName.length]=field;
					i=0;
					RadioObj[field]=i;
			}
			if(inputs[inputNumber].checked) {
					i++;
					RadioObj[field]=i;					
			}
		}	

	}
	//loop thru the object containing all required radio and checkbox inputs
	//check that there is at list one element checked
	if(checkArraysOfElements(RadioObj)) {
			is_valid=false;
	}
	//let's look for the select tags and check them too
	var selects;
 	selects = currentForm.getElementsByTagName("select");
	for (var selectNumber = 0; selectNumber < selects.length; selectNumber++) {
		if (selects[selectNumber].className.indexOf("required",0)!=-1) {
			if (isEmpty(selects[selectNumber]) ) {
				is_valid = false;
			}
		}
	}
	//let's look for the select tags and check them too
	var textareas;
 	textareas = currentForm.getElementsByTagName("textarea");
	for (var textareaNumber = 0; textareaNumber < textareas.length; textareaNumber++) {
		if (textareas[textareaNumber].className.indexOf("required",0)!=-1) {
			if (isEmpty(textareas[textareaNumber]) ) {
				is_valid = false;
			}
		}
	}
	return is_valid; 
}


function validateField(field) {
 	var is_valid=true;
	var ieEvent = "srcElement";
	var mozEvent = "target";
	var instance="instance";

	field[mozEvent] ? field = field[mozEvent][instance] : field = field[ieEvent][instance];

	if (field.type == "text" ||  field.type == "password" || field.tagName=="SELECT" || 
		field.tagName=="TEXTAREA") {

		if (field.className.indexOf("required",0)!=-1) {
			if (isEmpty(field) ) {
				is_valid = false;
			} 
		}
		else if (field.className.indexOf("mail",0)!=-1) {

 			if (!isEmail(field) ) {
 				is_valid = false;
			}
		}
		else if (field.className.indexOf("zip",0)!=-1) {
 			if (!isZip(field) ) {
 				is_valid = false;
			}
		}
		else if (field.className.indexOf("alphaNum",0)!=-1) {
 			if (!isAlphaNum(field) ) {
 				is_valid = false;
			}
		}
		else if (field.className.indexOf("numeric",0)!=-1) {
 			if (!isNum(field) ) {
 				is_valid = false;
			}
		}
	}
	return is_valid;
}

function applyValidation() {
	forms = document.getElementsByTagName("form"); 
	//loop thru all the forms
   	for (var formNumber = 0; formNumber < forms.length; formNumber++)  { 
		var currentForm=forms[formNumber];
		if(currentForm.className.indexOf('validate',0)!=-1) {

			if(currentForm.className.indexOf('append',0)!=-1) {
				APPEND_WARNING=true;
			} else { APPEND_WARNING=false ;}
			if(currentForm.className.indexOf('highlight',0)!=-1) {
				HIGHLIGHT=true;
			} else { HIGHLIGHT=false;}

				//loop thru all the elements of one form	
				for(var Field=0; Field <currentForm.elements.length; Field++) {
					var elmObj = currentForm.elements[Field];
						if(elmObj.type=="text" || elmObj.type=="password" || elmObj.tagName=="SELECT" || elmObj.tagName=="TEXTAREA") {
							var index=elmObj;
							if(index.attachEvent) { 
									index.attachEvent('onblur',  validateField); 
								    index.instance=elmObj;
							}
							else { 
								elmObj.addEventListener('blur',  validateField,true); 
								index.instance=elmObj;
							}
						}
				}
			if(currentForm.className.indexOf('onsubmit',0)!=-1) {
				//trigger the checking onsubmit
				if(currentForm.attachEvent) { 
					currentForm.attachEvent('onsubmit',  function () { validateForm(currentForm) }); 
				}
				else { 
					currentForm.addEventListener('submit',  function () { validateForm(currentForm) },true); 
				}
			}
		}
	} 
	//addUniversalEventListener(window,'unload', function () {unregisterAllEvents()});
}


var WARNING_COLOR="red";
var WARNING_SYMBOL='*';


//displaying and hidding error messages
function showError(name) {

    //first display the error_message
 	var ErrorMessage=document.getElementById('error_'+name);
	new Effect.Appear(ErrorMessage);
	//then check to see if its a checkbox or radio button
    var FieldNum = document.getElementsByName(name);
	//if it has only one name we assume one id
	if(FieldNum.length==1){
		if(HIGHLIGHT) {
			var highlightField=document.getElementById(name);
			  var ActualClassName=highlightField.className;
			highlightField.className=ActualClassName+" highlight";
		}
	}
	//if it has several names, we assume checkbox or radio
	// we color the parentNode /change color
	else {
		if(HIGHLIGHT) {
			FieldNum[0].parentNode.style.backgroundColor=BACKGROUND_COLOR;
			FieldNum[0].parentNode.style.color=TEXT_COLOR;
		}
	}
	if(APPEND_WARNING) {
		warningDiv = document.createElement("div");
		warningDiv.id="warning_"+name;
		warningDiv.style.color=WARNING_COLOR;
		warningDiv.style.display="inline";
		warning = document.createTextNode(WARNING_SYMBOL);
		warningDiv.appendChild(warning);
		if(document.getElementById("warning_"+name)) {
			//we do not add the warning again so just pass
		}
		else {
			FieldNum[0].parentNode.appendChild(warningDiv);
		}
	}
}


function hideError(name) {
	var t=document.getElementById('error_'+name);
	new Effect.Fade(t);
    var FieldNum = document.getElementsByName(name);
	if(FieldNum.length==1){
		var highlightField=document.getElementById(name);
		var actualClassNames=highlightField.className.split(" ");
		highlightField.className=actualClassNames[0];
	}
	else {
		FieldNum[0].parentNode.style.backgroundColor="";
		FieldNum[0].parentNode.style.color="";
	}
	if(document.getElementById("warning_"+name)) {
		FieldNum[0].parentNode.removeChild(document.getElementById("warning_"+name));
	}
}

addLoadEvent(applyValidation);
