// ==UserScript==
// @name           Lingr URL catcher
// @namespace      http://n.h7a.org/
// @author         HIROSHIMA Naoki <n at h7a dot org>
// @description    This will detect URLs in the messages and open them.
// @include        http://www.lingr.com/room/*
// ==/UserScript==

// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html

// ver 0.1: 2006-09-29
//  - experimental release 

(function ()
{
    const display_prompt = true;

    function $(id)
    {
        return document.getElementById(id);
    }

    function $V(value, defaultValue)
    {
        return value == undefined ? defaultValue : value;
    }

    function $N(value)
    {
        return isNaN(value) ? 0 : $V(value, 0);
    }

    function onLoad(e) {
        var ChatSystem = unsafeWindow["ChatSystem"];
        if (ChatSystem == null) return;

        ChatSystem.prototype._updateMessages = ChatSystem.prototype.updateMessages;
        ChatSystem.prototype.updateMessages = function(msgs, highlight, ignoreLocal) {
            if (!$N(msgs)) if (msgs[0].h != undefined) {
                var a = msgs[0].h.match(/(<a.*href)/g);
                if (a) for (var i=0; i<a.length; i++) {
                    var urls = a[i].match(/(https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:@&=+\$,%#]+[A-Za-z0-9\/])/g);
                    if (urls) {
                        var prompt = GM_getValue("prompt", display_prompt);
                        for (var j=0; j<urls.length; j++) {
                            if (prompt)
                                setTimeout(function(url) {
                                               if (window.confirm('Do you want to open '+url+' ?'))
                                                   window.open(url, '_blank');
                                           }, 10, urls[j]);
                            else
                                window.open(urls[j], '_blank');
                        }
                    }
                }
            }

            this._updateMessages(msgs, highlight, ignoreLocal);
        }

        var user_image = $("user_image");
        if (user_image)
            user_image.addEventListener("click", onClick, false);
    }

    function onClick(e) {
        if (e.shiftKey) {
            var prompt = GM_getValue("prompt", display_prompt);
            prompt = window.prompt("open URL without confirmation? (y/n):", prompt ? "n" : "y");
            if (prompt)
                GM_setValue("prompt", prompt != 'y');
        }
    }

    window.addEventListener("load", onLoad, false);
})();
