﻿// blank-links.js
// Sets target="_blank" on all links in the item bodies

(function($) {

    var plugin = Echo.createPlugin({
	    "name": "BlankLinks",
	    "applications": ["Stream"],
	    "init": function(plugin, application) {
		    plugin.extendRenderer("Item", "body", plugin.renderers.body, "BlankLinks");
            plugin.extendRenderer("Item", "sourceIcon", plugin.renderers.sourceIcon, "BlankLinks");
	    }
    });

    plugin.renderers = {};

    plugin.processLinks = function() {
        var href = $(this).attr("href");
        if (typeof href === 'string' && href.substr(0,4) === 'http' && getDomain(href) !== getDomain(window.location.href)) {
            $(this).attr("target", "_blank");
        }
        else {
            $(this).attr("target", "_top");
        }
    }

    plugin.renderers.body = function(element, dom) {
        this.parentRenderer("body", arguments);
        element.find('a').each(plugin.processLinks);
    }

    plugin.renderers.sourceIcon = function(element, dom) {
        this.parentRenderer("sourceIcon", arguments);
        element.parent('a').each(plugin.processLinks);
    }

    function getDomain(url) {
        var matches;
        if (matches = /^https?:\/\/(?:[a-z0-9-]+\.)*([a-z0-9-]+\.[a-z0-9-]+)(?:\/|$)/.exec(url)) {
            return matches[1];
        }
        return "";
    }

})(jQuery);
