$(function() {
    (function() {
        var chars = "`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?";

        function deobfuscate(str) {
            // QWERTY-shift!  Silly?  Yes.  Effective?  Uh-huh.
            var res = '', c, i, x;
            for (i = 0; i < str.length; i++) {
                c = str.charAt(i);
                x = chars.indexOf(c) + 1;
                if (x > chars.length - 1) x = 0;
                res += chars.charAt(x);
            }

            return res;
        }

        $("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");
    });
});

