$(function() {
    (function() {
        var k = [0x56,-0xc,-0x11,0x50,0x34,0xa9,-0x11,0x6b,0x55,0x4b,0x3,0x3c,0x9a,0x1,0x78,0xb3,-0x3,0xb1,0x3d,0xd3,0x9b,0xd2,0xcb,0x9f,0x6,0xd1,0xd1,0x65,-0x18,0xbd,0x2d,0x9f,0xb1,-0x11,0x8d,0xd8,-0xc,-0x4,0xbb,0xc3,0xb8,0xa1,0xb,0xae,0x3d,0xc1,0x2e,0xae,-0x1d,0x54,0x7,-0xf,0xa,0x5a,0xd0,0x8a,0x78,0x4,0x6,0x32,0x86,0x2c,0xac,-0xe];

        function deobfuscate(z) {
            var b,c,d,e,f;
            b = "";
            c = 0;

            for (f = 0; f < z.length; f++) {
                if (z.charCodeAt(f) != 38)
                    d = z.charCodeAt(f);
                else {
                    f++;
                    d = parseInt("0x" + z.charAt(f++) + z.charAt(f++), 16);
                }
                e = d - k[c];
                b = b + String.fromCharCode(e < 0 ? e + 255 : e);
                c++;
            }
            return b;
        }

        $("a.obfuscated").each(function() {
            var a = $(this);
            a
                .attr("href", deobfuscate(a.attr("href")))
                .text(deobfuscate(a.text()))
                .removeClass("obfuscated")
            ;
        });
    })();

    (function() {
        var valid_states = ['a','o','n'];
        var re = RegExp("^(.+_)([" + valid_states.join("") + "])(\.gif)$");

        $("#nav a img, a.swap-image img").each(function() {
            var img = $(this);
            var idx = 0;
            var preload_img, m, base, orig_state, ext;

            m = img.attr("src").match(re);

            if (! m) return;

            base = m[1];
            orig_state = m[2];
            ext = m[3];

            function preload_next() {
                var this_idx = idx++;

                if (valid_states[this_idx]) {
                    preload_img.attr("src", base + valid_states[this_idx] + ext);
                } else {
                    preload_img.remove();
                }
            };

            preload_img = $(document.createElement("img"))
                .css("visibility", "hidden")
                .appendTo("body")
                .load(preload_next)
                .error(preload_next)
            ;

            preload_next();

            function set_state(s) { img.attr("src", base + s + ext); }

            img
                .mouseover(function(event) { set_state("o"); })
                .mouseout(function(event) { set_state(orig_state); })
            ;
        });
    })();

    $(".success").each(function() {
        var elem = $(this);
        window.setTimeout(function() {
            elem.slideUp(1000, function() {
                elem.remove();
            });
        }, 5000);
    });

    $(".inset-links tr").click(function(event) {
        var tr = $(this);
        var a = tr.find("a:first");
        window.location.href = a.attr("href");
    });
});
