/*
 * Check Email string for validity
 * Paul Gregg <pgregg@pgregg.com>
 * January 2002, Updated Nov 2003, Logic fix May 2006
 * Updated May 2008 - rewrote localpart/domainpart splitting
 * http://www.pgregg.com/projects/php/code/validate_email.inc.phps
 * Copyright 2002-2008, Paul Gregg.
 */
 // ethan@waveriderdesign.com 8.26.2008 - turned into JS

// thanks to Douglas Crockford, http://javascript.crockford.com/remedial.html
String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function validateEmail(emailstr) {
    // Make the email address lower case and remove whitespace
    var lc_emailstr = emailstr.trim().toLowerCase();
    
    // Split it up into before and after the @ symbol
    var email_components = lc_emailstr.split('@');
    
    // Check that there is only one @ symbol
    // if (count($email_components) != 2)
    //   return false;

    // Everything after the last @ is the domain, before is the local part
    var domain_part = email_components.pop();
    var local_part = email_components.join('@');

    // sanitize quoted parts
    local_part = local_part.replace(/\\\./, '_');
    local_part = local_part.replace(/"[^"]+"/, '.');

    // comments ( this is a comment ) are permitted in domain parts
    domain_part = domain_part.replace(/\([^()]*\)/, '');

    // Make sure there are no more @ (we sanitized valid oes above)
    if (local_part.indexOf('@') >= 0) return false;
    
    // Check that the username is >= 1 char
    if (local_part.length == 0) return false;
    
    // Split the domain part into the dotted parts
    var domain_components = domain_part.split('.');
    
    // check there are at least 2
    if (domain_components.length < 2) return false;
    
    // Check each domain part to ensure it doesn't start or end with a bad char
    for(var domain_component in domain_components) {
      if ( domain_component.length > 0 ) {
        if (domain_component.charAt(0).match(/[\.-]/) || domain_component.charAt(domain_component.length - 1).match(/[\.-]/)) return false;
      } else return false;
    }

    // Check the last domain component has 2-6 chars (.uk to .museum)
    var domain_last = domain_components.pop();
    if (domain_last.length < 2 || domain_last.length > 6) return false;
    
    // Check for valid chars - Domains can only have A-Z, 0-9, ., and the - chars,
    // or be in the form [123.123.123.123]
    if (domain_part.match(/^\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]$/)) return true;
    if (domain_part.match(/^[a-z0-9\.-]+$/)) return true;

    // If we get here then it didn't pass
    return false;
}
