/**
 *  @class  The Email object contains properities and methods to validate emails
 *          and to display messages on error.
 *
 *  @constructor
 *  @requires String
 *  @param  {String}  id      the id attribute of the calling element
 *  @param  {String}  value   the email as input by the user
 *  @param  {String}  errId   id of error-display element
 *  @type void
 */
function Email(id, value, errId)
{
  this.id = id;
  this.value = value.trim();
  this.errId = errId;
}

/**
 *  ID of element containing the email.
 *  @type String
 */
Email.prototype.id = null;

/**
 *  Value of element containing the email.
 *  @type String
 */
Email.prototype.value = null;

/**
 *  Is the field in this instance required?
 *  @type boolean
 */
Email.prototype.required = false;

/**
 *  Id of element in which to display error messages.
 *  @type String
 */
Email.prototype.errId = null;

/**
 *  Error messages; set by validate() method.
 *  @type String
 */
Email.prototype.errMsg = null;

/**
 *  Marks the field as required by setting this.required to true.
 *
 *  @type void
 */
Email.prototype.setRequired = function()
{
  this.required = true;
}

/**
 *  The format() method does nothing.
 *
 *  @type String
 */
Email.prototype.format = function()
{
  return this.value;
};

/**
 *  Validates an email. Input must match regx format
 *  <code>/[%\+-\.\w]+&#64;[-\.a-z0-9]+\.[\w]+/i</code>.
 *
 *  @type boolean
 */
Email.prototype.validate = function()
{
  if (this.required && this.value == "") {
    this.errMsg = "A valid email is required.";
    return false;
  }

  if (this.value != "" &&
      !/[%\+-\.\w]+@[-\.a-z0-9]+\.[\w]+/i.test(this.value)) {
    this.errMsg = "There seems to be a problem with your email. " +
      "Please try again."
    return false;
  }

  return true;
};

/**
 *  Verifies email and reports invalid input.
 *
 *  @requires ValidateInput validateInput
 *  @return if email ok then return it else false.
 *  @type mixed
 */
Email.prototype.verify = function()
{
  if (this.validate()) {
    return this.format();
  }

  validateInput.showError(this.errId, this.errMsg);
  validateInput.newFocus = this.errId;
  return false;
};
