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, dropDown) {
        input.closest("form").find(".quick-nav-drop-down").append(dropDown);
    };
        
    $("#quick-search-query").quicksearch("/json/contentnamesearch.action?query=", null, {
        dropdownPostprocess : AJS.quicksearch.dropdownPostprocess,
        dropdownPlacement : quickNavPlacement 
    });
    if ($("#space-blog-search-query").length && ("#confluence-space-key").length) {
	    $("#space-blog-search-query").quicksearch("/json/contentnamesearch.action?type=blogpost&spaceKey=" + 
	    		AJS("i").html($("#confluence-space-key").attr("content")).text() + "&query=", null, {
	        dropdownPostprocess : AJS.quicksearch.dropdownPostprocess,
	        dropdownPlacement : quickNavPlacement 
	    });
    };
});
