(function ($) {

    $(function () {

        // All pages:

        $(".email").each(function () {
            var recParts = $(this).find(".recipient").text().split(" ");
            var domParts = $(this).find(".domain").text().split(" ");

            var tld = domParts[domParts.length - 1];

            var rec = recParts.join(".");
            var dom = (domParts[0] == "untyped") ? "untyped.com" : domParts.join(".");

            $(this).html("<a href=\"mailto:" + rec + "@" + dom + "\">" + rec + "@" + dom + "</a>");
        });

        // Homepage:

        $("#home").each(function () {
            var spotRoot = $("#spotlight-posts");
            var spotPosts = spotRoot.find(".spotlight-post")
            var spotBg = spotRoot.find("#spotlight-bg");

            var currIndex = 0;
            var postDisplayMs = 7000;
            var postChangeMs = 1000;
            var bgFadeMs = 150;

            function changeSpotPost () {
                var nextIndex = (currIndex + 1) % spotPosts.length;
                var currPost = $(spotPosts[currIndex]);
                var nextPost = $(spotPosts[nextIndex]);
                currPost.fadeOut(postChangeMs);
                nextPost.fadeIn(postChangeMs, function () {
                    currIndex = nextIndex;
                    window.setTimeout(changeSpotPost, postDisplayMs);
                });
            }

            window.setTimeout(changeSpotPost, postDisplayMs);

            $(spotPosts[currIndex]).css("display", "block");

            spotBg.width(Math.max.apply(this, $.map(spotPosts, function(post) { return $(post).width() + 20; })))
                  .height(Math.max.apply(this, $.map(spotPosts, function(post) { return $(post).height() + 20; })));

            spotPosts.hover(
                function () {
                    $(this).addClass("hovered");
                    if(!spotBg.is(":visible")) {
                        spotBg.fadeIn(bgFadeMs);
                    }
                },
                function () {
                    $(this).removeClass("hovered");
                    if(!spotPosts.is(".hovered")) {
                        spotBg.fadeOut(bgFadeMs);
                    }
                });

            spotPosts.click(function () {
                var href = $(this).find(".read-more").attr("href");
                if(href) {
                    window.location = href;
                }
            });
        });

    });

})(jQuery);

