// ==UserScript==
// @name            tinyurl expander
// @namespace       http://twitter.com/kosugi
// @description     expands tinyurl/xrl'ed URL
// @include         *
// ==/UserScript==
//
// version: 2007-12-21T11:59:25+09:00
// author:  KOSUGI Tomo (kosugi dot tomo at gmail dot com)
// license: GPL <http://www.gnu.org/copyleft/gpl.html>
//
// TODO: cache results, allows clear caches, recursive detection

new function() {

    var doIt = function(anchor) {
        if (anchor.href.match(/^http:\/\/tinyurl\.com\/(.*)/)) {
            GM_xmlhttpRequest({
                method: 'GET',
                url: 'http://tinyurl.com/preview.php?num=' + encodeURIComponent(RegExp.$1),
                onload: function(r) {
                    if (r.responseText.match(/<a\s+id=\"redirecturl\"\s+href=\"([^\"]+)\"\s*>/)) {
                        var e = document.createElement('div');
                        e.innerHTML = RegExp.$1;
                        var url = e.textContent;
                        anchor.href = url;
                        anchor.title = url;
                    }
                }
            });
        }
        else if (anchor.href.match(/^http:\/\/xrl\.us\/(.*)/)) {
            GM_xmlhttpRequest({
                method: 'GET',
                url: 'http://metamark.net/api/rest/simple?short_url=' + encodeURIComponent(RegExp.$1),
                onload: function(r) {
                    if (r.responseText.match(/^http/)) {
                        var url = r.responseText;
                        anchor.href = anchor.title = url;
                    }
                }
            });
        }
    }

    var collectAnchors = function(node) {
        var anchors = node.getElementsByTagName('a');
        for (var n = 0, len = anchors.length; n < len; ++n) {
            doIt(anchors[n]);
        }
    }

    setTimeout(function() {
        if (window.AutoPagerize && window.AutoPagerize.addFilter) {
            window.AutoPagerize.addFilter(function(ctx) {
                ctx.forEach(function(node) { collectAnchors(node) });
            });
        }
    }, 0);

    setTimeout(collectAnchors, 0, document);
}
