(function(context,$) {

    // NOTE - not currently used. Was hooked up in header before
    // Jeff's new mockups moved search to sidebar and made search results
    // a full-blown screen. This should probably be removed, along with
    // any HTML that accompanies it. Tests too.

    "use strict";

    context.JK = context.JK || {};
    context.JK.Searcher = function(app) {
        var logger = context.JK.logger;

        var searchSectionTemplate;
        var searchItemTemplate;
        var noResultsTemplate;
        var usernames = ['Brian', 'David'];
        var userids = ['1', '2'];

        function events() {
            $('.searchtextinput').keyup(handleKeyup);
            $('.searchtextinput').focus(function(evt) {
                var searchVal = $(this).val();
                search(searchVal);
            });
            $('.searchtextinput').blur(hideSearchResults);
        }

        function templates() {
            searchSectionTemplate = $('#template-search-section').html();
            searchItemTemplate = $('#template-search-item').html();
            noResultsTemplate = $('#template-search-noresults').html();
        }

        function hideSearchResults() {
            $('.searchresults').hide();
        }

        function showSearchResults() {
            $('.searchresults').show();
        }

        function handleKeyup(evt) {
            if (evt.which === 27) {
                return hideSearchResults();
            }
            var searchVal = $(evt.currentTarget).val();
            search(searchVal);
        }

        function search(query) {
            if (query.length < 2) {
                return;
            }
            $.ajax({
                type: "GET",
                url: "/api/search?query=" + query,
                success: searchResponse,
                error: app.ajaxError
            });
        }

        function searchResponse(response) {
            ensureResultsDiv();
            updateResultsDiv(response);
            positionResultsDiv();
            showSearchResults();
        }

        function ensureResultsDiv() {
            if ($('.searchresults').length === 0) {
                var $searchresults = $('<div/>');
                $searchresults.addClass('searchresults');
                $searchresults.css({position:'absolute'});
                $('body').append($searchresults);
            }
        }

        function updateResultsDiv(searchResults) {
            var sections = ['musicians', 'bands', 'fans', 'recordings'];
            var fullHtml = '';
            $.each(sections, function() {
                fullHtml += getSectionHtml(this, searchResults);
            });
            if (fullHtml === '') {
                fullHtml += getNoResultsMessage();
            }
            $('.searchresults').html(fullHtml);
        }

        function getNoResultsMessage() {
            // No replacement needed at the moment.
            return noResultsTemplate;
        }

        function getSectionHtml(section, searchResults) {
            if (section in searchResults && searchResults[section].length === 0) {
                return '';
            }
            var items = '';
            $.each(searchResults[section], function() {
                items += getItemHtml(this);
            });
            var html = context.JK.fillTemplate(
                searchSectionTemplate,
                { section: section, items: items });
            return html;
        }

        function getItemHtml(item) {
            var replacements = {
                id: item.id,
                name: item.first_name + " " + item.last_name,
                image: item.photo_url,
                subtext: item.location
            };
            return context.JK.fillTemplate(
                searchItemTemplate, replacements);
        }

        function positionResultsDiv() {
            var bodyOffset = $('body').offset();
            var inputOffset = $('.searchtextinput').offset();
            var inputHeight = $('.searchtextinput').outerHeight();
            var resultsTop = bodyOffset.top + inputOffset.top + inputHeight;
            var resultsLeft = bodyOffset.left + inputOffset.left;
            $('.searchresults').css({
                top: resultsTop + 'px',
                left: resultsLeft + 'px'});
        }

        this.initialize = function() {
            events();
            templates();
        };
    };

 })(window,jQuery);