// create object
function formValidator()
{
// set up array to hold error messages
this.errorList = new Array;
// set up object methods
this.isEmpty = isEmpty; 
this.isNumber = isNumber; 
this.isInteger = isInteger; 
this.isAlphabetic = isAlphabetic; 
this.isAlphaNumeric = isAlphaNumeric; 
this.isWithinRange = isWithinRange; 
this.isEmailAddress = isEmailAddress; 
this.isPassword = isPassword;
this.isChecked = isChecked; 
this.isRadio = isRadio; 
this.isProvince = isProvince;
this.isValidCanadianCode = isValidCanadianCode;
this.isCanada = isCanada;
this.isValidZip = isValidZip;
this.isUSA = isUSA;
this.isInternationalPhone = isInternationalPhone;
this.isPhone = isPhone;
this.isPhoneCode = isPhoneCode;
this.strip_spaces = strip_spaces;
this.stripCharsInBag = stripCharsInBag;

this.changeTitleStyle = changeTitleStyle;
this.raiseError = raiseError; 
this.numErrors = numErrors; 
this.displayErrors = displayErrors;
this.getError = getError;
this.resetTitles = resetTitles;
}
// check to see if input is whitespace only or empty
function isEmpty(val)
{
	if (val.match(/^\s+$/) || val == "")
	{
	return true;
	}
	else
	{
	return false;
	} 
}
// check to see if input is number
function isNumber(val)
{
if (isNaN(val))
{
return false;
}
else
{
return true;
} 
}
//functions used in phone check
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;
}
// check to see if input is alphabetic
function isAlphabetic(val)
{
if (val.match(/^[a-zA-Z]+$/))
{
return true;
}
else
{
return false;
} 
}
// check to see if input is alphanumeric
function isAlphaNumeric(val)
{
if (val.match(/^[a-zA-Z0-9]+$/))
{
return true;
}
else
{
return false;
} 
}
// check to see if value is within range
function isWithinRange(val, min, max)
{
if (val >= min && val <= max)
{
return true;
}
else
{
return false;
} 
}
// check to see if input is a valid email address
function isEmailAddress(val)
{
if (val.match(/^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/))
{
return true;
}
else
{
return false;
} 
}
function isPassword(val)
{
var illegalChars = /\W/;
    
if (illegalChars.test(val)) 
{
   return "passwordchar";
}
else if (val.length< 4 || val.length>8) {
   return "passwordlength";
} 
else
{  
return "ok";
}
}
// check to see if form value is checked
function isChecked(obj)
{
if (obj.checked)
{
return true;
}
else
{
return false;
} 
}
// check to see if form radio button has been selected
function isRadio(obj)
{
if (obj[0].checked || obj[1].checked)
{
return true;
}
else
{
return false;
} 
}
function strip_spaces(mystr) {
  var newstring = "";
  if (mystr.indexOf(' ') != -1) {
    string = mystr.split(' ');
    for (var i=0; i<string.length ;i++) {
      newstring += string[i];
    }
    return newstring;
  } else { 
    return mystr; 
  }
}
// is state a province
function isProvince (state) {
 var canada = new Array();
 canada = ["AB","BC","MB","NB","NL","NT","NS", "NU","ON","PE","QC","SK","YT"];
 for (var i=0; i<canada.length; i++) {
	if (state==canada[i]) {
	   return true;
	}   
 } 	
  return false;
}

// validate  canadial postal code because state is province
function isValidCanadianCode(entry) 
{
	entry=entry.toUpperCase();        // in case of lowercase characters
	entry=strip_spaces(entry); 		  // in case of whitespace before or after	
	strlen = entry.length; 
	if (strlen == 6) {
		// no space expected
		// Check for legal characters in string - note index starts at zero
		if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(0)) < 0) {return false;}
		if ('0123456789'.indexOf(entry.charAt(1)) < 0) {return false;}
		if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(2)) < 0) {return false;}
		if ('0123456789'.indexOf(entry.charAt(3)) < 0) {return false;}
		if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(4)) < 0) {return false;}
		if ('0123456789'.indexOf(entry.charAt(5)) < 0) {return false;}
	} else if (strlen == 7) {
		// space expected
		// Check for legal characters in string - note index starts at zero
		if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(0)) < 0) {return false;}
		if ('0123456789'.indexOf(entry.charAt(1)) < 0) {return false;}
		if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(2)) < 0) {return false;}
		if (' '.indexOf(entry.charAt(3)) < 0) {return false;}
		if ('0123456789'.indexOf(entry.charAt(4)) < 0) {return false;}
		if ('ABCDEFGHJKLMNPQRSTUVWXYZ'.indexOf(entry.charAt(5)) < 0) {return false;}
		if ('0123456789'.indexOf(entry.charAt(6)) < 0) {return false;}
	} else {
	  // length is invalid - needs to be 6 or 7
	  return false;
	}
	return true;  
}
// validate province against country
function isCanada (val) {
		   
 if (val!='Canada') {
	 return false;
  } else {
	  return true;
  } 
			   			  			  
}	

// validate zip
function isValidZip (zip)
{
var valid = "0123456789-";
var hyphencount = 0;
field=strip_spaces(zip); 
if (field.length!=5 && field.length!=10) {
return false;
}
for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (temp == "-") {
   hyphencount++;
   if (field.length != 10) {
      return false;
   }   
}   
if (valid.indexOf(temp) == "-1") {
return false;
}
if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
return false;
   }
}

return true;
}

// validate state against country
function isUSA (val) {	   
 if (val!='USA') {
	 return false;
 } else {
	  return true;
 } 
			   			  			  
}			
function isInternationalPhone(strPhone) 
{
s=fv.stripCharsInBag(strPhone,validWorldPhoneChars);
// between 6 and 10 digits
if (s.length < minDigitsInIPhoneNumber || s.length > maxDigitsInIPhoneNumber) {
  return false;
} else {  
   return (fv.isInteger(s));
} 
}
function isPhone(strPhone) 
{
s=fv.stripCharsInBag(strPhone,validWorldPhoneChars);
//alert ('s= '+s);
if (s.length < 7) {
  return false;
} else {  
   return (fv.isInteger(s));
} 
}
function isPhoneCode(strPhone){
s=fv.stripCharsInBag(strPhone,validWorldPhoneChars);
//alert ('s= '+s);
 
   return (fv.isInteger(s));
  
}

        
// display all errors
// iterate through error array and print each item
function displayErrors()
{
var text = "";
for (x=0; x<this.errorList.length; x++)
{
   text+="\n"+this.errorList[x];
}
alert("The following fields are required or need attention:" + text);
}
// add an error to error list
function raiseError(msg)
{
this.errorList[this.errorList.length] = msg;
}
// return number of errors in error array
function numErrors()
{
return this.errorList.length;
}
//get error for particular field
function getError(field) {
var message=messageArray[field];
return message;

}
//used in validating phone to strip acceptable characters
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;
}
// Declaring required variables for phone check
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()-. ";
// 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 = 6;
// Maximum no of digits in an international phone no.
var maxDigitsInIPhoneNumber = 10;

var emptyString = /^\s*$/
// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------

function changeTitleStyle(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.)
  //alert(fld);
  var dispmessage;
  var elem = document.getElementById(fld);
  if (emptyString.test(message)) {
    //dispmessage = String.fromCharCode(nbsp);    
  } else {  
    dispmessage = message;
    elem.firstChild.nodeValue = dispmessage;  
  }  
  
    
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

function charOnly(field) {
  
var invalid = "0123456789";

for (var i=0; i < field.length; i++) {
   temp = "" + field.substring(i, i+1);
     
   if (invalid.indexOf(temp) != "-1") {
      return false;
   }
}


return true;

}
// reset title to plain (non-error) color
function resetTitles() {
var id;
var elems = document.getElementsByTagName('div'); // yes, wildcards do exist
//alert('len= '+elems.length);
for (var i=0;i<elems.length;i++) {
   id=elems[i].getAttribute('id');
   //alert('id= '+id);
   // R and W signify IDs that are not of class titlecell. For now they are not required so do not need resetting
   if (id && id.indexOf('title')!=-1 && id.indexOf('R')==-1 && id.indexOf('W')==-1)  {  //only if tag has title in name
    //alert('tag= '+elems[i].getAttribute("id"));
      if (id=="countryotherfieldtitle" || id =="class_otherfieldtitle") {
         // labels are in field column on right
         changeTitleStyle(id,'fieldcell',''); 

      } else {
         changeTitleStyle(id,'titlecell',''); 
      }   
   }   
}
}
//define error messages for each form element
var messageArray= new Array();
messageArray['title']="Title";
messageArray['firstname']="First Name";
messageArray['lastname']="Last Name";
messageArray['email']="Email";
messageArray['validemail']="Email is invalid";
messageArray['organization']="Organization";
messageArray['company']="Company";
messageArray['organizationBusiness']="Organization/Business Name";
messageArray['organizationSchool']="School/Organization Name";
messageArray['org_type']="Organization Type";
messageArray['org_id']="Organization ID must be numbers only";
messageArray['address1']="Address";
messageArray['city']="City";
messageArray['state']="State";
messageArray['province']="Province";
messageArray['zippostal']="Zip/Postal Code";
messageArray['zip']="Zip Code";
messageArray['country']="Country";
messageArray['location']="Location";
messageArray['validPostalcode']="Canadian Postal Code is invalid";
messageArray['validCAcountry']="You have selected a Canadian Province.  Please select Canada from the Country menu.";
messageArray['validZipcode']="Zip Code is invalid";
messageArray['validUScountry']="You have selected a US state.  Please select USA from the Country menu.";
messageArray['specifycountry']="Specify country";
messageArray['source']="Referral source";
messageArray['phonecntry']="Please enter a valid phone country code (all numbers, + and - OK).";
messageArray['phonearea']="Please enter a valid area code (all numbers).";
messageArray['iphone']="Please enter a valid phone number (6-10 digits, + and - OK).";
messageArray['phone']="Please enter a valid phone number (7 digits, + and - OK).";
messageArray['phoneext']="Please enter a valid phone extension (all numbers).";
messageArray['classification']="Self Description";
messageArray['classOther']="Self Description - Other: specify";
messageArray['learningCenter']="Contact by Scientific Learning Representative?";
messageArray['job']="Job Title";
messageArray['org_type_PS']="If you are a School Administrator or a Teacher, Organization Type must be 'Public School' or 'Independent School'";
messageArray['retypeemail']="Re-type Email";
messageArray['veremail']="Email and re-typed Email are not identical";
messageArray['password']="Password";
messageArray['passwordchar']="Password contains invalid characters (use letters and numbers only)";
messageArray['passwordlength']="Password must be 4-8 characters";
messageArray['retypepassword']="Confirm Password";
messageArray['verpassword']="Password and Confirm Password are not identical";
messageArray['credential']="License Credential";
messageArray['yrspractice']="Years in Practice";
messageArray['yrspracticedigits']="Years In Practice must be numbers only.";
messageArray['tdrop']="Type of Project";
messageArray['ddrop']="Demographics of School";
messageArray['sdrop']="Number of Students";
messageArray['qualified']="Are you a qualified professional?";


// end object