/**
 * @module    emailobfuscator
 * @author    Kaj Haffenden
 *
 * 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
 
  /**
   * 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) {
        var email = href.replace(patternHref, '$1' + '@' + '$2');
        if (href != email)  // ensure a replacement was made
          tags[i].setAttribute('href', 'mailto:' + email);
      }
    }
    
    // find and replace unlinked email address references

    if (typeof(Prototype) !== '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');
    }

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


