BitlyCB.expandResponse = function(data) {
    for (var r in data.results) {
        var lnk = document.querySelector('#community_links a[href="http://bit.ly/' + r + '"]');
        if (!lnk) continue;
        lnk.href = data.results[r].longUrl;
        lnk.nextSibling.nodeValue = " [" + lnk.host + "]";
    }
}
window.addEventListener("DOMContentLoaded", function() {
    var comments_heading = document.getElementById("comments");
    if (!comments_heading) return;
    if (!document.querySelectorAll) return;
    var links = document.querySelectorAll("ol.commentlist div.comment-entry a");
    var displinks = [];
    for (var i=0; i<links.length; i++) {
        if (links[i].className == 'comment-reply-link') continue;
        var a = document.createElement("a");
        a.href = links[i].href;
        var txt = links[i].firstChild.nodeValue;
        if (txt.length > 30) { 
            if (txt.substr(0,4) == "http") {
                if (txt.length > 50) {
                    txt = txt.substr(0,47) + "..." 
                }
            } else {
                txt = txt.substr(0,27) + "..." 
            }
        }
        a.appendChild(document.createTextNode(txt));
        displinks.push(a);
    }
    if (displinks.length > 0) {
        var h = document.createElement("h3");
        h.appendChild(document.createTextNode("Links from the Shot of Jaq community"));
        var ul = document.createElement("ul");
        ul.id = "community_links";
        displinks.forEach(function(a) {
            var li = document.createElement("li");
            li.appendChild(a);
            if (a.firstChild.nodeValue.substr(0,4) != "http") {
                li.appendChild(document.createTextNode(" [" + a.host + "]"));
                if (a.host == "bit.ly") {
                    BitlyClient.expand(a.href, 'BitlyCB.expandResponse');
                }
            }
            ul.appendChild(li);
        });
        comments_heading.parentNode.insertBefore(h, comments_heading);
        comments_heading.parentNode.insertBefore(ul, comments_heading);
    }
}, false);

