/* -- These general functions are used in form validation ----------------------------------------------- */

function isBlank(s)
// Assumes s is a token (i.e., a single word).
{
	var i, c;
	
	for (i = 0; i < s.length; i++)
	{
		c = s.charAt(i);
		
		if ( (c != " ") && (c != "\n") && (c != "") )
			return false;
	}
	
	return true;	// If we've reached this point, s is of length 0 or it contains white space - that is, s is blank (i.e., it contains no data).
}

// ------------------------------------------------------------------------------------------------------ //

function isEmpty(s)
// Assumes that s is of type text or textarea.
{
	if ( (s == null) || (s == "") || isBlank(s) )	// Due to logical shortcutting, do the simplest tests first.
		return true;
		
	return false;
}

// ------------------------------------------------------------------------------------------------------ //

/* 
	Function to validate telephone number using 2 acceptable templates
	
		template re1 will accept (###)###-#### or (###) ###-####
		template re2 will accept ###-###-####
		template re3 will accept ###.###.####
		template re4 will accept ### ### ####
		template re5 will accept ##########
	
    If the template passes the data, a true condition is set, else a false condition is set.
 
	Works in IE4+, Netscape 4+, NOT Opera 3.6 
*/

function phoneNumberValid(str) 
{
    var re1 = /^\(+([0-9]{3})+\)\s?([0-9]{3})+(\-)+([0-9]{4})$/;
    var re2 = /^([0-9]{3}\-){2}[0-9]{4}$/;
    var re3 = /^([0-9]{3}\.){2}[0-9]{4}$/;
    var re4 = /^([0-9]{3}\s){2}[0-9]{4}$/;
    var re5 = /^([0-9]{10})$/;
    
	if ( re1.test(str) || re2.test(str) || re3.test(str) || re4.test(str) || re5.test(str) ) 
		return true;
    
	return false;
}

// ------------------------------------------------------------------------------------------------------ //

function emailAddressValid(emailStr) {
/* 
	The following pattern is used to check if the entered e-mail address
   	fits the user@domain format.  It also is used to separate the username
   	from the domain. 
*/
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address.
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a
	   username or domainname.  It really states which chars aren't allowed. */
	
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
		 even fit the general mould of a valid e-mail address. */
		 
		// return("Email address seems incorrect (check for @ and .'s)\n");
		return false;
	}
	
	var user=matchArray[1]
	var domain=matchArray[2]
	// See if "user" is valid
	if (user.match(userPat)==null) {
		// user is not valid
		// return("The email username doesn't seem to be valid.\n");
		return false;
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// this is an IP address
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				// return("Email destination IP address is invalid!\n");
				return false;
			}
		}
		return true;
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		// return("The email domain name doesn't seem to be valid.\n");
		return false;
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 ||
		domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   // return("The email address must end in a three-letter domain, or two letter country.\n");
	   return false;
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   // return("This address is missing a hostname!\n");
	   return false;
	}
	
	// If we've gotten this far, everything's valid!
	// return ("");
	return true;
}

// ------------------------------------------------------------------------------------------------------ //

function zipValid(curValue)
{
	var valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"; //Added the alphabet for Canadian postal codes
	var hyphencount = 0;
	// alert("Lent of var is " + curValue.length);

	if (curValue.length < 5)
	{
		// return("Enter a zip with at least 5 characters\n");
		return false;
	}

	for (var i=0; i < curValue.length; i++)
	{
		temp = "" + curValue.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1")
		{
			// return("There are invalid characters in your zip code\n");
			return false;
		}

		if (hyphencount == 0 && curValue.length > 5)
		{
			// return("Zip code can either be 5 characters, or 10 if you use a 4 digit extension, '12345-6789'\n");
			return false;
		}

		if ((hyphencount > 1) || ((curValue.length==10) && curValue.charAt(5)!="-") || ((hyphencount > 0) && (curValue.length!=10)))
		{
			// return("The proper format for the use of a hyphen character in a zip code is: '12345-6789'\n");
			return false;
	    }
	}
	// return("");
	return true;
}

// ------------------------------------------------------------------------------------------------------ //

function textAreaTruncator(formField, maxNumChars)
/*
	The calling context for this function should be similar to:
	
		<textarea cols="20" rows="2" value="whatever" onkeyup="textLimit(this, 1000);"></textarea>
*/
{
	if (formField.value.length > maxNumChars)
	{
		alert("You have reached the maximum number of allowed characters for this form field.");
		formField.value = formField.value.substring(0, maxNumChars);
	}
}

// ------------------------------------------------------------------------------------------------------ //

function disableForm(form)
/*
	Disable all elements in the form, except those elements whose class is 'class="doNotDisable"'.
*/
{
	for (var i = 0; i < form.length; i++)
	{
		form_element = form[i];	// An element (like <input>) in the form.
		if (form_element.className !== "doNotDisable")
			form_element.disabled = true;
	}
}

function enableForm(form)
/*
	Enable all elements in the form.
*/
{
	for (var i = 0; i < form.length; i++)
	{
		form_element = form[i];	// An element (like <input>) in the form.
		form_element.disabled = false;
	}
}

/* -- Specific form validator functions ----------------------------------------------------------------- */

function validateContactUsForm() // Located in /about_us/contact_us.aspx
{
	var errors = false;	
	var bad_field = new Array();		
	var j = 0;
	var form_element;
	var s = "";
		
	if ( 	
		isEmpty( document.getElementById("Address1").value ) && 
		isEmpty( document.getElementById("WorkPhone").value ) && 
		isEmpty( document.getElementById("HomePhone").value ) &&
		isEmpty( document.getElementById("Fax").value ) &&
		isEmpty( document.getElementById("Email").value )
	   )
	{
		errors = true;
		bad_field[j++] = "Some form of contact information is required (email, address or phone\n";
	}
	
	form_element = document.getElementById("Name");
	if ( isEmpty(form_element.value) )	// Assumes the all values are string tokens (i.e., not numbers).
	{
		errors = true;
		bad_field[j++] = "The Name field is required.\n";
	}			

	form_element = document.getElementById("ZipOrPostalCode");
	if ( !(isEmpty(form_element.value)) && !(zipValid(form_element.value)) )	
	{
		errors = true;
		bad_field[j++] = "The Zip/Postal Code is invalid.\n";
	}			

	form_element = document.getElementById("WorkPhone");
	if ( !(isEmpty(form_element.value)) && !(phoneNumberValid(form_element.value)) )
	{
		errors = true;
		bad_field[j++] = "The Work Phone number is invalid (include area code).\n";
	}
	
	form_element = document.getElementById("HomePhone");
	if ( !(isEmpty(form_element.value)) && !(phoneNumberValid(form_element.value)) )
	{
		errors = true;
		bad_field[j++] = "The Home Phone number is invalid (include area code).\n";
	}
	
	form_element = document.getElementById("Fax");
	if ( !(isEmpty(form_element.value)) && !(phoneNumberValid(form_element.value)) )
	{
		errors = true;
		bad_field[j++] = "The Fax number is invalid (include area code).\n";
	}
		
	form_element = document.getElementById("Email");
	if ( !(isEmpty(form_element.value)) && !(emailAddressValid(form_element.value)) )	// Allow for the case when the user does not have an email address.
	{
		errors = true;
		bad_field[j++] = "The Email address is invalid.\n";
	}
		
	form_element = document.getElementById("QuestionsComments");
	if ( isEmpty(form_element.value) )	// Assumes the all values are string tokens (i.e., not numbers).
	{
		errors = true;
		bad_field[j++] = "A brief note is required in the bottom text field.\n";
	}			
		
	form_element = document.getElementById("Address1");
	if ( isEmpty(form_element.value) && !(isEmpty(document.getElementById("Address2").value)) )	// Check to make sure that Address1 has data if Address2 has data.
	{
		errors = true;
		bad_field[j++] = "Use the first address field prior to the second address field.\n";
	}
	
	if (errors)
	{
		s = "The form has the following errors:\n\n";
		for (i = 0; i < bad_field.length; i++)
		{
			s += "- " + bad_field[i];
		}
		s += "\nPlease correct these problem(s) and resubmit the form.\n";
		alert(s);
		return false;	// Stop the form from being submitted.
	}
	
	return true;	// No problems found with the form, so submit it.
}

// ------------------------------------------------------------------------------------------------------ //

function validateParkingForms()
{
	var errors = false;	
	var bad_field = new Array();		
	var j = 0;
	var form_element;
	var s = "";
		
	if ( 	
		isEmpty( document.getElementById("address1").value ) && 
		isEmpty( document.getElementById("dayPhone").value ) && 
		isEmpty( document.getElementById("homePhone").value ) &&
		isEmpty( document.getElementById("email").value )
	   )
	{
		errors = true;
		bad_field[j++] = "Some form of contact information is required (email, address or phone)\n";
	}
	
	form_element = document.getElementById("firstName");
	if ( isEmpty(form_element.value) && isEmpty(document.getElementById("lastName").value) )	
	{
		errors = true;
		bad_field[j++] = "A First or Last name is required.\n";
	}

	form_element = document.getElementById("zipOrPostalCode");
	if ( !(isEmpty(form_element.value)) && !(zipValid(form_element.value)) )	
	{
		errors = true;
		bad_field[j++] = "The Zip/Postal Code is invalid.\n";
	}			

	form_element = document.getElementById("dayPhone");
	if ( !(isEmpty(form_element.value)) && !(phoneNumberValid(form_element.value)) )
	{
		errors = true;
		bad_field[j++] = "The Daytime Phone number is invalid (include area code).\n";
	}
	
	form_element = document.getElementById("homePhone");
	if ( !(isEmpty(form_element.value)) && !(phoneNumberValid(form_element.value)) )
	{
		errors = true;
		bad_field[j++] = "The Home Phone number is invalid (include area code).\n";
	}
			
	form_element = document.getElementById("email");
	if ( !(isEmpty(form_element.value)) && !(emailAddressValid(form_element.value)) )	// Allow for the case when the user does not have an email address.
	{
		errors = true;
		bad_field[j++] = "The Email address is invalid.\n";
	}
		
	form_element = document.getElementById("address1");
	if ( isEmpty(form_element.value) && !(isEmpty(document.getElementById("address2").value)) )	// Check to make sure that Address1 has data if Address2 has data.
	{
		errors = true;
		bad_field[j++] = "Use the first address field prior to the second address field.\n";
	}
	
	if (errors)
	{
		s = "The form has the following errors:\n\n";
		for (i = 0; i < bad_field.length; i++)
		{
			s += "- " + bad_field[i];
		}
		s += "\nPlease correct these problem(s) and resubmit the form.\n";
		alert(s);
		return false;	// Stop the form from being submitted.
	}
	
	return true;	// No problems found with the form, so submit it.
}


// ------------------------------------------------------------------------------------------------------ //

function validatePostEventClientSurvey()
{
	var errors = false;	
	var bad_field = new Array();		
	var j = 0;
	var form_element;
	var s = "";
		
	if (isEmpty(document.getElementById("FirstName").value) || isEmpty(document.getElementById("LastName").value)) {
		errors = true;
		bad_field[j++] = "First and Last names are required.\n";
	}
	
	if (isEmpty(document.getElementById("email").value)) {
	    errors = true;
	    bad_field[j++] = "E-mail Address is required.\n";
	} else {
	    if (!(emailAddressValid(document.getElementById("email").value))) {
	        errors = true;
		    bad_field[j++] = "The E-mail Address is invalid.\n";
        }
	}

	if (isEmpty(document.getElementById("txtEvent").value)) {
	    errors = true;
	    bad_field[j++] = "Event Name is required.\n";
	}

	if (isEmpty(document.getElementById("WorkPhone").value)) {
	    errors = true;
	    bad_field[j++] = "Work Phone is required.\n";
	} else {
	    if (!(phoneNumberValid(document.getElementById("WorkPhone").value))) {
	        errors = true;
	        bad_field[j++] = "Work Phone is invalid (include area code).\n";
	    }
	}

	if (errors)
	{
		s = "The form has the following errors:\n\n";
		for (i = 0; i < bad_field.length; i++)
		{
			s += "- " + bad_field[i];
		}
		s += "\nPlease correct these problem(s) and resubmit the form.\n";
		alert(s);
		return false;	// Stop the form from being submitted.
	}
	
	return true;	// No problems found with the form, so submit it.
}