//fv denotes field value

// Function to check for empty field
function isEmpty(fv) {
	return (fv =="" || fv == null)
	}
	
//function to check fof field that contain white space
function isWS(fv){
	// Whitespace characters definitions
	var ws = " \n\r\t"
	//looping each characters in the field string
	for (var i=0; i <fv.length; i++) {
		//Get the current character
		currChar = fv.charAt(i)
		//If non whitespace return false
		if (ws.indexOf(currChar) == -1) {
			return false
		}
	}
	// Otherwise there's whitespace int the field string
	return true
}

//function to check for wrong email format
function isEmail(fv) {
	//Creates Regular Expression
	var reExp = /^[a-z][\w\.]*@[\w\.]+\.[a-z]{2,3}/i
	if (reExp.test(fv)) {
		return true
	} else {
		return false
	}
}

// function to invoke all checking functions
function validate(thisForm) {
var errNum = new Array()
var errTtl = 0

// Check for empty fields
for (var i=0; i<thisForm.elements.length; i++) {
	if (thisForm.elements[i].type =="text" || thisForm.elements[i].type =="textarea") {
		var fldValue = thisForm.elements[i].value
		if (isEmpty(fldValue)||isWS(fldValue)) {
			errNum[errTtl] = thisForm.elements[i]
			errNum[errTtl].errType = " is not filled\n"
			errTtl++		
		} else {
			if (thisForm.elements[i].name == "Email") {
				if(!isEmail(fldValue)) {
					errNum[errTtl] = thisForm.elements[i]
					errNum[errTtl].errType = " address format is invalid\n     Correct format is in the form of\n     userid@your_domain_name\n"
					errTtl++	
				}
			}
		}		 
	}		
}

// Alert message if any empty field found
if (errTtl > 0) {
	var errMsg = "The following "+(errTtl ==1 ? "error was " : "errors were ")+
	             "found in the form you just send:"+
				 "\n______________________________\n\n"
	//Loop through missing fields
	for (var i=0; i<errNum.length;i++) {
		errMsg += "=> " + errNum[i].name + errNum[i].errType+"\n"
	}
	
	// Finish up & display the message
	errMsg += "\n______________________________\n\n"+
	          "Please ensure all fields are filled correctly and submit again."
	alert(errMsg)
	
	// Put focus on the first missing field
	errNum[0].select()
	return false
} else {
	// Enable form submission by returning true for server processing
	return true
	}
}	