// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Aug 2004: have tested that IE 5.0 and IE 5.5 both support DOM model
// sufficiently well, so innerHTML option removed (redundant).
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread
var glb_RequiredVars = new Object;
var minyear = 1900;
var debug=false;

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 

    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};

// -----------------------------------------
//                  msgReqd
// This is a wrapper for msg that will also log the Required Status
// commonCheck routine must have previously been called
// -----------------------------------------

function msgReqd(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  msg(fld,msgtype,message);
  var ss =  fld.substring(4,1000);
  logRequiredField(ss,message);
};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;  

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var testval = '';
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);

  if (!elem.firstChild)
    return true;  // not available on this browser 

  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  
  
  if (vfld.type == 'select-one') {
	testval = vfld.options[vfld.selectedIndex].value;
  } else {
   	testval = vfld.value;
  }

  if (emptyString.test(testval)) {

    if (reqd) {
      msg (ifld, "error", "!required");  
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;

}

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  //alert("made it thisfar");
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;
  
  msg (ifld, "warn", "");  
  return true;
};

// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "ERROR:\nnot a valid e-mail address");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "warn", "Invalid e-mail address");
  else
    msg (ifld, "warn", "");
  return true;
};





// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd,   
			 mindigits)   // true if required
{
  if (mindigits==undefined) mindigits=10;
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;
  
  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-x]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "ERROR:\nnot a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<7) {
    msg (ifld, "error", "ERROR:\n" + numdigits + " need at least " + mindigits +" digits	");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "warn","\n" + numdigits + " digits - check if correct");
  else { 
    if (numdigits<mindigits)
      msg (ifld, "warn", "\nOnly " + numdigits + " at least " + mindigits );
    else
      msg (ifld, "warn", "");
  }
  return true;
};

// -----------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// -----------------------------------------

function validateAge    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "ERROR:\nnot a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "ERROR:\nnot a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg (ifld, "warn", "\nOlder than 110: check correct");
  else {
    if (tfld<7) msg (ifld, "warn", "\nBit young for this, aren't you?");
    else        msg (ifld, "warn", "");
  }
  return true;
};


/*****************************************************
 END OF BUDDYS CODE
******************************************************/

// -----------------------------------------
//               logRequired
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function logRequiredField  (ifld,   // field name
			reqd 	//value of reqd feild
 			) {
	if (reqd == '') {
		if (glb_RequiredVars[ifld] != undefined) {
			//alert('undefining this'+ifld);
			delete glb_RequiredVars[ifld] ;
		}
	} else {
		//alert('defining this'+ifld);

		glb_RequiredVars[ifld] = reqd;
	}
};

function clearAllRequiredFields () {
 glb_RequiredVars = undefined;

}



function showCalendarPlus(id,dateformat) {
	var elem = document.getElementById(id);
	
	var bob= showCalendar(id,dateformat);
	setfocus(elem);
	//return bob;
}


function validatePCodeFormat (vfld,ifld,reqd) {
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;
  var tfld = trim(vfld.value);

  var re= /^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i;
	if (!re.test(tfld)) {
 		msg (ifld, "error", "ERROR:\nnot a valid postal code (a1b 2c3)");
   		setfocus(vfld);
    		return false;
  	} else {
		msg (ifld, "warn", "");
	}

  return true;

}

function validateUserName(vfld,ifld,reqd) {
	var tfld = trim(vfld.value);
	var r = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]", "i");
	//r.exec(form.username.value)
	if (r.exec(tfld) || tfld.length < 3) {
 		msg (ifld, "error", 'Login username cannot contain <>[]"%;()&+- and must be at least 3 characters');
   		setfocus(vfld);
		return false;
	}
	msg(ifld, "warn", '');
	return true;

}


function validateDateFormat (vfld, ifld, reqd) {

  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;
  var tfld = trim(vfld.value);

	var re= /^((\d{4})-(\d{2})-(\d{2})).*$/;
	var matchArray = re.exec(tfld);

	if (!re.test(tfld)) {
		msg (ifld, "error", "ERROR:\nnot a valid date - YYYY-MM-DD");
   		setfocus(vfld);
		return false;
		
	} else {
		
		//alert(matchArray[2] +" " +matchArray[3] +" "+ matchArray[4] ); 
		if (matchArray[2]*1 < minyear) {
			msg (ifld, "warn", "year is a little suspect. Please enter something realistic (i.e. >"+minyear+").");
	   		setfocus(vfld);
	    		return (false);
		}
		if ((matchArray[3] * 1) < 1 || (matchArray[3] * 1) > 12 ) {
	   		msg (ifld, "warn", "\"Birth Date\" month should be two digits long 01 to 12");
	   		setfocus(vfld);
	    		return (false);
		}
		if ((matchArray[4] * 1) < 1 || (matchArray[4] * 1) > 31 ) {
	   		msg (ifld, "warn", "\"Birth Date\" day should be two digits long from 01 to 31");
	   		setfocus(vfld);
	    		return (false);
		}
		
		vfld.value = matchArray[1];
		msg (ifld, "warn", "");

		//incoming.replace(re,"$1");
		return(true);
	}
	msg (ifld, "warn", "");
	setfocus(vfld);
	return true;
}


function noenter() {
  return !(window.event && window.event.keyCode == 13); 
}



// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- xX.";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	s=stripCharsInBag(strPhone,validWorldPhoneChars);

	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidateForm(){
	var Phone=document.frmSample.txtPhone
	
	if ((Phone.value==null)||(Phone.value=="")){
		alert("Please Enter your Phone Number")
		Phone.focus()
		return false
	}
	if (checkInternationalPhone(Phone.value)==false){
		alert("Please Enter a Valid Phone Number")
		Phone.value=""
		Phone.focus()
		return false
	}
	return true
 }



function checkDateFormat_YYYY_MM_DD (incoming) {

	var re= /^((\d{4})-(\d{2})-(\d{2})).*$/;
	var matchArray = re.exec(incoming.value);

	if (incoming.value.search(re) <0) {
	   alert("\"Birth Date\" field is not entered correctly  - enter as YYYY-MM-DD.");
	    incoming.focus();
	    return (false);
	
	} else {
		var minyear = 1990;
		
		//alert(matchArray[2] +" " +matchArray[3] +" "+ matchArray[4] ); 
		if (matchArray[2]*1 < minyear) {
	   		alert("\"Birth Date\" year is a little suspect. Please enter something realistic (i.e. >"+minyear+").");
	    		incoming.focus();
	    		return (false);
		}
		if ((matchArray[3] * 1) < 1 || (matchArray[3] * 1) > 12 ) {
	   		alert("\"Birth Date\" month should be two digits long 01 to 12");
	    		incoming.focus();
	    		return (false);
		}
		if ((matchArray[4] * 1) < 1 || (matchArray[4] * 1) > 31 ) {
	   		alert("\"Birth Date\" day should be two digits long from 01 to 31");
	    		incoming.focus();
	    		return (false);
		}
		
		incoming.value = matchArray[1];
		//incoming.replace(re,"$1");
		return(true);
	}

}

function writeConsole(content) {
	if (debug) {
 top.consoleRef=window.open('','myconsole',
  'width=350,height=500'
   +',menubar=0'
   +',toolbar=1'
   +',status=0'
   +',scrollbars=1'
   +',resizable=1')
 top.consoleRef.document.writeln(
  '<html><head><title>Console</title></head>'
   +'<body bgcolor=white onLoad="self.focus()">'
   +content
   +'</body></html>'
 )
 top.consoleRef.document.close()
	}
}

function checkAllLoggedReqdFields (ip) {
	var outstring='';
	var outstring1='';
	var issuesexist = false;
	for (n in glb_RequiredVars) {
		var issue = false;
		//	if (	ip.elements[n].type=='radio') {
		//		if (
		if (ip.elements[n].value == undefined) {
		 	issue = true;
			if ( ip.elements[n].length >0 ) {
				if (ip.elements[n][0].type == 'radio') {
					outstring = outstring + 'RADIO BUTTON';
					for (var i = 0; i<ip.elements[n].length ; i++) {

						if (ip.elements[n][i].checked) {
							issue=false;
						}
					}
				}
			} else {
				outstring = outstring + '  UNDEFINED' ;		
			}
		} else {
			if (ip.elements[n].value == '') {
				outstring = outstring + 'DEFINED';
				issue =true;
			}
		}
		

		if (issue) {
			outstring = outstring + ' but MISSING ';
			outstring = outstring + 'indexname' + n;
			outstring = outstring + ' name:' + glb_RequiredVars[n];
			outstring = outstring + " value:'<b>" + ip.elements[n].value + "</b>'";
			outstring = outstring + '<br>';
			outstring1 = outstring1 + n + " (needs to be filled in)\n";
			issuesexist=true;
		}

	}
	writeConsole('output<br>'+outstring);
	return(outstring1);
}


function checkRequiredFields() {
	var tform = document.Page1;
	var outputerrors = checkAllLoggedReqdFields(tform);
	outputerrors = outputerrors + checkExtraCheckBoxes(outputerrors);
	if (outputerrors) {
		alert("There are some required fields that still need some attention\n\nLook for the fields with a * next to them\n\n"+outputerrors);
	return false;
	}	

	

	document.Page1.submit();

}

function checkExtraCheckBoxes(outputerrors) {
	//if (!document.Page1.PrivacyPolicyRead.checked) {
	//	outputerrors = outputerrors +"Please agree to the Privacy Policy at the bottom\n";
	//}
	return outputerrors;
}

function checkRequiredFields1()
{
/*if (document.Page1.disclaimer.options[document.Page1.disclaimer.selectedIndex].value != "agree") {
   		alert("Please read and check agree with the disclaimer at the top of this form.");
   		 document.Page1.disclaimer.focus();
   		 return (false);
	}
*/
if (document.Page1.disclaimer.checked == false) {
	  		alert("Please read and check agree with the disclaimer at the top of this form.");
   		 document.Page1.disclaimer.focus();
   		 return (false);
}


if (document.Page1.fName.value == "" || document.Page1.lName.value == "")
  {
    alert("First or Last Name field cannot be empty.");
	if (document.Page1.fName.value == "") {
	    document.Page1.lName.focus();

	    return (false);
	}
	if (document.Page1.lName.value == "") {
	    document.Page1.lName.focus();

	    return (false);
	}


  }


if (document.Page1.Address.value == "")
  {
    alert("\"Address\" field cannot be empty");
    document.Page1.Address.focus();
    return (false);
  }
if (document.Page1.City.value == "")
  {
    alert("\"City\" field cannot be empty");
    document.Page1.City.focus();
    return (false);
  }
if (document.Page1.Province.value == "")
  {
    alert("\"Province\" field cannot be empty");
    document.Page1.Province.focus();
    return (false);
  }

if (!checkPCodeFormat(document.Page1.PCode)) {
    return (false);
}

if (!checkInternationalPhone(document.Page1.Phone.value))
  {
    alert("\"Child's Phone\" field is not entered correctly. Please enter it complete with area code. \n\nOnly use numbers spaces and brackets. Use x for an extention.");
    document.Page1.Phone.focus();
    return (false);
 }

if (document.Page1.Email.value != '') {

	if (!emailCheck (document.Page1.Email.value) ) {
		alert("Email Address must be in a valid form myaddress@somewhere.com");
		    document.Page1.Email.focus();

		    return (false);
	}

} else {
	if (document.Page1.Noemail.checked == false) {
		alert("You have entered no email address but you have also not checked off the box 'I have no email address'.");
		    document.Page1.Noemail.focus();

		    return (false);

	}
}
if (document.Page1.Birthdate.value == "") {
    alert("\"Birth Date\" field cannot be empty - enter as YYYY-MM-DD");
    document.Page1.Birthdate.focus();
    return (false);
  }

if (!checkDateFormat_YYYY_MM_DD(document.Page1.Birthdate))
  {
    document.Page1.Birthdate.focus();
    return (false);
  }
if (document.Page1.Grade.options[document.Page1.Grade.selectedIndex].value == "") {
    alert("Please choose a \"Grade\"");
    document.Page1.Grade.focus();
    return (false);
}
/*if (document.Page1.Grade.value == "")
  {
    alert("\"Grade\" field cannot be empty");
    document.Page1.Grade.focus();
    return (false);
  } else {
	 if (isNaN(document.Page1.Grade.value)) {
		if (!(document.Page1.Grade.value.toUpperCase().substr(0,1) == "E" || document.Page1.Grade.value.toUpperCase().substr(0,1) == "K" )) {
		   alert("\"Grade\" must be ECS or a number from 1 to 6.");
   		   document.Page1.Grade.focus();
    		   return (false);
		}
	} else {
		if (document.Page1.Grade.value < 1 || document.Page1.Grade.value > 6 ) {
		   alert("\"Grade\" must be ECS or a number from 1 to 6");
   		   document.Page1.Grade.focus();
    	   	return (false);
		}
	}
  }
*/

if (document.Page1.ABHealth.value == "")
  {
    alert("\"AlBerta Health\" field cannot be empty");
    document.Page1.ABHealth.focus();
    return (false);
  }
if (document.Page1.GuardianName.value == "")
  {
    alert("\"Guardian Name\" field cannot be empty.");
    document.Page1.GuardianName.focus();
    return (false);
  }
if (!checkInternationalPhone(document.Page1.GuardianWPhone.value))
  {
    alert("\"Guardian Main Phone\" is not entered correctly. Please enter it complete with area code. \n\nOnly use numbers spaces and brackets. Use x for an extention.");
    document.Page1.GuardianWPhone.focus();
    return (false);
  }
if (document.Page1.GuardianMPhone.value != "" && !checkInternationalPhone(document.Page1.GuardianMPhone.value))
  {
    alert("\"Guardian Mobile or Secondary Phone\" is not entered correctly. Please enter it complete with area code. \n\nOnly use numbers spaces and brackets. Use x for an extention.");
    document.Page1.GuardianMPhone.focus();
    return (false);
  }
if (document.Page1.EmergeContactName.value == "")
  {
    alert("\"Emergency Contact Name\" field cannot be empty.");
    document.Page1.EmergeContactName.focus();
    return (false);
  }

if (!checkInternationalPhone(document.Page1.EmergePhone.value))
  {
    alert("\"Emergency Phone Number\" is not entered correctly. Please enter it complete with area code. \n\nOnly use numbers spaces and brackets. Use x for an extention.");
    document.Page1.EmergePhone.focus();
    return (false);
  }
  
if (document.Page1.EmergeRelationship.value == "")
  {
    alert("\"Emergency Contact Relationship\" field cannot be empty.");
    document.Page1.EmergeRelationship.focus();
    return (false);
  }

if (document.Page1.NoAllergies.checked == false && document.Page1.Notes.value == "")
  {
    alert("\"The Notes are left empty by the 'child does not have any allergies' check box is not checked. Please enter the details of any allergies in the Notes box or check the 'child does not have any allergies' checkbox.");
    document.Page1.NoAllergies.focus();
    return (false);
  }


	document.Page1.submit();


}




/* 1.1.2: Fixed a bug where trailing . in e-mail address was passing
            (the bug is actually in the weak regexp engine of the browser; I
            simplified the regexps to make it work).
   1.1.1: Removed restriction that countries must be preceded by a domain,
            so abc@host.uk is now legal.  However, there's still the 
            restriction that an address must end in a two or three letter
            word.
     1.1: Rewrote most of the function to conform more closely to RFC 822.
     1.0: Original  */

/*<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
*/
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;
}


