/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
* Check Form Script 																																	*
* Version: 2.0																																				*
* Supported field types:	Text																												*
*													[+|-][int]Number[(Digits)]																	*
*													Email																												*
*													Date																												*
*													Checkbox																										*
*													Radio																												*
*																																											*
*	04.03.04	MaAeb		Allow coexistence of several forms																*
*	18.03.04	MaAeb		Problems with NN4.x solved																				*
*	02.04.04	MaAeb		FormObject.fieldFocus('fieldName') as shortcut to									*
*										FormObject.formFields.fieldName.fieldFocus()											*
*										FormObject.addField() replaced with FormObject.newField()					*
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/****************************\
* Object: Form to be checked *
\****************************/
function checkForm(formName,messageHead) {
	this.form							=	document[formName];		var formChecked	=	this.form;
	this.formFields				=	new Array();
	this.messageHead			=	messageHead;
	var regNumberFormat	= /^([\+\-])?([a-z]+[a-z0-9]*)?(number)(\(([0-9]+)\))?$/;
	
	function submitForm(direct_error,empty_field) {
		if (this.validateForm(direct_error,empty_field))
			this.form.submit();
	}
	this.submitForm = submitForm;
	
	
	////// ADD FIELD TO FORM - DEPRECATED //////
	function addField(fieldName,defVal,msgText,required,condition,type) {
		this.formFields[fieldName]	= new formField(fieldName,defVal,msgText,required,condition,type);
	}
	this.addField = addField;
	
	////// ADD FIELD TO FORM - DEPRECATED //////
	function newField(fieldName,fieldMsgText,fieldRequired,fieldType,fieldDefVal,fieldCondition) {
		if (!fieldMsgText)
			fieldMsgText		=	"";
		if (!fieldRequired)
			fieldRequired		=	false;
		if (!fieldType)
			fieldType				=	"text";
		if (!fieldDefVal)
			fieldDefVal			=	"";
		if (!fieldCondition)
			fieldCondition	=	"";
		this.formFields[fieldName]	= new formField(fieldName,fieldDefVal,fieldMsgText,fieldRequired,fieldCondition,fieldType);
	}
	this.newField = newField;
	


			/********************\
			* Object: Form field *
			\********************/
			function formField(fieldName,defVal,msgText,required,condition,type) {
				this.name				=	fieldName;
				this.field			=	formChecked[fieldName];
				this.defVal			=	defVal;
				this.msgText		=	msgText;
				this.required		=	required;
				this.condition	=	condition;
				this.type				=	type.toLowerCase();
				
				function trim(value) {
				   var temp = value+" ";
					 temp = temp.replace(/^\s*/,"").replace(/\s* $/,"");
				   return temp;
				}
				this.trim =	trim;
				
				function fieldFocus() {
					if (this.type != 'radio' && this.type != 'checkbox') {
						if(trim(this.field.value) == this.defVal) {
							this.field.value = '';
						}
					}
					if (this.field.focus)
						this.field.focus();
				}
				this.fieldFocus =	fieldFocus;
				
				function fieldBlur() {
					if (this.type != 'radio' && this.type != 'hidden' && trim(this.field.value) == "" && this.defVal != "")
						this.field.value = this.defVal;
				}
				this.fieldBlur =	fieldBlur;
				
				////// CHECK FIELD EMPTY OR DEFAULT VALUE //////
				function checkDefault() {
					if (this.type == "radio") {
						var checked = false;
						for (var i = 0; i < this.field.length; i++) {
							if (this.field[i].checked)
								checked = true;
						}	
						return !checked;
					} else if (this.type == "checkbox") {
						var checked = false;
						if(this.field.length > 1) {
							for (var i = 0; i < this.field.length; i++) {
								if (this.field[i].checked)
									checked = true;
							}
						} else {
							if (this.field.checked)
								checked = true;
						}
						return !checked;
					} else if (trim(this.field.value) != this.defVal && trim(this.field.value) != "") {
						return false;
					} else {
						return true;
					}
				}
				this.checkDefault =	checkDefault;
				
				////// TYPE DEPENDING INPUT VALIDATION //////
				if (this.type == "date") {
					function callCheckDate() {
						var checkedDate	= checkDate(this.field.value);
						if (checkedDate)
							this.field.value	= checkedDate;
						return checkedDate;
					}
					this.typeCheck = callCheckDate;
				} else if (this.type == "email") {
					function callCheckEmail() {
						return checkEmail(this.field.value);
					}
					this.typeCheck = callCheckEmail;
				} else if (regNumberFormat.exec(this.type)) {
					function callCheckNumber() {
						var checkedNumber	= checkNumber(this.field.value,this.type);
						if (checkedNumber)
							this.field.value	= checkedNumber;
						return checkedNumber;
					}
					/*function returnFalse(){
						alert("number");
						return true;
					}*/
					this.typeCheck = callCheckNumber;/*returnFalse;*/
				} else {
					function returnTrue() {
						return true;
					}
					this.typeCheck = returnTrue;
				}
				
				/*//Check if field has to be checked
				function toBeChecked() {
					if (this.required || !this.checkCondition) {
						return true;
					} else
						return false;
				}
				this.toBeChecked = toBeChecked;*/
				
				function checkCondition() {
					if (this.required && this.checkDefault()) {
						return false;
					} else if (this.condition != '' && !eval(this.condition)) {
						return false;
					} else {
						return true;
					}
				}
				this.checkCondition = checkCondition;
			}
			this.formField = formField;
	
	
	
	// Form validation //
	// --------------- //
	function fieldFocus(fieldName) {
		this.formFields[fieldName].fieldFocus();
	}
	this.fieldFocus	= fieldFocus;
	
	function fieldBlur(fieldName) {
		this.formFields[fieldName].fieldBlur();
	}
	this.fieldBlur	= fieldBlur;
	
	
	
	// Form validation //
	// --------------- //
	function validateForm(direct_error,empty_field) {
		errorField = new Array();
		errorMsg = this.messageHead;
		
		function errorHandling(formField) {
			if (direct_error) {
				alert(formField.msgText);
				//errorField.push(myform[field]);
				errorField[errorField.length] = formField;
				formField.fieldFocus();
			} else {
				//errorField.push(myform[field]);
				errorField[errorField.length] = formField;
				errorMsg += formField.msgText;
			}
		}
	
		for (fieldName in this.formFields) {
			formField	=	this.formFields[fieldName];
			if (formField.checkDefault()) { //Field value is empty or default value
				if (!formField.checkCondition()) { //Field is required or has a condition
					errorHandling(formField); //Error output/storing
					if (direct_error) //If direct error output is enabled
						break; //Stop checking
				}	else {
					if (empty_field)
						formField.field.value = '';
				}
			} else if (!formField.typeCheck()) {
				errorHandling(formField); //Error output/storing
				if (direct_error) //If direct error output is enabled
					break; //Stop checking
			}
			else if (!formField.checkCondition()) { //If condition is false
				errorHandling(formField); //Error output/storing
					if (direct_error) //If direct error output is enabled
						break; //Stop checking
			}
		}

		if (errorField.length == 0) {
			return true;
		} else {
			for (fieldName in this.formFields) {
				var formField	= this.formFields[fieldName];
				formField.fieldBlur();
			}
			if(!direct_error)
				alert(errorMsg);
			errorField[0].fieldFocus();
			return false;
		}
	}
	this.validateForm = validateForm;
	
	////// CHECK EMAIL ADDRESS //////
	function checkEmail(address) {
		//var reg_email = /^.+@.+\..{2,}$/;
		var reg_email = /^[\w](([_\.-]?[\w]+)*)@([\w]+)(([\.-]?[\w]+)*)\.([A-Za-z]{2,})$/;
		if (reg_email.exec(address))
			return true;
		else
			return false;
	}
	this.checkEmail = checkEmail;

	////// NUMBER VALIDATION //////
	function checkNumber(checkNumber,checkFormat) {
		var number					=	Number(checkNumber.replace(/,/,"."));
		var number_format		= regNumberFormat.exec(checkFormat)
		//invalid number format or not a number
		if (!number_format || !number) {
			return false;
		} else {
			var numType						=	(number_format[2])?number_format[1]:"float";
			var numPosNeg					=	number_format[1];
			var numDigits					=	(number_format[5])?Number(number_format[5]):0;
			//not an integer
			if (numType == "int" && Math.floor(number) < number) {
				return false;
			//positive or negative number
			} else if ((numPosNeg == "+" && number < 0) || (numPosNeg == "-" && number > 0)) {
				return false;
			} else if (numDigits > 0) {
				// integer value too high
				if (numType == "int" && Math.abs(number) >= Math.pow(10,numDigits)) {
					return false;
				// round float value on x digits
				} else {
					number = Math.round(number*Math.pow(10,numDigits))/Math.pow(10,numDigits);
				}
			}
			return number;
		}
		return false;
	}
	this.checkNumber = checkNumber;
	
	////// DATE VALIDATION //////
	function checkDate(checkDate) {
		//initialization	
		var passed					=	true;
		var reg_date_format	=	/^([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{2}|[0-9]{4})$/;
		var day							=	0;
		var month						=	0;
		var year						=	0;
		//get number of days in month
		function getDaysInMonth(month,year)  {
		 	var days;
		  if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)  
				days = 31;
			else if (month==4 || month==6 || month==9 || month==11) 
				days = 30;
		  else if (month==2)  {
				if (isLeapYear(year))
					days = 29;
				else
					days = 28;
		  }
			return (days);
		}
		//check to see if year is a leap year
		function isLeapYear (Year) {
		  if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) {
		     return (true);
		  } else {
			  return false;
		 	}
		}
		//date-check routine
		//check if the date has a valid format
		var a_checkDate = reg_date_format.exec(checkDate);
		if (!a_checkDate)
			passed = false;
		if (passed) {
			day = Number(a_checkDate[1]);
			month = Number(a_checkDate[2]);
			year = Number(a_checkDate[3]);
			//check day, month and year
			var maxDaysInMonth = getDaysInMonth(month,year);
			if ((day > 0 && day <= maxDaysInMonth) && (month > 0 && month <= 12) && ((year >= 0 && year <= 99) || (year >= 1000 && year <= 9999))) {
				//if the year is entered in the short form: if greater than 20 insert 19 else 20 in front of the year
				if (year <= 99) {
					if (year >= 20)
						year = 1900+year;
					else
						year = 2000+year;
				}
				passed = true;
			} else {
				passed = false;
			}	
		}	
		if (!passed) {
			return false;
		}
		return ((day<=9)?"0":"")+day+'.'+((month<=9)?"0":"")+month+'.'+year;
	}
	this.checkDate = checkDate;
}
