// Declare the function "setRequiredObj". This sets the text for the required span tag.
// The span tags should normally be positioned next to the form element with a class value of "required" and be empty.
function setRequiredObj(el, set, text){
	// This function accepts THREE parameters.
	// "el" - This is the current form field that is being validated.
	// "set" - This should be a BOOLEAN value and is used to determine if the required text is to be SET or CLEARED.
	// "text" - This is the text that should be used within the required span tag. 
	//			This will only be used if "set" has a TRUE value.
	//			The default value for an empty "text" string is "&nbsp;*&nbsp;Required";
	// Assign the parent object of the current element "el" to the "obj" varaible
	var obj = el.parentNode;
	// Check to see if the "obj" element has any child nodes.
	if(obj.hasChildNodes()){
		// Loop through each of the child nodes in the "obj" element.
		for(i=0; i<obj.childNodes.length; i++){
			// Get the current child node and assign it to the varaible "child".
			var child = obj.childNodes[i];
			// Check to see if the "child" "nodeName" property is EQUAL to "span" and the class name is EQUAL to "required".
			if(child.nodeName.toLowerCase() == "span" && child.className == "required"){
				// Check to see if the element is to be "set" or not
				if(set == true){
					// Check to see if the "text" variable is EQUAL to an empty string.
					if(text == ""){
						// Set the text for the required span tag using the default value.
						child.innerHTML = "&nbsp;*&nbsp;Required";
					}
					else{
						// Set the text for the required span tag using the "text" variable.
						child.innerHTML = text;
					}
					// End of IF Else statement.
				}
				else{
					// Clear the text for the required span tag.
					child.innerHTML = "";
				}
				// End of IF Else statement.
			}
			// End of IF statement.
		}
		// End of FOR Loop.
	}
	// End of IF statement.
}
// End of function "setRequiredObj()".

function markInvalid(el){
	// Increment the "errCount" varaiable by ONE.
	errCount++;
	// Set the "required" text.
	setRequiredObj(el, true, "");
	// Focus the "el" element (but only if the element type is NOT hidden).
	if(el.type !== "hidden") el.focus();
}
// End of function "markInvalid()".

function clearRequired(){
	// Get all of thew SPAN tags.
	var reqTags = document.getElementsByTagName("span");
	// Check to see if there is at least 1 SPAN tag returned.
	if(reqTags.length > 0){
		// Loop through each of the SPAN tags.
		for(i=0; i<reqTags.length; i++){
			// Check to see if the class name of the current SPAN tag is equal to "required".
			if(reqTags[i].className == "required"){
				// Remove the text that was in the current SPAN tag.
				reqTags[i].innerHTML = "";
			}
			// End of IF statement.
		}
		// End of FOR Loop.
	}
	// End of IF statement.
}
// End of function "clearRequired()".

function checkFormElement(el){
	// Check to see if the "type" property is available.
	if(el.type){
		// The "type" property is available.
		// Select the "type" property of the "el" element (in lowercase).
		switch(el.type.toLowerCase()){
			// Text element.
			case "text":
				// check to see if the value property of the "el" element is EQUAL to an empty string.
				if(el.value == ""){ markInvalid(el); } else{ setRequiredObj(el, false, ""); }
				break;
			// TextArea element.
			case "textarea":
				// check to see if the value property of the "el" element is EQUAL to an empty string.
				if(el.value == ""){ markInvalid(el); } else{ setRequiredObj(el, false, ""); }
				break;
			// Hidden element.
			case "hidden":
				// check to see if the value property of the "el" element is EQUAL to an empty string.
				if(el.value == ""){ markInvalid(el); } else{ setRequiredObj(el, false, ""); }
				break;
			// Checkbox element
			case "checkbox":
				// check to see if the checked property of the "el" element is TRUE.
				if(el.checked == false){ markInvalid(el); } else{ setRequiredObj(el, false, ""); }
				break;
			// Select element
			case "select-one":
				// Check to see if the "selectedIndex" property is LESS than or EQUAL to ZERO.
				if(el.selectedIndex <= 0){ markInvalid(el); } else{ setRequiredObj(el, false, ""); }
				break;
			// All other element types.
			default:
				// Do nothing (for now).
		}
		// End of SWITCH statement.
	}
	else{
		// The "type" property is NOT available.
		// Check to see if "el" has a length property.
		// And also if the length property is greater than ZERO.
		if(el.length && el.length > 0){
			// The variable "el" is a set of RADIO elements.
			var radioChecked = false;
			// Loop through each of the elements in the radio set.
			for(i=0; i<el.length; i++){
				// Check to see if the current radio element's "checked" property is set to TRUE.
				// If this is the case then assign the "radioChecked" varaible a TRUE value,
				// which will indicate that there is a radio element that was checked.
				if(el[i].checked == true) radioChecked = true;
			}
			// End of FOR Loop.
			// Check to see if one of the radio elements in the current set has been checked or not.
			// And call the relevant functions.
			if(radioChecked == false){ markInvalid(el[0]); } else{ setRequiredObj(el[0], false, ""); }
		}
		// End of IF statement.
	}
	// End of IF Else statement.
}
// End of function "checkFormElement()".

function isValidEmail(email){
	// Declare "emailValid" as a local varaible and initialise it to FALSE.
	var emailValid = false;
	// Check to see if the "email" is avaialble and if it DOESN'T have an empty string value.
	if(email && email !== "" && email.indexOf(" ", 0) < 0 && email.indexOf("@", 0) >= 0){
		// Build the EMAIL Regular Expression.
		//var emailRE = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/
		var emailRE = /^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z\d]{2,4})(\.[a-zA-Z\d]{2})?)$/;
		// Test the EMAIL string against the regualr expresion to see if the format is valid.
		if(emailRE.test(email)) {
			// Email format IS valid.
			emailValid = true;
		} 
		// End of IF statement.
	}
	// End of IF statement.
	
	// Return TRUE or FALSE, depending on whether or not the EMAIL is valid or not.
	return emailValid;
}
// End of function "isValidEmail()"

function validateDate(sDate, iDate){
	// "sDate" is the date to be validated.
	// "iDate" is the date that it will be validated against 
	// i.e it is to be used to determine if the "sDate" is in the past, present or future.
	// Check to see if "iDate" is an empty string.
	if(iDate == ""){
		// "iDate" is an empty string.
		// Use the current date as the default date for "iDate".
		// Get the current date in the instance called "nDate".
		var nDate = new Date();
		// Get the day of the month.
		var nDay = nDate.getDate();
		// Get the month of the year
		var nMonth = nDate.getMonth()+1;
		// Get the year.
		var nYear = nDate.getFullYear();
		// Rebuild the date in the format: "dd/mm/yyyy" and assign it to the varaible "iDate".
		iDate = nDay+"/"+nMonth+"/"+nYear;
	}
	// End of IF statement.
	// In order to validate the date, the function will send a request to along with both dates.
	// This will determnine whether the "sDate" varaible is in the PAST, FUTURE, TODAY or is INVALID.
	// Once this has been determined, an XML Document will be returned with information regarding the date.
	// The XML format is as follows: <date value="14/10/2008" formated="Tuesday 14th October 2008">today</date>
	// ##--NOTE--##
	// Although the request is using AJAX, the request is NOT made in assychronous mode.
	// ##--END NOTE--##
	// Build the url that point to the file that the request is to be sent to.
	var url = "/xml/ValidateDateXML.asp";
	// Append the appropriate query string varaibles.
	url += "?date="+sDate;
	url += "&diffdate="+iDate;
	// Get the XML Document.
	var xmlObj = getXMLDocument(url);
	// Get the "date" tag (this is also the root element).
	var dateObj = xmlObj.getElementsByTagName("date");	
	// Get the "formatted" attribute
	// This is the date in a more user friendly format.
	var fDate = dateObj[0].getAttribute("formated");
	// Get the Date information
	var info = getNodeValue(dateObj[0]);
	// Return the date information and the formated date as an array.
	return [info, fDate];
}
// End of function "validateDate()".

function validateReportForm(myForm){
	// Reset the "errCount".
	// This will be used to count the number of submission errors.
	errCount = 0;
	
	// Validate all of the relevant form fileds.
	// Start from the bottom element and work up.
	// This way the last validated form field in FOCUS will be the top most element.	
	
	// Validate the "HasImages" Radio elements.
	checkFormElement(myForm.HasImages);
	// Validate the "DumpedInWater" Radio elements.
	checkFormElement(myForm.DumpedInWater);
	// Validate the "DumpedQuantity" field.
	checkFormElement(myForm.DumpedQuantity);
	// Validate the "DumpedItemTypes" field.
	checkFormElement(myForm.DumpedItemTypes);
	// Check to see if the "DumpedItemTypes" field has a valid option selected.
	if(myForm.DumpedItemTypes.selectedIndex > 0){
		// A valid option was selected.
		// Check to see if the selected value is equal to "other".
		if(myForm.DumpedItemTypes.value.toLowerCase() == "other"){
			// // The other option was specified.
			// Validate the "DumpedItemTypesOther" field.
			checkFormElement(myForm.DumpedItemTypesOther);
		}
		else{
			// Set the "required" text.
			setRequiredObj(myForm.DumpedItemTypesOther, false, "&nbsp;");
		}
		// End of IF Else statement.
	}
	// End of IF statement.
	
	if(myForm.VehicleNoOccupants.value !== ""){
		if(isNaN(myForm.VehicleNoOccupants.value)){
			// Increment the "errCount" varaiable by ONE.
			errCount++;
			// Set the "required" text.
			setRequiredObj(myForm.VehicleNoOccupants, true, "&nbsp*&nbsp;Must be a number");
			// Focus the "el" element.
			myForm.VehicleNoOccupants.focus();
		}
		else{
			setRequiredObj(myForm.VehicleNoOccupants, false, "");	
		}
	}
	
	// Validate the "UsedVehicle" Radio elements.
	checkFormElement(myForm.UsedVehicle);
	// Validate the "AnotherWittness" Radio elements.
	checkFormElement(myForm.AnotherWittness);
	// Validate the "NearestTown" field.
	checkFormElement(myForm.NearestTown);
	// Validate the "Location" field.
	checkFormElement(myForm.Location);
	// Check to see if the "DumpDate" field is NOT an empty string.
	if(myForm.DumpDate.value !== ""){
		// The "DumpDate" field is to be validated to make sure that the value is a valid date.
		// Get the date info for the "DumpDate".
		var dateInfo = validateDate(myForm.DumpDate.value, "");
		
		//window.alert(dateInfo[0]);
		// Check to see if the date is NOT in the past and is NOT today.
		if(dateInfo[0].toLowerCase() !== "past" && dateInfo[0].toLowerCase() !== "today"){
			// The date is INVALID.
			// Increment the "errCount" varaiable by ONE.
			errCount++;
			// Set the "required" text.
			setRequiredObj(myForm.DumpDate, true, "&nbsp*&nbsp;Invalid");
			// Focus the "el" element.
			myForm.DumpDate.focus();
		}
		else{
			// Reset the "required" span tag.
			setRequiredObj(myForm.DumpDate, false, "");	
		}
		// End of IF Else statement.
	}
	else{
		// Reset the "required" span tag.
		setRequiredObj(myForm.DumpDate, false, "");	
	}
	// End of IF Else statement.
	// Validate the "DumpingNow" Radio elements.
	checkFormElement(myForm.DumpingNow);
	// Validate the "Email" field.
	checkFormElement(myForm.Email);
	if(myForm.Email.value !== ""){
		// validates to make sure the email is in the proper format (i.e. someone@mydomain.com)
		if(isValidEmail(myForm.Email.value) == false){
			// Increment the "errCount" varaiable by ONE.
			errCount++;
			// Set the "required" text.
			setRequiredObj(myForm.Email, true, "&nbsp*&nbsp;Invalid");
			// Focus the "el" element.
			myForm.Email.focus();
		}
		else{
			// Reset the "required" span tag.
			setRequiredObj(myForm.Email, false, "&nbsp;");
		}
		// End of IF Else statement.
	}
	// End of IF statement.
	
	// Check to see if the "errCount" varaible is GREATER than ZERO.
	if(errCount > 0){
		// There are submission errors.
		// At least one field was not filled.
		window.alert("You MUST fill in all of the required fileds.");
		return false;
	}
	else{
		// There are NO submission errors.
		// All required fileds were filled.
		submitForm(myForm);
		return false;
	}
	// End of IF Else statement.
}
// End of function "validateReportForm()".

function validateContactForm(myForm){
	// Reset the "errCount".
	// This will be used to count the number of submission errors.
	errCount = 0;
	
	// Validate all of the relevant form fileds.
	// Start from the bottom element and work up.
	// This way the last validated form field in FOCUS will be the top most element.
	
	// Validate the "cMessage" field.
	checkFormElement(myForm.cMessage);
	// Validate the "cEmail" field.
	checkFormElement(myForm.cEmail);
	if(myForm.cEmail.value !== ""){
		// validates to make sure the email is in the proper format (i.e. someone@mydomain.com)
		if(isValidEmail(myForm.cEmail.value) == false){
			// Increment the "errCount" varaiable by ONE.
			errCount++;
			// Set the "required" text.
			setRequiredObj(myForm.cEmail, true, "&nbsp*&nbsp;Invalid");
			// Focus the "el" element.
			myForm.cEmail.focus();
		}
		else{
			setRequiredObj(myForm.cEmail, false, "");
		}
		// End of IF Else statement.
	}
	// End of IF statement.
	// Validate the "cName" field.
	checkFormElement(myForm.cName);
	
	// Check to see if the "errCount" varaible is GREATER than ZERO.
	if(errCount > 0){
		// There are submission errors.
		// At least one field was not filled.
		window.alert("You MUST fill in all of the required fileds.");
		return false;
	}
	else{
		// There are NO submission errors.
		// All required fileds were filled.
		submitForm(myForm);
		return false;
	}
	// End of IF Else statement.
}
// End of function "validateContactForm()".

// Declare the GLOBAL variable "errCount" and initialise it to ZERO.
// This will be used to count the number of form validation errors.
var errCount = 0;