//Form validator for Registration
//v1.0 ... (adjust after script is working but when new features are added)

//ERROR STRING LIST, place in include file eventually? If lots of errors certainly
namecounterr = "Field must contain at least two words";
addresscounterr = "Field must contain at least three words";
notnumericerr = "Field must contain only numbers";
beginsnumericerr = "Field must begin with a numeric address";
notalphaerr = "Field must contain only letters";
notnumericerr = "Field must contain only numbers";
bademailerr = "Must contain valid email address";

//Call script from onSubmit handler of any form. Pass it the subject and 

function validate(input) {
	err = "";
	switch(input.id) {
		case "name":
			if(!is_alpha(input))
				err += notalphaerr + "<br/>";
			if(!(wordcount(input) >= 2))
				err += namecounterr + "<br/>";
			break;
		case "address":
			if(!begins_numeric(input))
				err += beginsnumericerr + "<br/>";
			if(!(wordcount(input) >= 3))
				err += addresscounterr + "<br/>";
			break;
		case "phone":
			if(!is_numeric(input))
				err += notnumericerr + "<br/>";
			break;
		case "email":
			if(!IsEmailValid(input.form.id,input.id))
				err += bademailerr + "<br/>";
			break;
		case "descrip":
			break;
									
		default:	
			break;
	}
	
	insert(input, err);
	
	form = input.form;
	if(checkall(form)) {
		//re-enable submit button
		form.submit.disabled = false;
	}
	else
		form.submit.disabled = true;
}

//performs checks on all pertinent inputs and enables or leaves disabled the submit button
function checkall(theform) {
	with(theform) {
		if(
			wordcount(name) >= 2 &&
			is_alpha(name) &&
			begins_numeric(address) &&
			wordcount(address) >= 3 &&
			is_numeric(phone) &&
			IsEmailValid(theform.id, "email")
		)
			return true;			
		else
			return false;
	}
}

//Inserts error text before given form element
function insert(elem, errtext) {
	elem_id = elem.id;
	if(document.getElementById(elem_id + "_err") != null) {
		err_ref = document.getElementById(elem_id + "_err");
		err_ref.innerHTML = "";
	}
	
	else {
		elem_ref = document.getElementById(elem_id);
		err_ref = document.createElement("span");	
		parent_ref = elem_ref.parentNode;
		parent_ref.insertBefore(err_ref, elem_ref);		
		err_ref.setAttribute("id", elem_id + "_err");
		err_ref.setAttribute("class", "error");
	}
	//add break to prevent word wrap issues
	err_ref.innerHTML = errtext;
}

//UTILITY FUNCTIONS, PLACE IN LIBRARY EVENTUALLY

//Count Number of words in string obj
function wordcount(obj) {
	count = 0;
	words = obj.value.split(" ");
	for(word in words)
		count++;
	return count;
}

//Verify obj begins with numbers
function begins_numeric(obj) {
//ACCOUNT FOR EMPTY FIELDS
	if(obj.value == "")
		return false;
	if(isNaN(parseInt(obj.value)))
		return false;
	else
		return true;
}

//Verify obj is only alphabetic
function is_alpha(obj) {
//ACCOUNT FOR EMPTY FIELDS
	if(obj.value == "")
		return false;
	words = obj.value.split(" "); //split obj into multiple words
	for(i = 0; i < words.length; i++) { //check each word
		if(!isNaN(parseInt(words[i]))) //if this word IS a number
			return false;
			//We could get into checking for A-Z and a-z, but then special chars such as accents are not accounted for
	}
	//otherwise...
	return true;
}

//Verify obj is only numeric
function is_numeric(obj) {
//ACCOUNT FOR EMPTY FIELDS
	if(obj.value == "")
		return false;

	val = obj.value;
	checkstring = "1234567890- ";	
	is_valid = true;
	for(i = 0; i < val.length; i++) { //check each char of entered string
		for(j = 0; j < checkstring.length; j++) {
			if(val.charAt(i) == checkstring.charAt(j))
				break;				
			if(j == checkstring.length - 1) {
				is_valid = false;
				break;
			}
		}
	}
	return is_valid;
}

// -----------------------------------------------------------------
// Function    : IsEmailValid
// Language    : JavaScript
// Description : Checks if given email address is of valid syntax
// Copyright   : (c) 1998 Shawn Dorman
// http://www.goodnet.com/~sdorman/web/IsEmailValid.html
// -----------------------------------------------------------------
// Ver    Date    Description of modification
// --- ---------- --------------------------------------------------
// 1.0 09/04/1996 Original write
// 1.1 09/30/1998 CHG: Use standard header format
// -----------------------------------------------------------------
// Source: Webmonkey Code Library
// (http://www.hotwired.com/webmonkey/javascript/code_library/)
// -----------------------------------------------------------------

//Modified by Nick Carter, May 19, 2006

function IsEmailValid(FormName,ElemName)
{
var EmailOk  = true;
var Temp     = document.forms[FormName].elements[ElemName];
var AtSym    = Temp.value.indexOf('@');
var Period   = Temp.value.lastIndexOf('.');
var Space    = Temp.value.indexOf(' ');
var Length   = Temp.value.length - 1;   // Array is from 0 to length-1

if ((AtSym < 1) ||                     // '@' cannot be in first position
    (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
    (Period == Length ) ||             // Must be atleast one valid char after '.'
    (Space  != -1))                    // No empty spaces permitted
   {  
      EmailOk = false;
  //    alert('Please enter a valid e-mail address!')
      Temp.focus();
   }
	return EmailOk;
}

