$(document).ready(function() {
    $.each($(".code"), function() {
        var div = $(document.createElement("div"));
        div.css({
            "text-align": "center",
            "background-color": "#e9e9e9"
        });
        div.addClass("pad4");
        div.addClass("corner5px");
        var toggle = $(document.createElement("a"));
        toggle.attr("title", "Show/hide this sourcecode box");
        toggle.click(function() {$(this).parent().next().slideToggle(500);});
        toggle.css({"cursor": "pointer"});
        toggle.text(" [ show/hide ] ");
        div.append(toggle);
        var enhance = $(document.createElement("a"));
        enhance.attr("title", "Enhance code with token mouseovers and codesearch links!");
        enhance.click(function() {
            $(this).fadeOut(1000);
            enhance_code($(this).parent().next());
        });
        enhance.css({"cursor": "pointer"});
        enhance.text(" [ enhance! ]");
        div.append(enhance);
        $(this).prepend(div);
    });
});

function jqmap(func, obj) {
    /** Asynchronously apply func to jquery object
        Avoids doing bulk operations at once
    **/
    function inner(i) {
        if(i < obj.length) {
            func(obj.get(i));
            setTimeout(function() {inner(i + 1)}, 10);
        }
    }
    inner(0);
}

function enhance_code(code) {

    function ajax_tip(e) {
        e.cluetip({
            activation: 'click',
            width: 600,
            cluetipClass: 'jtip',
            arrows: true,
            sticky: true,
            closePosition: 'bottom',
            closeText: '[close]',
            ajaxCache: false,
        });
    }

    function enhance_type(query, type, color) {
        jqmap(function(x) {
            var text = $(x).text();
            var a = $(document.createElement("a"));
            a.attr("title", type+": "+text);
            a.css("background-color", color);
            a.addClass("point");
            text = "search?"+type+"="+text;
            a.attr("href", text);
            a.attr("rel", text);
            ajax_tip(a);
            a.append($(x).replaceWith(a));
        }, $(code).find(query));
    }

    enhance_type(".nn, .n, .nb, .nd, .nx, .nv, .vg", "variable", "#ffc")
    enhance_type(".k, .kt", "keyword", "#cfc")
    enhance_type(".nf", "function", "#def")
    enhance_type(".nc", "class", "#fdd")
}
