
/*******************************
 *                             *
 *   Form Validation Script    *
 *                             *
 *******************************/

/*  form elements:
	document.myform
	document.myform.useful
	document.myform.fName
	document.myform.lName
	document.myform.address
	document.myform.city
	document.myform.state
	document.myform.zip
	document.myform.buyBook[0] ... SUV history
	document.myform.buyBook[1] ... sports cars and Daimler-Benz
	document.myform.buyBook[2] ... History of Daimler-Benz
	document.myform.creditCard[0] ... visa
	document.myform.creditCard[1] ... mc
	document.myform.creditCard[2] ... disc
	document.myform.creditCard[3] ... amex
	document.myform.cardNumber
	document.myform.expireDate
	document.myform.shipping[0] ... ups
	document.myform.shipping[1] ... usps
	document.myform.shipping[2] ... fedex
	document.myform.emailAdd
	document.myform.pword1
	document.myform.pword2
	document.myform.comments
 */
 
 
// Error Messages
err_fName = "You must include your FIRST NAME.\n";
err_lName = "You must include your LAST NAME.\n";
err_address = "You must include your STREET ADDRESS.\n";
err_city = "You must include your CITY name.\n";
err_state = "You must include your STATE code.\n";
err_state_valid = "Your STATE code can only be TWO LETTERS.\n";
err_zip = "You must include your ZIP CODE.\n";
err_zip_valid = "Your ZIP CODE must be FIVE NUMBERS.\n";
err_buyOne = "You must BUY at least ONE BOOK.\n";
err_cardNumber = "You must include a valid CREDIT CARD NUMBER.\n";
err_cardNumber_valid = "Your CREDIT CARD NUMBER must contain NUMBERS ONLY.\n";
err_expireDate = "You must include a valid EXPIRATION DATE.\n";
err_expireDate_valid = "Your EXPIRATION DATE must be in the format 'MM/YY'.\n";
err_shipping = "You must choose a SHIPPING OPTION.\n";
err_emailAdd = "You must include valid EMAIL ADDRESS.\n";
err_pword = "You must enter the same PASSWORD TWICE for verification.\n";
err_pword_valid = "Your PASSWORD may only contain LETTERS or NUMBERS.\n";
err_pword_match = "Your PASSWORDS do not MATCH--please retype them.\n";


// Error Counter
var error_count = 0;


// The Overall Error Message
var error_message = '';

 
// String Check #1
//   simply check to see if the examined string does not have a null value
//	 this should be done now for: fName, lName, address, city, state, zip
//   and for handling the password fields later
function checkPersonalInfo () {
	var infoFields = new Array('fName', 'lName', 'address', 'city', 'state', 'zip');
	for (i = 0; i < infoFields.length; i++) {
		theField = eval('document.myform.' + infoFields[i]);
		if (theField.value == '') {                                        // there is an error!
			error_count++;                                                 // add one to the error count
			addMessage = eval('err_' + infoFields[i]);                     // put together the name of the error
			error_message += addMessage;                                   // put the error into the error message gatherer
			alert(error_message);                                          // just to check to see if it is working
		}
	}
}


// Form Element Check #1
//   not all form elements gather user-entered strings
//   checkboxes and radio buttons need to be checked
function checkBookPurchase () {                                            // see if each of the books isn't checked
	var book_count = 0;
	for (i = 0; i < document.myform.buyBook.length; i++) {
		if (document.myform.buyBook[i].checked) book_count++;              // count the number of books checked
	}
	
	if (book_count == 0) {                                                 // false if even one is checked
			error_count++;                                                 // add one to the error count
			error_message += err_buyOne;                                   // put the error into the error message gatherer
			alert(error_message);                                          // just to check to see if it is working
	}
}


// String Check #2
//   see how many characters there are in the string by accessing the length property
//   do this for the credit card number
//   it must be 16 for the first three cards, 15 for the last
function checkCreditLength () {
	var error_flag = false;                                                // flag to see if there is a problem
	if (!document.myform.creditCard[3].checked) {                          // if NOT amex, it must be 16
		if (document.myform.cardNumber.value.length != 16) error_flag = true;
	} else {                                                               // it must be 15
		if (document.myform.cardNumber.value.length != 15) error_flag = true;
	}

	if (error_flag) {                                                      // then register the error...
		error_count++;                                                     // add one to the error count
		error_message += err_cardNumber;                                   // put the error into the error message gatherer
		alert(error_message);                                              // just to check to see if it is working
	}
}


// String Check #3
//   if the credit card number is the correct length
//   we need to make sure that there are only numbers
function checkCreditValid () {
	var error_flag = false;                                                // flag to see if there is a problem
	for (i = 0; i < document.myform.cardNumber.value.length; i++) {                 // go character by character
		if (isNaN(document.myform.cardNumber.value.charAt(i))) error_flag = true;   // is it Not a Number? (NaN) flag an error
	}

	if (error_flag) {                                                      // then register the error...
		error_count++;                                                     // add one to the error count
		error_message += err_cardNumber_valid;                             // put the error into the error message gatherer
		alert(error_message);                                              // just to check to see if it is working
	}
}


// String Check #4
//   check to see if we have a valid expiration date
//   we first need to check to see if there are 5 characters, then
//   we need to make sure that there are 2 numbers, a slash, two numbers
function checkExpireValid () {
	var skipTwo = false;
	// part one: check the length
	if (document.myform.expireDate.value.length != 5) {
		error_count++;                                                     // add one to the error count
		error_message += err_expireDate;                                   // put the error into the error message gatherer
		alert(error_message);                                              // just to check to see if it is working
		skipTwo = true;                                                    // don't do the second half of this function
	}
	
	if (skipTwo == false) {                                                    // then do it! could also say (!skipTwo)
		// part two: check the characters
		var error_flag = false;                                                // flag to see if there is a problem
		for (i = 0; i < document.myform.expireDate.value.length; i++) {        // go character by character
			if (isNaN(document.myform.expireDate.value.charAt(i))) {           // is it not Not a Number? (NaN) flag an error unless
				if ((i == 2) && (document.myform.expireDate.value.charAt(i) != '/')) error_flag = true;  // the third char is a slash
			}
		}
		
		if (error_flag) {                                                      // then register the error...
			error_count++;                                                     // add one to the error count
			error_message += err_expireDate_valid;                             // put the error into the error message gatherer
			alert(error_message);                                              // just to check to see if it is working
		}
	}
}


// Form Element Check #2
//   similar to the book boxes above
//   one radio button for shipping must be selected
function checkShippingInfo () {                                            // see if one shipping method is checked
	var error_flag = true;                                                 // reverse psychology ... set to false if one is checked
	for (i = 0; i < document.myform.shipping.length; i++) {                // go button by button
		if (document.myform.shipping[i].checked) error_flag = false;       // only need one to remove the flag
	}
	
	if (error_flag) {                                                      // then register the error...
		error_count++;                                                     // add one to the error count
		error_message += err_shipping;                                     // put the error into the error message gatherer
		alert(error_message);                                              // just to check to see if it is working
	}
}


/* Do it yourself!
   Time to check the email and passwords, which are an optional part of the form
   The function below has the reasoning, not the JS, typed in.
function checkAddAccount () {
	// part one: is the email valid? only check if it is present!
	// look at each character in the email value
	// is there an @ sign and is it at least the second character?
	// count that as good enough
	
	// part two-a: only do this if the email is present AND valid!
	// check the value of each password field
	// if it has the right range of characters and no punctuation or white space
	// then it is valid
	
	// part two-b: only do this if part two-a is passed
	// compare the values of the two password fields
	// if not the same, then there is an error!
	
	// Question: two-b should be easier to check than two-a...
	//           So why should you do two-a first?
}
*/


// The Grande Finale!
// Putting it all together: the validateForm() function
function validateForm() {
	checkPersonalInfo ();
	checkBookPurchase ();
	checkCreditLength ();
	checkCreditValid ();
	checkExpireValid ();
	checkShippingInfo ();
	// checkAddAccount ();
	
	if (error_count == 0) {
		return true;  // comment removed here---- uncomment this line and comment out the next two to submit form
		// comment added--- alert('Your form data is valid!');                                 // since we aren't going to actually submit it
		// comment added--- return false;                                                      // we need an announcement that everything is ok
	} else {
		if (error_count == 1) {
			error_message = 'There is ' + error_count + ' error in your form.\nPlease check this and resubmit your form:\n\n' + error_message;		
		} else {
			error_message = 'There are ' + error_count + ' errors in your form.\nPlease check these and resubmit your form:\n\n' + error_message;	
		}
		alert (error_message);
		if (document.getElementById) {
			alert('DOM compliant')
			document.getElementById("errorbox").innerText = error_message;
		} else if (document.all) {
			alert('IEDOM compliant')
			document.all.errorbox.innerText = error_message;
		}
		error_count = 0;					                               // reset the counter and the error message gatherer
		error_message = '';
		return false;                                                      // prevent form from submitting
	}
}


