// avatar-link.js
// Makes the avatar picture a link to the user's profile if we can

(function($) {

    var plugin = Echo.createPlugin({
	    "name": "AvatarLink",
	    "applications": ["Stream"],
	    "init": function(plugin, application) {
		    plugin.extendRenderer("Item", "avatar", plugin.renderers.avatar, "AvatarLink");
            plugin.extendRenderer("Item", "authorName", plugin.renderers.authorName, "AvatarLink");
	    }
    });

    plugin.makeLink = function(el, href, type) {
        if (type === 'iframe') {
            $(el).addClass("echo-clickable").click(function() {
                Shadowbox.open({
                    player:     'iframe',
                    title:      'User Profile',
                    content:    href,
                    height:     600,
                    width:      900
                });
            });
        }
        else if (type === 'link') {
            $(el).wrapInner($('<a></a>').attr({href: href, target: '_blank', rel: 'nofollow'}));
        }
        return el;
    }

    plugin.addCss(".echo-item-authorName a, .echo-item-authorName a:visited, .echo-item-authorName a:active, .echo-item-authorName a:link { color: inherit; text-decoration: none }" +
        ".echo-item-authorName a:hover, .echo-item-authorName.echo-clickable:hover { color: inherit; text-decoration: underline }"
    );

    plugin.renderers = {};

    plugin.renderers.avatar = function(element, dom) {
        var content = this.parentRenderer("avatar", arguments);
        $(element).append(content);
        
        var user_link = get_user_link(this.data);
        if (user_link) {
            this.user_link = user_link;
            plugin.makeLink(element, user_link.href, user_link.type);
        }
    }

    plugin.renderers.authorName = function(element, dom) {
        var content = this.parentRenderer("authorName", arguments);
        $(element).append(content);

        var item = this;
        if (item.user_link) {
            content = plugin.makeLink(element, item.user_link.href, item.user_link.type);
        }
    }

    function get_user_link(o) {
        var retVal = {};
        var matches;
        if (typeof o.actor !== 'undefined') {
            matches = /^https:\/\/umg\.janraincapture\.com\/oauth\/public_profile\?uuid=([a-z0-9-]+)$/.exec(o.actor.id);
            if (matches) {
                retVal.type = 'iframe';
                retVal.href = "/_global/ucid/PublicProfile.aspx?uuid=" + matches[1];
                return retVal;
            }
            
            matches = /^http:\/\/twitter\.com\/[a-zA-Z0-9_-]+$/.exec(o.actor.id);
            if (matches) {
                retVal.type = 'link';
                retVal.href = matches[0];
                return retVal;
            }
        }
        return null;
    }

})(jQuery);
