/*!
 * Linkifier plugin for jQuery
 * Goes through jQuery elements recursively and turns URLs into links
 *
 * Example usage:
 * $("body").linkify(); // Linkify URLs in all text nodes inside body
 * $("body > *").linkify(); // Linkify children of body, but not body itself
 * $("span").linkify({target: '_blank'});
 *
 * Authors: Raine Virta, Jyri Tuulos
 * Date: 2009-10-07
 */

(function($) {
  $.fn.linkify = function(opts) {
    var options = {};
    jQuery.extend(options, $.linkify.defaults, opts);

    function linkifyNode(node) {
      var str = String(node.textContent || node.data); // Handle different browsers
      var pos = str.search(options.regex);
      if (pos > -1) {
        var url = RegExp.$1;
        var protocol = RegExp.$2;
        var mid = node.splitText(pos);
        var end = mid.splitText(url.length);

        var linkNode = $('<a/>').addClass("linkify-link");

        // If protocol is empty, we can assume url to have matched because of 'www' as subdomain, thus adding 'http://'
        linkNode.attr('href', (protocol == "" ? "http://" : '') + url);

        if (options.truncateThreshold > 0 && url.length > options.truncateThreshold) {
          linkNode.attr("title", url);
          linkNode.text(url.substring(0, options.truncateLength) + "…");
        } else {
          linkNode.text(url);
        }

        if (options.target) {
          linkNode.attr('target', options.target);
        }

        mid.parentNode.replaceChild(linkNode[0], mid);
        linkifyNode(end);
      }
    }

    function linkifyChildren(element) {
      for(var i = 0; i < element.childNodes.length; i++){
        var child = element.childNodes[i];
        if (child.nodeType == 3) {
          linkifyNode(child);
        } else if(child.hasChildNodes() && 
            !$(child).hasClass("linkify-link")) {
              linkifyChildren(child);
        }
      };
    }
    
    return this.each(function() {
      linkifyChildren(this);
    });
  };

  $.linkify = {};
  $.linkify.defaults = {
    target: false,
    regex: /((?:(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|www\.\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?[^\.,\s])/,
    truncateThreshold: 0,
    truncateLength: 50
  };
})(jQuery);
