// form_validator.js

// This script checks to see if the user has filled in the
// the form inputs corresponding to the list of mandatoryFields 
// below, then alerts the users as to which fields need to be
// filled in before the form action will take place...

function checkForm() { //returns true when all mandatory fields are filled
var notFilled = new Array(); //placeholder array
var current = 0; //incrementor for alerted array
var alerted = new Array(); //the names of the unfilled mandatory fields that fill up stringOutput

var stringOutput = new String(); //string to be alert()ed to user
	stringOutput = 'Please fill in the following fields before clicking \"Submit\": '

var mandatoryFields = new Array(); //array containing the id's of the inputs that are mandatory fields
mandatoryFields[11] = "first_name";
mandatoryFields[10] = "last_name";
mandatoryFields[9] = "email";
mandatoryFields[8] = "address";
mandatoryFields[7] = "city";
mandatoryFields[6] = "state";
mandatoryFields[5] = "zipcode";
mandatoryFields[4] = "country";
mandatoryFields[3] = "phone";
mandatoryFields[2] = "date_arrival";
mandatoryFields[1] = "date_departure";
mandatoryFields[0] = "attendees";

var fieldNames = new Array(); //the names of the mandatory fields that aren't filled in ( spelled as they are to be alert()ed to user )
fieldNames[11] = "First Name";
fieldNames[10] = "Last Name";
fieldNames[9] = "Email";
fieldNames[8] = "Address";
fieldNames[7] = "City";
fieldNames[6] = "State";
fieldNames[5] = "Zipcode";
fieldNames[4] = "Country";
fieldNames[3] = "Phone Number";
fieldNames[2] = "Date of Arrival";
fieldNames[1] = "Date of Departure";
fieldNames[0] = "Number of Attendees";
		
	for (var k=0; k<alerted.length; k++){ //delete all entries of alerted[] to start from scratch on each call to checkForm()
		alerted.pop(); 
	}
	
	if (!document.getElementById)
	return true;
	else
	for (var i=0; i<mandatoryFields.length; i++){
		if (document.getElementById(mandatoryFields[i]).value == '')
		notFilled[i]=fieldNames[i];
	}
	
	for (var j=0; j<notFilled.length; j++){
		if (notFilled[j]){
			alerted[current] = notFilled[j];
			current++;
		}
	}
	


//each case returns after alerting the user to which mandatory fields he/she has failed to fill in

	if (alerted[0]){ //if there is at least one mandatory field not filled in
		var notZero = 0;
		for(var k=alerted.length; k>=0; k--){
			if(alerted[k]){
				if(k>=0){
					if(notZero == 0){
						notZero++;
						stringOutput = stringOutput + alerted[k];
					}
					else(stringOutput = stringOutput + ', ' + alerted[k])
				}
				else {
					stringOutput = stringOutput + ', ' + alerted[k] + ' and ' + alerted[0] + '.'
				}
			}
		}
		alert(stringOutput);
		return false;
	}
	return true;
}
