$(document).ready(function() {
  $('#contact-form').submit(function() {
    if (!validateEmail($('#email-field').val())) {
      $('#email-label, #email-field, #email-field-wrapper span').addClass('form-error');
      $('#email-field').focus(function() { $('#email-label, #email-field, #email-field-wrapper span').removeClass('form-error'); });
      return false;
    }
  });
});

// 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;
}