/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

function valid(address) {
  if (typeof address !== 'string') {
    return false;
  }

  // http://blog.gerv.net/2011/05/html5_email_address_regexp/
  var regex = /^[\w.!#$%&'*+\-/=?\^`{|}~]+@[a-z\d-]+(\.[a-z\d-]+)+$/i;

  var parts = address.split('@');

  return (regex.test(address) &&
          address.length <= 254 &&
          parts[0].length <= 64 &&
          parts[1].length <= 253);
}

function canonicalized(s) {
  // Normalize case
  s = s.toLowerCase();

  var parts = s.split('@');
  var lhs = parts[0];
  var rhs = parts[1];

  // Ignore dots
  lhs = lhs.replace(/\./g, '');

  // Trim plus addresses
  if (lhs.indexOf('+') > -1) {
    lhs = lhs.slice(0, lhs.indexOf('+'));
  }

  // Normalize googlemail.com to gmail.com
  if (rhs === 'googlemail.com') {
    rhs = 'gmail.com';
  }

  // Reject non-gmail domains
  if (rhs !== 'gmail.com') {
    return NaN; // Because it's falsey and not equal to itself
  }

  return lhs + '@' + rhs;
}

function compare(a, b) {
  // Both arguments must be valid email addresses
  if (!valid(a) || !valid(b)) {
    return false;
  }

  a = canonicalized(a);
  b = canonicalized(b);

  return a === b;
}

exports.compare = compare;
exports.valid = valid;

@@ -347,16 +347,39 @@
 regexp/%0A
+  // jshint maxlen:154%0A
   var re
@@ -391,10 +391,17 @@
  /%5E%5B
-%5Cw
+a-zA-Z0-9
 .!#$
@@ -409,49 +409,123 @@
 &'*+
-%5C-
 /=?
-%5C
 %5E
+_
 %60%7B%7C%7D~
+-
 %5D+@%5Ba-z
-%5Cd-%5D+(%5C.%5Ba-z%5Cd-%5D+)+
+A-Z0-9%5D(?:%5Ba-zA-Z0-9-%5D%7B0,253%7D%5Ba-zA-Z0-9%5D)?(?:%5C.%5Ba-zA-Z0-9%5D(?:%5Ba-zA-Z0-9-%5D%7B0,253%7D%5Ba-zA-Z0-9%5D)?)*
 $/
-i
 ;%0A%0A 

Update the html5 email regex as per gerv's blog