// JavaScript Document
// Last modified 20091201 ge 
//  function library for notify.html

function checkPhone(phonenumber) {
	// check if a phone number has enough digits
	// return true if apparently ok
	// return false if clearly not enough digits
	var i;
	var digitcount = 0;
	var length = phonenumber.length;
	
	// first chop off any 707 at the beginning
	if (phonenumber.substr(0,3) == "707") {
		phonenumber = phonenumber.substr(3);
	}
	if (phonenumber.substr(0,5) == "(707)") {
		phonenumber = phonenumber.substr(5);
	}
	
	// now check for alphanumerics (1-800-LIBRARY is fine)
	for (i=0; i<length; i++) {
		if (phonenumber.charAt(i).match(/\w/)) {
			// increment digit count if a digit or letter is found
			digitcount++;
		} // end if
	} // end for

	// check if the total is less than 7
	if (digitcount < 7) {
		return false; //false;
	} 
	else {
		return true; //true;
	}
} // end function

function checkNotify(formname) {
	// run the generic required fields check
	// plus a couple of notify-specific checks
	
	var PIN = document.forms[formname]["New_PIN"].value;
	var phone = document.forms[formname]["Patron_Phone"].value;
	var phonereq = document.forms[formname]["Patron_Phone"].className == "required";

	// reset PIN field style in case this is the second time through this form
	document.forms[formname]["New_PIN"].className = "unhighlight";

	if (checkRequiredFields(formname)) {
		// all required fields filled
		if (checkPIN(PIN)) {
			// PIN ok
			if (phonereq) {
				if (checkPhone(phone)) {
					return true;
				} // end if - checkPhone
				else {
					alert("Your phone number doesn't seem to be complete.  Please re-type it.");
					document.forms[formname]["Patron_Phone"].focus();
					return false;
				} // end else - checkPhone
			} // end if - phonereq
			else {
				// no phone required (they selected email)
				return true;
			} // end else - phonereq
		} // end if - checkPIN
		else {
			alert("Your new PIN must be exactly four digits 0 - 9.");
			document.forms[formname]["New_PIN"].className = "required";
			document.forms[formname]["New_PIN"].focus();
			return false;
		} // end else - checkPIN
	} // end if - checkRequiredFields
	
	else {
		return false;
	} // end else - checkRequiredFields
	
} // end function

function checkPIN(PIN) {
	// check if a PIN (if provided) is the correct number of digits
	// the only acceptable PINs are either blank (none submitted) or 4 digits

	var length = PIN.length;

	if (PIN.length != 4 && PIN.length !=0){
		return false;
	} // end if
	
	// now check the PIN is all numeric
	if (!(is_numeric(PIN))) {
		return false;
	} // end if

	// if we are still here in the function then no errors found
	return true;

} // end function

