AJS.toInit(function ($) {

    /**
     * function to add a tooltip showing the space name to each drop down list item
     */
    AJS.quicksearch = AJS.quicksearch || {};
    AJS.quicksearch.dropdownPostprocess = function (list) {
         $("a span", list).each(function () {
            var $a = $(this);
            // get the hidden space name property from the span
            var spaceName = AJS.dropDown.getAdditionalPropertyValue($a, "spaceName") || "";

            // we need to go through html node creation so that all encoded symbols(like &gt;) are displayed correctly
            if (spaceName) {
                spaceName = " (" + AJS("i").html(spaceName).text() + ")";
            }

            $a.attr("title", $a.text() + spaceName);
        });
    };

    /**
     * Append the drop down to the form element with the class quick-nav-drop-down
     */
    var quickNavPlacement = function (input) {
        return function (dropDown) {
            input.closest("form").find(".quick-nav-drop-down").append(dropDown);
        };
    };
    var quickSearchQuery = $("#quick-search-query"),
        spaceBlogSearchQuery = $("#space-blog-search-query"),
        confluenceSpaceKey = $("#confluence-space-key");
    quickSearchQuery.quicksearch("/json/contentnamesearch.action", null, {
        dropdownPostprocess : AJS.quicksearch.dropdownPostprocess,
        dropdownPlacement : quickNavPlacement(quickSearchQuery)
    });
    if (spaceBlogSearchQuery.length && confluenceSpaceKey.length) {
        spaceBlogSearchQuery.quicksearch("/json/contentnamesearch.action?type=blogpost&spaceKey=" + 
                AJS("i").html(confluenceSpaceKey.attr("content")).text(), null, {
            dropdownPostprocess : AJS.quicksearch.dropdownPostprocess,
            dropdownPlacement : quickNavPlacement(spaceBlogSearchQuery)
        });
    };
});
