// validates that the field value string has one or more characters in it
function isSet(elem) {
  var str = elem.value;
  var re = /.+/;
  if(!str.match(re)) {
    return false;
  }
  return true;
}

//validates that the entry is a positive or negative number
function isNumber(elem) {
  var str = elem.value;
  var re = /^[-]?\d*\.?\d*$/;
  str = str.toString();
  if (!str.match(re)) {
    return false;
  }
  return true;
}


// validates that the entry is formatted as an phone number
function isPhoneValid(elem) {
  var str = elem.value;
  var re = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
  if (!str.match(re)) {
    return false;
  }
  return true;
}               

// validates that the entry is formatted as an e-mail address
function isEmailValid(elem) {
  var str = elem.value;
  var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
  if (!str.match(re)) {
    return false;
  }
  return true;
}

// validate that the user made a selection, skips first Item
function isSelected(elem) {
  if (elem.selectedIndex == 0) {
    return false;
  }
  return true;
}

// validate that the user made a selection
function isChecked(elem) {
  return elem.checked;
}

// validate that the user has checked one of the radio buttons
function isRadioChecked(elem) {
  for (var i = 0; i < elem.length; i++) {
    if (elem[i].checked) {
      return true;
    }
  }
  return false;
}

function setFocus(elem) {
  elem.focus();
}

function validateForm(form) {

  if (!isSet(form.name)) {
    alert("Please enter your \"Name\" before submitting the form");
    setFocus(form.name);
    return false;
  }

  if (isSet(form.email)) {
    if (!isEmailValid(form.email)) {
      alert("INVALID EMAIL ADDRESS.\n\nYour email address should follow this general format:     \n\nusername@domainname.com\n\n");
      setFocus(form.email);
      return false;
    }
  } else {
    alert("Please enter your \"Email Address\" before submitting the form");
    setFocus(form.email);
    return false;
  }

  if (isSet(form.phone)) {
    if (!isPhoneValid(form.phone)) {
      alert("INVALID PHONE NUMBER.\n\nYour phone number should follow this general format:     \n\n(xxx) xxx-xxxx\n\n");
      setFocus(form.phone);
      return false;
    }
  }

  return true;
}
