$(function() {
    function addLoginLink() {
        var link = $("<a />")
            .attr("href", "/auth/login?return=" + encodeURIComponent(location.href))
            .text("Войти");
        $("#user_area").append(link);
    }

    function addUserInterface(user) {
        var form = $("<form class='inline' />")
            .attr("action", "/auth/logout")
            .attr("method", "post")
            .append($("<div />")
                .append($("<input type='hidden' name='return' />").val(location.href))
                .append($("<button type='submit'>Выйти</button>"))
            )
        ;
        $("#user_area")
            .append($("<span />").text(user.display_name))
            .append(" ")
            .append(form)
        ;

        form.submit(function() {
            $.post("/auth/logout", function() {
                $("#user_area").text("");
                addLoginLink();
                removeSiteOwnersInterface();
            });
            return false;
        });

        if (user.is_site_owner) {
            addSiteOwnersInterface();
        }
    }

    function addSiteOwnersInterface() {
        function addEditLink(container, text, href) {
            container.append(" ");
            var link = $("<a />")
                .addClass("edit")
                .text(text)
                .attr("href", href)
                .appendTo(container);
        }

        function makeLinkEditable() {
            addEditLink($(this).parent(), "изменить", $(this).attr("href") + "/edit");
        }

        function makePageEditable() {
            addEditLink($(this), "изменить", location.href + "/edit");
        }

        $("h2.editable").each(makePageEditable);
        $("a.editable").each(makeLinkEditable);

        $("h2.art-reviews-add").each(function() {
            addEditLink($(this), "добавить", "/art-reviews/add");
        });
        $("h2.art-authors-index").each(function() {
            addEditLink($(this), "добавить", "/art-reviews/authors/add");
        });
        $("h2.blog-index").each(function() {
            addEditLink($(this), "управление", "/blog/manage");
            addEditLink($(this), "добавить", "/blog/entries/add");
        });
    }

    function removeSiteOwnersInterface() {
        $("a.edit").remove();
    }

    $.get("/auth?format=json", function(user) {
        if (user.is_logged_in) {
            addUserInterface(user);
        } else {
            addLoginLink();
        }
    });
});
