var LABEL_ERROR_COLOR = 'red';
var LABEL_NORMAL_COLOR = 'black';
var ERROR_MSG_BOX = 'jsError';

//---------------------------------------
function validate(form, errorMsg) 
{
	var retVal = true;
	var fieldError = false;
	var retMsg = '';

	//Check all the input fields that have a valid label id
	var fields = form.getElementsByTagName("input");
    for (var i=fields.length-1; i>=0 ; i--) {
		fieldError = false;

		trim(fields[i]);

		//If the field is required check if the field is empty
		if (isRequired(fields[i])) {
			if (isEmpty(fields[i])) {
				retVal = false;
				fieldError = true;
				retMsg = errorMsg;
			}
		}


		//Check if the field needs to be validated
		if (!isEmpty(fields[i])) {
			if ((valType = getValidationType(fields[i])) != null) {
				switch (valType[1]) {
					case 'txt':
						break;
					case 'email':	//Check if the email field is well formed		
						if (!emailIsValid(fields[i])) {
							retMsg = "That doesn't appear to be a valid email address.";
							retVal = false;
							fieldError = true;
						}
						break;
					case 'int':
						//If we have a size for the field
						if (valType[2] == undefined || valType[2] == '') {
							if (!isInteger(fields[i])) {
								retMsg = "You must insert a positive number.";
								retVal = false;
								fieldError = true;
							}
						} else {
							if ((fields[i].value.length!=valType[2]) || !isInteger(fields[i])) {
								retMsg = "You must insert a "+valType[2]+" digit number.";
								retVal = false;
								fieldError = true;
							}
						}
						break;
					case 'date':
						if ((ret = isDate(fields[i])) != true) {
							if (ret == false) {
								retMsg = "You must insert a date with the format mm/dd/yyyy.";
							} else if (ret == -1){
								retMsg = "That date is not valid.";
							}
							retVal = false;
							fieldError = true;
						}
						break;
				}
			}
		}
		if (fieldError) {
			highlightLabel(fields[i], LABEL_ERROR_COLOR);
		} else {
			highlightLabel(fields[i], LABEL_NORMAL_COLOR);
		}


	}

	//Check all the textarea fields
	var fields = form.getElementsByTagName("textarea");
    for (var i=fields.length-1; i>=0 ; i--) {
		//If the field is required check if the field is empty
		if (isRequired(fields[i])) {
			if (isEmpty(fields[i])) {
				retVal = false;
				fieldError = true;
				retMsg = errorMsg;
				highlightLabel(fields[i], LABEL_ERROR_COLOR);
			} else {
				highlightLabel(fields[i], LABEL_NORMAL_COLOR);
			}
		}
	}

	if (retVal == false) {
		showError(retMsg);
	}

	return retVal;
 }

//---------------------------------------
// Returns the type of validation to be performed in a field
//---------------------------------------
function getValidationType(field) {
	var filter=/(?:((?:txt)|(?:pwd)|(?:email)|(?:int)|(?:date))(?:\(([\d]*)-*([\d]*)\))*)/i;
	
	found = field.className.match(filter);
	if ((found = field.className.match(filter)) != null) {
		return found;
	} else {
		return false;
	}
}

//---------------------------------------
// Returns true is the field is required or false otherwise
//---------------------------------------
function isRequired(field) {
	var filter=/required/i;
	
	return filter.test(field.className);
}

//---------------------------------------
// Returns true if the field is empty
//---------------------------------------
function isEmpty(field) {
	return field.value.length == 0;
}

//---------------------------------------
// Returns true is the field is an integer or false otherwise
//---------------------------------------
function isInteger(field) {
	var filter=/^[0-9]*$/;
	
	return filter.test(field.value);
}

//---------------------------------------
// Returns true is the field is a date formated as mm/dd/yyyy or false otherwise
//---------------------------------------
function isDate(field) {
	var filter=/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/;
	
	found = field.value.match(filter);
	if (found == null){
		return false;
	}
	if (found.length != 4){
		return false;
	}

	//Check the month
	if(found[1] < 1 || found[1] > 12){
		return -1;
	}
	//Check the day
	if(found[2] < 1 || found[2] > 31){
		return -1;
	}
	//Check the year
	if(found[3] < 1970 || found[3] > 2100){
		return -1;
	}
	//Check that it's a valid date 
	var myDate = new Date( found[3], found[1]-1, found[2] );
	var myDateArray = myDate.toGMTString().split( ' ' );

	if(Number(myDateArray[1]) != Number(found[2])) {
		return -1;
	}

	return true;
}



//---------------------------------------
// Returns true if the email adddress in the field is valid
//---------------------------------------
function emailIsValid(field) {
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

	if (!filter.test(field.value)) {
		return false;
	} else {
		return true;
	}
}

//---------------------------------------
// Returns true if the password fields are valid and match or false otherwise.
// The password must be at last between 5 and 15 characters long 
// and use letters, numbers and ~ ! @ # $ % \ ^ & * ( ) = ? (no spaces)
//---------------------------------------
function passwordIsValid(pass1, pass2, errMsg1, errMsg2) {
	var retVal = false;
	var filter=/^[A-Za-z0-9_~!@#$%\^&*()=?]{5,15}$/i;

	labelName1 = document.getElementById('lbl_'+pass1.name);
	labelName2 = document.getElementById('lbl_'+pass2.name);
	if (labelName1 == null) labelName1 = document.getElementById('x_lbl_'+pass1.name);
	if (labelName2 == null) labelName2 = document.getElementById('x_lbl_'+pass2.name);

	//Check if the password is valid
	if (!filter.test(pass1.value)) {
		if (labelName1 != null) labelName1.style.color = LABEL_ERROR_COLOR;
		if (labelName2 != null) labelName2.style.color = LABEL_ERROR_COLOR;
		pass1.focus();
		showError(errMsg1);
		retVal = false;
	} else {
		//Check if the password fields are the same
		if (pass1.value != pass2.value) {
			if (labelName1 != null) labelName1.style.color = LABEL_ERROR_COLOR;
			if (labelName2 != null) labelName2.style.color = LABEL_ERROR_COLOR;
			pass1.focus();
			showError(errMsg2);
			retVal = false;
		} else {
			if (labelName1 != null) labelName1.style.color = LABEL_NORMAL_COLOR;
			if (labelName2 != null) labelName2.style.color = LABEL_NORMAL_COLOR;
			retVal = true;
		}
	}
	return retVal;
}

//---------------------------------------
// Highlights a field label
// The label is assumed to have an id with the form 'lbl_'+field.name
//---------------------------------------
function highlightLabel(field, color) {
	fieldLabel = document.getElementById('lbl_'+field.name);
	if (fieldLabel != null) fieldLabel.style.color = color;
}

//---------------------------------------
// Shows an error message
//---------------------------------------
function showError(msg) {
	document.getElementById(ERROR_MSG_BOX).style.display = 'block';
	document.getElementById(ERROR_MSG_BOX).innerHTML = msg;
	document.location="#error";
}

//---------------------------------------
// Removes any spaces  at the begining of a field
//---------------------------------------
function leftTrim(field) {
	while(field.value.length > 0) {
		if (field.value.charAt(0) == ' '){
			field.value = field.value.slice(1);
		} else {
			break;
		}
	}
}

//---------------------------------------
// Removes any spaces  at the end of a field
//---------------------------------------
function rightTrim(field) {
	while(field.value.length > 0) {
		if (field.value.charAt(field.value.length-1) == ' '){
			field.value = field.value.slice(0, field.value.length-1);
		} else {
			break;
		}
	}
}

//---------------------------------------
// Removes any spaces at the begining and end of a field
//---------------------------------------
function trim(field) {
	leftTrim(field);
	rightTrim(field);
}
