// * Set parameters for form elements before running.                                     *
// *                                                                                      *
// *    KEY:                                                                              *
// *  e.longname = specifies a readable name for the element for messages                 *
// *   e.setsize = needs to be a certain [t\f] (element.setsize = true)                   *
// *   e.maxsize = (element.maxsize = "20"); "" = no max # of characters                  *
// *   e.minsize = (element.minsize = "1"); "" = no min # of characters                   *
// *       e.req = required field [t\f] (element.req = true)                              *
// *       e.val = validation type      (element.val = "?")                               *
// *                blank - Not Necessary                                                 *
// *                a - all characters allowed (not checked for validity)                 *
// *                t - textarea characters (extended characters + CR's etc)              *
// *                c - Only characters (a-z and A-Z)						              *
// *                x - extended characters                                               *
// *                e - email characters and validation                                   *
// *                l - limited characters                                                *
// *                p - password validation                                               *
// *                    need to specify an element.passchk for a confirm.                 *
// *                    ex element.passchk = document.form.passchk.value                  *
// *                w - whole numbers only (strips non-number characters)                 *
// *                    if a number field, need to define an element.minvalue             *
// *                      and element.maxvalue setting for value                          *
// *                n - numbers only, "." allowed                                         *
// *                    if a number field, need to define an element.min                  *
// *                      and element.max setting for value                               *
// *                z - Zip/Postal Code number only if                                    *
// *                    country = "US", "USA", or "United States"                         *
// *                    if a zipcode field, need to define an element.min                 *
// *                      and element.max setting for value                               *
// *                      also need to specify element.country                            *
// *                      (ex document.f.zip.country = document.f.country)                *
// *                                                                                      *
// * (note: e = form element)                                                             *
// * If e is a select list or dropdown, and there are spacer options that shouldn't be    *
// * selected, set the option's value to "invalid"                                        *
// *                                                                                      *
// *           loadForm() {                                                     *
// *             document.forms["email"].elements["emailaddr"].longname = "Email Address" *
// *             document.forms["email"].elements["emailaddr"].req = true                 *
// *             document.forms["email"].elements["emailaddr"].val = e                    *
// *           }                                                                          *
// ****************************************************************************************


var e = ""
var vLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var vNumbers = "0123456789"
var vExt1 = "-_."
var vExt2 = "@"
var vExt3 = "?:; #+$%^*=,!/&\'\\()<>[]{}\""
var vExt4 = "\f\n\r\t"
var validChars = ""
var focus_set = false
var focus_point = ""
var blank_msg = ""
var error_msg = ""
var alert_msg = ""

function blankMsg(fe) {
	if (focus_set != true) {
		focus_set = true
		focus_point = fe
	}
	blank_msg += "\n     " + fe.longname
	return true
}

function isblank(s) {  // Checks for a string containing only whitespace characters
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false
	}
	return true
}

function checkSize(fe) {
	if (fe.setsize == true) {
		if (fe.minsize != "") {
			if (fe.value.length <= (fe.minsize - 1)){
				error_msg += "\n     Your " + fe.longname + " must be at least " + fe.minsize + " characters"
				if (focus_set != true) {
					focus_set = true
					focus_point = fe
				}
			}
		}
		if (fe.maxsize != "") {
			if (e.value.length >= (fe.maxsize)){
				error_msg += "\n     Your " + e.longname + " must be less than " + fe.maxsize + " characters"
				if (focus_set != true) {
					focus_set = true
					focus_point = fe
				}
			}
		}
	}
	
	return
}

function isValidChar(c) {
	for (var i=0; i < validChars.length; i++) {
		if (c == validChars.charAt(i)) {
			return true
		}
	}
	return false
}
 
function isValidString(s) {
	for (var i=0; i < s.length; i++) {
		if (isValidChar(s.charAt(i)) != true ) {
			return s.charAt(i)
		}
	}
	return true
}

function validEmail(s) {  // Checks string for valid email address
	validChars = vLetters + vNumbers + vExt1 + vExt2
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if (isValidChar(c) != true) {
			return false
		}
	}
	if ( (s.indexOf("@")<1) || (s.indexOf(".")<3) || (s.length <7) ||  (s.lastIndexOf(".") < s.indexOf("@")) || (s.indexOf("@") != s.lastIndexOf("@")) || (s.lastIndexOf(".")==(s.length-1))){
	return false
		}
	
	return true
}

function numberStrip(s) {
	var n = ""
	for (var i=0; i < s.length; i++) {
		if (isValidChar(s.charAt(i))) {
			n += s.charAt(i)
		}
	}
	return n
}
 
function wholeNumberCheck(fe){ // checks for valid numbers
	validChars = vNumbers
	var v = parseFloat(numberStrip(fe.value))
	fe.value = v
	if ((isNaN(v)) || (fe.value == null) || (fe.value == "") || (v < fe.minvalue) || (v > fe.maxvalue)) {
		return false
	}
	return true
}


function numberCheck(fe){ // checks for valid numbers
	var v = fe.value
	if ((isNaN(v)) || (fe.value == null) || (fe.value == "") || (v < fe.minvalue) || (v > fe.maxvalue)) {
		validChars = vNumbers + "."
		v = parseFloat(numberStrip(fe.value))
		fe.value = v
		return false
	}
	return true
}


function validForm(f,testing) {
	//reset variables
	validChars = ""
	focus_set = false
	focus_point = ""
	blank_msg = ""
	error_msg = ""
	alert_msg = ""	
	var has_radio=false
	for (var i=0; i < f.length; i++) {
		e = f.elements[i]
		if (e.type == "radio") {
			has_radio=true		
			if (e.checked == true) {
				var radiocheck=true
			}
			var radioname=e.name
			}
		if (e.type == "select-one") {
			if ((e.req == true) && (e.options[e.selectedIndex].value == "invalid")) {
				if (e.longname) {
					error_msg += "\n     Invalid Selection - " + e.longname + " has an invalid selection."
				}else{
					error_msg += "\n     Invalid Selection - " + e.name + " has an invalid selection."
				}
				if (focus_set != true) {
					focus_point = e
					focus_set = true
				}
			}
		}
		if (e.type == "select-multiple") {
			for (var j=0; j < e.length; j++) {
				if (e.options[j].selected == true) {
					if ((e.req == true) && (e.options[j].value == "invalid")) {
						if (e.longname) {
							error_msg += "\n     Invalid Selection - " + e.longname + " has an invalid selection."
						}else{
							error_msg += "\n     Invalid Selection - " + e.name + " has an invalid selection."
						}
						if (focus_set != true) {
							focus_point = e
							focus_set = true
						}
					}
				}
			}
		}
		
		if ((e.type == "file")||(e.type == "password")||(e.type == "text")||(e.type == "hidden")||(e.type == "textarea")) {
			if (isblank(e.value) != true) {
				checkSize(e)
				if (e.val == "p") {
					validChars = vLetters + vNumbers + vExt1
					if ((isValidString(e.value) != true)) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Password Entry - " + isValidString(e.value) + " - in " + e.longname + " field."
					}
					if (e.value != f.Password.value) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Passwords don't match!"
					}
				}

				if (e.val == "t") {
					validChars = vLetters + vNumbers + vExt1 + vExt2 + vExt3 + vExt4
					if (isValidString(e.value) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Text Entry - " + isValidString(e.value) + " - in " + e.longname + " field."
					}
				}

				if (e.val == "x") {
					validChars = vLetters + vNumbers + vExt1 + vExt2 + vExt3
					if (isValidString(e.value) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Text Entry - " + isValidString(e.value) + " - in " + e.longname + " field."
					}
				}

				if (e.val == "l") {
					validChars = vLetters + vNumbers + vExt1
					if (isValidString(e.value) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Text Entry - " + isValidString(e.value) + " - in " + e.longname + " field."
					}
				}

				if (e.val == "c") {
					validChars = vLetters + vExt4
					if (isValidString(e.value) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Text Entry - " + isValidString(e.value) + " - in " + e.longname + " field."
					}
				}

				if (e.val == "l2") {
					validChars = vLetters + vNumbers + vExt1 + " "
					if (isValidString(e.value) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Text Entry - " + isValidString(e.value) + " - in " + e.longname + " field."
					}
				}

				if (e.val == "e") {
					if ((validEmail(e.value) != true)) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Email Address - " + e.longname
					}
				}

				if (e.val == "n") {
					if (numberCheck(e) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Number Entry - " + e.longname
						error_msg += "\n          Must be a number between " + e.minvalue + " and " + e.maxvalue + "."
					}
				}

				if (e.val == "w") {
					if (wholeNumberCheck(e) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Whole Number Entry - " + e.longname
						error_msg += "\n          Must be a whole number between " + e.minvalue + " and " + e.maxvalue + "."
					}
				}

				if (e.val == "z") {
					if (wholeNumberCheck(e) != true) {
						if (focus_set != true) {
							focus_set = true
							focus_point = e
						}
						error_msg += "\n     Invalid Whole Number Entry - " + e.longname
						error_msg += "\n          Must be a whole number between " + e.minvalue + " and " + e.maxvalue + "."
					}
				}
			} else {
				if (e.req == true) {
					blankMsg(e)
				}
			}
		}
	}
	if (has_radio==true && radiocheck!=true)
	{
		error_msg += "\n     Invalid Selection - " + radioname + " has an invalid selection."
	}
	if ((blank_msg == "")&&(error_msg == "")) {
		
			return true
		
	} else {
		alert_msg = "Your entries were not submitted, due to the following..."
		alert_msg += "\n______________________________________________________________"
		if (blank_msg != "") {
			alert_msg += "\n\nBlank Fields:\n"
			alert_msg += blank_msg
		}
		if (error_msg != "") {
			alert_msg += "\n\nErrors:\n"
			alert_msg += error_msg
		}
		alert_msg += "\n_______________________________________________________________"
		alert(alert_msg)
		//focus_point.focus()
		return false
	}
}
function submitTest(f) {
	var submitMsg = "<html>\n\t<head>\n\t\t<title>Form is valid.</title>\n\t</head>\n\t<body onblur='window.self.close()'>\n\t\t<table cellpadding=\"2\" border=\"1\">"
	for (var i=0; i < f.length; i++){
		var e = f.elements[i]
		alert(e.longname)
		if ((e.type == "text")||(e.type == "hidden")||(e.type == "textarea")||(e.type == "password")||(e.type == "button")||(e.type == "submit")) {
			submitMsg += "\n\t\t\t<tr>"
			submitMsg += "\n\t\t\t\t<td>"
			submitMsg += "\n\t\t\t\t\t" + e.name
			submitMsg += "\n\t\t\t\t</td>"
			submitMsg += "\n\t\t\t\t<td>"
			submitMsg += "\n\t\t\t\t\t&nbsp;&nbsp;&nbsp;" + e.value
			submitMsg += "\n\t\t\t\t</td>"
			submitMsg += "\n\t\t\t</tr>"
		}
		if (e.type == ("checkbox")) {
			if (e.checked = true) {
				submitMsg += "\n\t\t\t<tr>"
				submitMsg += "\n\t\t\t\t<td>"
				submitMsg += "\n\t\t\t\t\t" + e.name
				submitMsg += "\n\t\t\t\t</td>"
				submitMsg += "\n\t\t\t\t<td>"
				submitMsg += "\n\t\t\t\t\t&nbsp;&nbsp;&nbsp;" + e.value
				submitMsg += "\n\t\t\t\t</td>"
				submitMsg += "\n\t\t\t</tr>"
			}
		}
		if (e.type == ("radio")) {
			if (e.checked == true) {
				submitMsg += "\n\t\t\t<tr>"
				submitMsg += "\n\t\t\t\t<td>"
				submitMsg += "\n\t\t\t\t\t" + e.name
				submitMsg += "\n\t\t\t\t</td>"
				submitMsg += "\n\t\t\t\t<td>"
				submitMsg += "\n\t\t\t\t\t&nbsp;&nbsp;&nbsp;" + e.value
				submitMsg += "\n\t\t\t\t</td>"
				submitMsg += "\n\t\t\t</tr>"
			}
		}

		if (e.type == "select-one") {
			submitMsg += "\n\t\t\t<tr>"
			submitMsg += "\n\t\t\t\t<td>"
			submitMsg += "\n\t\t\t\t\t" + e.name
			submitMsg += "\n\t\t\t\t</td>"
			submitMsg += "\n\t\t\t\t<td>"
			submitMsg += "\n\t\t\t\t\t&nbsp;&nbsp;&nbsp;" + e.options[e.selectedIndex].value
			submitMsg += "\n\t\t\t\t</td>"
			submitMsg += "\n\t\t\t</tr>"
		}

		if (e.type == "select-multiple") {
			submitMsg += "\n\t\t\t<tr>"
			submitMsg += "\n\t\t\t\t<td>"
			submitMsg += "\n\t\t\t\t\t" + e.name
			submitMsg += "\n\t\t\t\t</td>"
			submitMsg += "\n\t\t\t\t<td>"
			for (var j=0; j < e.length; j++) {
				if (e.options[j].selected == true) {
					submitMsg += "\n\t\t\t\t\t&nbsp;&nbsp;&nbsp;" + e.options[j].value + "<br>"
				}
			}
			submitMsg += "\n\t\t\t\t</td>"
			submitMsg += "\n\t\t\t</tr>"
		}
	}
	submitMsg += "\n\t\t</table>\n\t<body>"
	var msgWindow = window.open("","test_submit","resizable,status,width=600,height=400,scroll=auto")
	var target = msgWindow.document
	target.write(submitMsg)
	target.close()
	msgWindow.focus()
}

function emailCheck (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. */
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("The username doesn't seem to be valid.")
    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) {
	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.")
    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.
   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
//return true;
}
