$(document).ready(function () {
    var ajaxHolder = null;
    var contentHolder = null;
    var animationDone = false;
    function setAnimationDone() {
        animationDone = true;
    }
    function sizeLayers(waiting) {
        var layers = $(".workspace").length;
        $(".workspace").each(function () {
            var indxto = layers - ($(".workspace").index(this) + 1);
            var sizeto = (100 - ((indxto) * 20));
            var posito = (100 - sizeto) / 2;
            $(this).animate({ "height": sizeto + "%", "width": sizeto + "%", "top": 0 - posito / 2 + "%", "left": posito + "%", "font-size": 14 - indxto + "px" }, 500, "linear");
            setTimeout(setAnimationDone, 600);
        });
    }
    function animateNew() {
        if (animationDone == false) {
            setTimeout(animateNew, 50);
        } else {
            animationDone = false;
            if ($(".level").last().children("a").length > 0) {
                $(".level").last().children("a").each(function () {
                    $(this).delay($(this).index() * 100).fadeTo(300, 1);
                });
            } else {
                $(".level").last().children("span").fadeTo(300, 1);
            }
        }
    }
    $(".level>span").live("click", function (e) {
        e.stopPropagation();
    });
    $("a:not([href^='http://'])").live("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        $('<div class="cover"></div><div class="workspace"><span class="spanner"></span><span class="level"></span></div>').appendTo("body");
        ajaxHolder = $.ajax({
            url: $(this).attr("href"),
            success: function (data) {
                if ($(data).first().is("a")) {
                    $(".level").last().append(data).find("a").fadeTo(0, 0);
                    animateNew();
                } else {
                    $(".level").last().append(data).children("span").fadeTo(0, 0);
                    animateNew();
                }
            }
        });
        $(".cover").last().fadeTo(300, 0.5);
        sizeLayers(true);
    });
    $(".workspace").live("click", function () {
        if ($(".workspace").length > 1) {
            $(".cover").last().fadeTo(300, 0, function () {
                $(this).remove();
            });
            $(this).remove();
            sizeLayers(false);
        }
    });
});
