
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (1 > email.indexOf("@")) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.indexOf("@") >= email.lastIndexOf(".")) {  // last dot must be after the @
        return false;
    } else if ((email.length-5) > email.lastIndexOf(".")) {  // after last dot there can be maximal 4 characters
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf("@@") >=0) { // two @ in a row is not valid
	return false;
    } else if (email.indexOf(".@") >=0) { // .@ within is not valid
	return false;
    } else if (email.indexOf("@.") >=0) { // @. within is not valid
	return false;
    } else if (email.lastIndexOf(".") == (email.length-1)) {  // . must not be the last character
	return false;
    } else if (email.lastIndexOf("@") == (email.length-1)) {  // @ must not be the last character
	return false;
    }
    return true;
};

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@&.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
};

