// Form validation functions

// Ensure form field contains data
function validate_nonempty(field, help)
{
  if (field.value.length == 0)
    {
      if (help != null)
        {
          help.innerHTML = "Value Required";
        }
      return false;
    }
  else
    {
      if (help != null)
        {
          help.innerHTML = "";
        }
    }
  return true;
}

function validate_length(min, max, field, help)
{
  if (field.value.length < min)
    {
      if (help != null)
        {
          help.innerHTML = "Too short";
        }
      return false;
    }
  else if (field.value.length > max)
  {
    if (help != null)
      {
        help.innerHTML = "Too long";
      }
    return false;
  }
  else
    {
      if (help != null)
        {
          help.innerHTML = "";
        }
    }
  return true;
}

// Ensure a proper email address
function validate_email(field, help)
{
  var email_regex = /^[\w\.-_\+]+@[\w-_\+]+[\.]+[\w\.-_\+]+$/;
  if (!email_regex.test(field.value))
      {
        if (help != null)
          {
            help.innerHTML = "Invalid email address";
          }
        return false;
      }
      else
        {
          if (help != null)
            {
              help.innerHTML = "";
            }
        }
  return true;
}

// Make sure everything's validating before submitting to the server
function validate_submit(form)
{
  if (validate_nonempty(form["name"], document.getElementById('name_help')) &&
      validate_nonempty(form["affiliation"], document.getElementById('affiliation_help')) &&
      validate_email(form["email"], document.getElementById('email_help')))
    {
      if (!validate_length(0, 65536, form["comments"], document.getElementById('comment_help')))
      {
        alert("Please keep your comments to a reasonable minimum");
        return;
      }
      form.submit();
    }
  else
    {
      alert("Please completely fill out the registration form before submitting");
    }
}

// Initially attempt to validate all form fields on page load
function validate_initial(form)
{
  validate_nonempty(form["name"], document.getElementById("name_help"));
  validate_nonempty(form["affiliation"], document.getElementById("affiliation_help"));
  validate_email(form["email"], document.getElementById("email_help"));
}

// Disabled, since Jonathan thinks it's mean to criticize you when you haven't done anything yet
// onload="validate_initial(document.getElementById('reg_form'))"

