
// A utility function that returns true if a string contains only
// whitespace characters.
function isblank(s)
{
  for(var i = 0; i < s.length; i++) 
  {
   var c = s.charAt(i);
   if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
  }
  return true;
}

// A utility function to determine if two fields contents match
function isMatching(a,b)
{
 	if (a.value  == b.value)
	{
		return true;
	}
	else
	{
		alert("Your email address does not match the confirmation of your email address. Please check both.");
		return false;
	}
}

// Function:        checkInt
// Description:     This verifies whether the field contains a valid integer
// Input arguments: objName (form field)
//                  fieldName (string)
// Return value:    boolean (true if problem)
// Note:            
// 
function isInt(objName) {

  if (isNaN(objName.value)){   // not a number
    return false;
  } else if(parseInt(objName.value) != objName.value) {  // not an integer
    return false;
  } 
  return true;
}

// Function:        checkEmail
// Description:     This verifies whether the field contains a valid email address
// Input arguments: str (string)
// Return value:    boolean (true if valid email address)
function checkEmail(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	// don't validate a blank email address
	if (isblank(str)) return true;

	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}


	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }

	 /* 
	Allowing for multiple emails -- removing check for double * or triple .
	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }


	 if (str.indexOf(" ")!=-1){
	    return false;
	 }
	*/

	 return true;
}


function getDescription(s)
{
	if (s.description)
		return s.description;
	else {
		if (s.type == "radio" && eval("document.forms[0]."+s.name+"[1].description") ) { 
			return eval("document.forms[0]."+s.name+"[1].description")
		} 
		if (s.type == "checkbox") {
		   	 idName = s.name.replace("[]","");
			 if (eval("document.forms[0]."+idName+"[1].description") ) {
			 	return eval("document.forms[0]."+idName+"[1].description");
			 } 
		}
		return s.name;
	}
}

function getMsg(e, msg) {
	if (e.msg) {
		return e.msg;
	} else {
		return getDescription(e) + msg; 
	}
}

// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verify(f)
{
  var msg;
  var empty_fields = "";
  var errors = "";

  // Loop through the elements of the form, looking for all text,
  // validating postal codes, phone number and checking if the field is
  // blank. If the particular field has an invalid format then this
  // method will put together error messages for fields that are wrong. 
  // Rules for validation:
  // Firstname must NOT be blank
  // Middlename is optional
  // Lastname is optional
  // Phone must be a valid phone number '(nnn)nnn-nnnn' or 'nnn-nnnn'
  // Postal Code must be of the form 'lnl nln' or 'lnlnln'
  var radioButtons = new Array();    
  var checkBoxes = new Array();    
  var errElement = null;



  for(var i = 0; i < f.length; i++) 
  {
    var e = f.elements[i];
	// alert("checking A "+e.description);

    // check the manditory radio buttons and checkboxes
    if ( (e.type == "radio") && eval("f."+e.name+"[1]") && eval("f."+e.name+"[1].isManditory")) { 
			// alert ("Checking" + eval("f."+e.name+"[1]") );
		if (!radioButtons[e.name]) { 
			var rbValid = false;
    	  	// alert (e.name + " = " + e.value + " = " + e.checked + eval("f."+e.name+".length") );
			var rbLength = eval("f."+e.name+".length");
			for(var j = 0; j < rbLength; j++) {
				// alert ("checking f."+e.name+"["+i+"].checked = " + eval("f."+e.name+"["+i+"].checked") );
				if ( eval("f."+e.name+"["+j+"].checked") )  {
					rbValid = true;
				}
			}
			if (!rbValid) { errors += getMsg(e," must be selected \n"); errElement = e; };
		}
	    radioButtons[e.name] = 1;
    } 

    if (e.isInteger) {
	if (!isInt(objName)) {
		errors += getMsg(e, " must be an integer number");
	}
    }


    if (e.isEmail) {
        if (!checkEmail(e.value)) {
        	if (f.jslang == "fr") { 
        	        errors += "L'adresse de ce courriel doit être valide"; 
        	} else { 
                	errors += "Email Address must be a valid email address.";
                }
        }	
    }


    if ((e.isManditory) ||
        (e.type == "text" && e.isPostal) ||
        (e.type == "text" && e.isPhone))
    {
    	// alert("checking "+e.description);
      // first check if the field is empty
      if ((e.value == null) || (e.value == "") || isblank(e.value))
      {
      	// alert("found "+e.description);
        empty_fields += "\n          " + getDescription(e);
        continue;
      }
    
      // Now check for phone if it is numeric with right format
      if (e.type == "text" && e.isPhone) 
      {
        // trim out blank space in phone number before validation
        if (e.value.indexOf(' ') != -1)
        {
          var no_blank = "";
          for (var i = 0; i < e.value.length; i++)
          {
            if (e.value.substring(i, i+1) != ' ') 
            {
              no_blank += e.value.substring(i, i+1); 
            }
          }
        }
        else
        {
          no_blank = e.value;
        }
        if (no_blank.length != 8 && no_blank.length !=13) 
        {
          errors += "- The field " + getDescription(e) + " " + "must be " +
                    "with format 'nnn-nnnn or '(nnn)nnn-nnnn'\n";
        }
        else if (no_blank.length == 8)
        {
          temp_phone = "" + no_blank.substring(0,3) + 
                       no_blank.substring(4,8);
          var v2 = parseInt(temp_phone);
          if ((v2 != temp_phone) || (isNaN(v2)) || 
              (no_blank.indexOf('-') != 3))
          {       
            errors += "- The field " + getDescription(e) + " " +
                      "must be with format 'nnn-nnnn'.\n";                
          }
        }
        else if (no_blank.length == 13)
        {
          temp_phone = "" + no_blank.substring(1,4) + 
                       no_blank.substring(5,8) + 
                       no_blank.substring(9,13);
          var v2 = parseInt(temp_phone);
          if ((v2 != temp_phone) || (isNaN(v2)) || 
              (no_blank.indexOf('(') != 0) ||
              (no_blank.indexOf(')') != 4) || 
              (no_blank.indexOf('-') != 8))
          {
            errors += "- The field " + getDescription(e) + " " +
                      "must be with format '(nnn)nnn-nnnn'.\n"; 
          }
        }
      }
      // Now check if postal code is in right format 
      if (e.type == "text" && e.isPostal)
      {
        if (e.value.length != 6 && e.value.length != 7)
        {
          errors += "- The field " + getDescription(e) + " " + "must be " +
                    "with format 'lnlnln' or 'lnl nln'\n";
        }
        else if (e.value.length == 6)
        {
          var valid_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + 
                            "abcdefghijklmnopqrstuvwxyz";
          var valid_num = "0123456789";
          var flag_alpha = true;
          var flag_num = true;
          for (var i = 0; i < e.value.length; i++)
          {
            temp_postal = "" + e.value.substring(i, i+1);
            if ((i == 0) || (i == 2) || (i==4))
            {
              if (valid_alpha.indexOf(temp_postal) == "-1")
                 flag_alpha = false;
            }
            else if ((i == 1) || (i == 3) || (i == 5))
            {
              if (valid_num.indexOf(temp_postal) == "-1") 
              flag_num = false;
            }
          }
          if (!flag_num || !flag_alpha)
          {
            errors += "- The field " + getDescription(e) + " " +
                       "must be in the format of 'lnlnln'.\n";
          }                         
        }
        else if (e.value.length == 7)
        {
          var valid_alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + 
                            "abcdefghijklmnopqrstuvwxyz";
          var valid_num = "0123456789";
          var flag_alpha = true;
          var flag_num = true;
          var flag_blank = true;
          for (var i = 0; i < e.value.length; i++)
          {
            temp_postal = "" + e.value.substring(i, i+1);
            if ((i == 0) || (i == 2) || (i==5))
            {
              if (valid_alpha.indexOf(temp_postal) == "-1") 
                 flag_alpha = false;
            }
            else if (i == 3)
            {
              if (temp_postal != " ") flag_blank = false;
            }
            else if ((i == 1) || (i == 4) || (i == 6))
            {
              if (valid_num.indexOf(temp_postal) == "-1")
                 flag_num = false;
            }
          }
          if (!flag_num || !flag_alpha || !flag_blank)
          {
            errors += "- The field " + getDescription(e) + " " +
                      "must be in the format of 'lnl nln'.\n";
          }  
        }                       
      }
    }
  }  
  // Now, if there were any errors, then display the messages, and
  // return false to prevent the form from being submitted. Otherwise
  // return true.
  if (!empty_fields && !errors) return true;
  msg = "Your entry could not be sent because it contained errors:\n";
  if (f.jslang == "fr") { msg = "Votre inscription n'a pas pu être enregistrée car il y avait des erreurs:\n"; } 
  if (empty_fields) 
  {
    if (f.jslang == "fr") { msg += "Vous n'avez pas remplis le(s) champs suivant(s):"; }
    else { msg += "You did not fill in the following field(s):"; } 
    msg += empty_fields + "\n";
    if (errors) msg += "";
  }
  msg += errors;

  alert(msg);
  return false;
}  

// --------------------------------------------------------------
// Below are all the hash functions and menthods to implement
// a hash object in Javascript.  This object is implemented 
// like the following:
// 
// var hash = new Hash(0);
// hash.add("Ain (01)","Burgundy");
// hash.add("Aisne (2)","Burgundy");
// hash.add("Alliers (3)","Burgundy");
// -------------------------------------------------------------

// The actual hash object
function Hash(n)
{
	this.arr = new Array(n);
	this.get = h_getValue;
	this.add = h_addObject;
	this.toString = h_stringArray;
}

function h_getValue(name)
{
	a = this.arr;
	if (a == null) { return null; }
	for(var i = 0; i < a.length; i++)  {
		n2 = a[i].substring(0,a[i].indexOf('|'));
		if (n2 == name) {
			return a[i].substring(a[i].indexOf('|')+1,a[i].length);
		}
	}
	return null;
} 

function h_addObject(name, value)
{
	a = this.arr;
	if (a == null) { 
		// alert("adding to empty array " + name + "|" + value);
		this.arr = new Array(name + "|" + value);
		return; 
	}
	a2 = new Array(a.length+1);
	for(var i = 0; i < a.length; i++)  {
		a2[i] = a[i];
	}
	a2[a.length] = name + "|" + value;
	// alert("adding to array l=" + a2.length + name + "|" + value);
	this.arr = a2;
} 

function h_stringArray()
{
	var msg;
	
	for(var i = 0; i < this.arr.length; i++)  {
		msg = msg + this.arr[i];
	}
	return msg;
}

