/**
 * @module    emailobfuscator
 * @authors    Kaj Haffenden, Abhi Beckert
 *
 * Replaces obfuscated email addresses in links and in general text.
 *
 * This JS is self-contained but will play nicely with Prototype.JS if it is installed.
 *
 * Tested in IE7, FF3, Chrome, Safari
 */
var EmailObfuscator = {

  /**
   * Configuration -- must match the equivalent PHP class.
   */
  requestPath:          "email/",
  atSignReplacement:    "[)][(]",     // Must be escaped for regex
  
  initialize: function() {
    if (window.addEventListener) { // modern browsers
      window.addEventListener('DOMContentLoaded', function() { EmailObfuscator.deObfuscate(); }, false);
      
    } else if (window.attachEvent) { // older versions of internet explorer
      document.write('<script type="text/javascript" defer="defer">EmailObfuscator.deObfuscate();</script>'); // this will execute before images are downloaded, but will sometimes run before all links are in the page and may miss some elements
      window.attachEvent('onload', function() { EmailObfuscator.deObfuscate(); }); // this will always run, but not until after all images are downloaded
    }
  },
  
  /**
   * Finds all <a> tags with mailto: links, and finds all other email addresses, and decodes them to display as normal.
   */
  deObfuscate: function() {
    
    var email_regex     = "([a-zA-Z0-9!#$%&'*+-\/=?^_`{|}~.]+)" + this.atSignReplacement + "([a-zA-Z0-9-.]+)";
    var patternHref     = new RegExp(".*" + this.requestPath + email_regex);        // the .* at the beginning is for HREFs that contain entire URL (e.g. IE)
    var patternUnlinked = new RegExp(this.requestPath + email_regex);
    
    // find and replace href="mailto:" links
    var tags = document.getElementsByTagName('a');
    var tagsLen = tags.length;
    for (var i=0; i<tagsLen; i++) {
      var href = tags[i].getAttribute('href');
      if (!href)
        continue;
      
      var email = href.replace(patternHref, '$1' + '@' + '$2');
      if (href != email)  // ensure a replacement was made
        tags[i].setAttribute('href', 'mailto:' + email);
    }
    
    // find <span> email addresses
    if (typeof($$) !== 'undefined')                // use Prototype.JS if it is available
      var tags = $$('span.obfuscated-email');
    else {
      this.registerIfNeeded_getElementsByClassName();     // ensure we have access to this function
      var tags = document.getElementsByClassName('obfuscated-email', 'span');
    }
    
    var tagsLen = tags.length;
    for (var i=0; i<tagsLen; i++) {
      tags[i].innerHTML = tags[i].innerHTML.replace(patternUnlinked, '$1' + '@' + '$2');
      
      if (tags[i].parentNode.tagName == 'A') {
        var href = tags[i].parentNode.getAttribute('href');
        if (href) {
          var email = href.replace(patternHref, '$1' + '@' + '$2');
          if (href != email)  // ensure a replacement was made
            tags[i].parentNode.setAttribute('href', 'mailto:' + email);
        }
      }
    }

  },
  
  /**
   * Checks if the getElementsByClassName function is available (it will be in FF, etc. but not IE7); if not, create it
   */
  registerIfNeeded_getElementsByClassName: function() {
    
    if (!document.getElementsByClassName) {                                     // check if the browser supports it natively
      document.getElementsByClassName = function(className, parentElement) {    // otherwise define it
        var pattern = new RegExp("\\b"+className+"\\b");
        var elementsWithClass = new Array();
        var tags = document.getElementsByTagName(parentElement);
        var tagsLen = tags.length;
        for (i=0, j=0; i<tagsLen; i++) {
          if (pattern.test(tags[i].className))
            elementsWithClass[j++] = tags[i];
        }
        return elementsWithClass;
      };
    }
  }
  
};

EmailObfuscator.initialize();

