(function(context,$) {

    "use strict";

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

        var instrument_logo_map = context.JK.getInstrumentIconMap24();

        function beforeShow(data) {
            var query = data.query;
        }

        function afterShow(data) {
        }

        function search(evt) {
            evt.stopPropagation();

            $('#search-results').empty();
            var query = $('#search-input').val();
            context.location = '#/searchResults/:' + query;

            logger.debug('query=' + query);
            if (query !== '') {
                $('#query').html(query + "\"");
                context.JK.search(query, app, onSearchSuccess);
            }

            else {
                $('#result-count').html('');
                $('#query').html('');
            }

            return false;
        }

        function onSearchSuccess(response) {

            // TODO: generalize this for each search result type (band, musician, recordings, et. al.)
            $.each(response.musicians, function(index, val) {
                // fill in template for Connect pre-click
                var template = $('#template-search-result').html();
                var searchResultHtml = context.JK.fillTemplate(template, {
                    userId: val.id, 
                    avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
                    profile_url: "/#/profile/" + val.id,
                    userName: val.name,
                    location: val.location,
                    instruments: getInstrumentHtml(val.instruments)
                });

                $('#search-results').append(searchResultHtml);

                // fill in template for Connect post-click
                template = $('#template-invitation-sent').html();
                var invitationSentHtml = context.JK.fillTemplate(template, {
                    userId: val.id,
                    first_name: val.first_name,
                    profile_url: "/#/profile/" + val.id
                });

                $('#search-results').append(invitationSentHtml);

                // initialize visibility of the divs
                $('div[user-id=' + val.id + '].search-connected').hide();
                $('div[user-id=' + val.id + '].search-result').show();

                // wire up button click handler if search result is not a friend or the current user
                if (!val.is_friend &&  val.id !== context.JK.currentUserId) {
                    $('div[user-id=' + val.id + ']').find('.btn-connect-friend').click(sendFriendRequest);
                }
                else {
                    $('div[user-id=' + val.id + ']').find('.btn-connect-friend').hide();
                }
            });

            var resultCount = response.musicians.length;
            $('#result-count').html(resultCount);

            if (resultCount === 1) {
                $('#result-count').append(" Result for \"");
            }
            else {
                $('#result-count').append(" Results for \"");
            }
        }

        function friendRequestCallback(userId) {
            // toggle the pre-click and post-click divs
            $('div[user-id=' + userId + '].search-connected').show();
            $('div[user-id=' + userId + '].search-result').hide();
        }

        function sendFriendRequest(evt) {
            evt.stopPropagation();
            var userId = $(this).parent().attr('user-id');
            context.JK.sendFriendRequest(app, userId, friendRequestCallback);
        }

        function getInstrumentHtml(instruments) {
            var instrumentLogoHtml = '';
            if (instruments !== undefined) {
                for (var i=0; i < instruments.length; i++) {
                    var inst = '../assets/content/icon_instrument_default24.png';
                    if (instruments[i].instrument_id in instrument_logo_map) {
                        inst = instrument_logo_map[instruments[i].instrument_id];
                        instrumentLogoHtml += '<img src="' + inst + '" width="24" height="24" />&nbsp;';
                    }
                }
            }
            return instrumentLogoHtml;
        }

        function events() {
            $('#searchForm').submit(search);
        }

        this.initialize = function() {
            var screenBindings = {
                'beforeShow': beforeShow,
                'afterShow': afterShow
            };
            app.bindScreen('searchResults', screenBindings);
            events();
        };

    };

})(window,jQuery);