var whitespace = " \t\n\r"


function validateForm(tempFormName)

{
  if (validate(tempFormName))
  		 {  tempFormName.submit();    }
}





function isEmpty(s)
{
  return ((s == null) || (s.length == 0))
}

function isWhitespace (s)
{ var i;
  if (isEmpty(s)) return true;
  for (i = 0; i < s.length; i++){
    var c = s.charAt(i);
    if (whitespace.indexOf(c) == -1) return false;
  }
  return true;
}

function isCharsInBag (s, bag)
{
  var i;
  // Search through string's characters one by one.
  // If character is 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) return false;
  }
  return true;
}

function validate(theForm)
{
  var errMesg = "";
  var loginName = theForm.usrUserID.value = theForm.usrUserID.value.toLowerCase();
  var usrUserID = theForm.usrUserID.value;

  //SET THE LOCALE EQUAL TO THE USRLOCALE
  theForm.Locale.value = theForm.usrLocale.options[theForm.usrLocale.selectedIndex].value;

  // VALIDATION OF THE LOGIN NAME (MANDATORY)
  if ( !isCharsInBag( loginName, "abcdefghijklmnopqrstuvwxyz0123456789.-_" ))
  {
    errMesg += "Login name has invalid characters.\n" ;
  } else if (! isCharsInBag( loginName.charAt(loginName.length - 1),"abcdefghijklmnopqrstuvwxyz0123456789"))
  {
    errMesg += "Login name must end in an alphanumeric character.\n";
  } else if ( !isCharsInBag( loginName.charAt(0),"abcdefghijklmnopqrstuvwxyz0123456789"))
  {
    errMesg += "Login name must start with an alphanumeric character.\n";
  } else if ( loginName.length < 3 )
  {
    errMesg += "Login name must be 3 or more characters.\n" ;
  }

  // VALIDATION OF THE PASSWORD (MANDATORY)
  if ( theForm.newpasswd.value.length < 5 )
  {
    errMesg += "Password must be at least 5 characters.\n";
  }
  else if ( theForm.newpasswd.value != theForm.RPasswd.value )
  {
    errMesg += "Your passwords do not match. Please retype and try again.\n" ;
  }

  // CHECK TO MAKE SURE STATE IS PROVIDED IF COUNTRY IS US
  if (
    theForm.usrCn.options[theForm.usrCn.selectedIndex].value== "US" && 
    (theForm.usrSt.options[theForm.usrSt.selectedIndex].text== "Not Selected")){
    errMesg += "State not selected.\n";
  }

  // CHECK ALL THE REQUIRED INFORMATION FIELDS.
  // FIRST_NAME AND LAST_NAME ARE MANDATORY
  { var Q = ""; // this block determines lifespan of Q
    if (isWhitespace(theForm.usrfirst.value)) Q += "  -First name\n";
    if (isWhitespace(theForm.usrlast.value)) Q += "  -Last name\n";

    // ADD CHECKS FOR ADDITIONAL FIELDS HERE EXACTLY AS ABOVE
    if ( Q.length> 0 )
    {
      errMesg += "Please provide valid values for:\n" + Q ;
    }
  }

  if (errMesg != ""){
    alert(errMesg);
    return false;
  }

  return true;
}
// END OF VALIDATE FUNCTION


