(function(context,$) {

  "use strict";

  context.JK = context.JK || {};
  context.JK.SearchResultScreen = function(app) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var instrument_logo_map = context.JK.getInstrumentIconMap24();

    function initializeSearchNavLinks() {
      $('.search-nav').click(function() {
        $('.search-nav.active').removeClass('active');
        $(this).addClass('active');
        setTimeout(search, 100);
        context.JK.Sidebar.searchTypeSelection($(this).data('search_text_type'));
      });
    }

    context.JK.SearchResultScreen.searchTypeSelection = function(typeSelection) {
      $('.search-nav.active').removeClass('active');
      $('.search-result-header a[data-search_text_type='+typeSelection+']').addClass('active');
    }

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

    function afterShow(data) {
    }

    function selectedSearchType() {
      var srchtype = $('.search-nav.active').data('search_text_type');
      if (srchtype === undefined) {
        srchtype = $('#search_text_type').val();
      }
      return srchtype;
    }

    function search(evt) {
      if (evt) {
        evt.stopPropagation();
      }
      
      $('#search-results').empty();
      
      var query = $('#search-input').val();
      if (query) {
        context.location = '/client#/searchResults/:' + query;
      }
      else {
        query = $('#query').html();
      }

      if (query !== '') {
        $('#query').html(query);
        query += '&search_text_type='+selectedSearchType();
        context.JK.search(query, app, context.JK.SearchResultScreen.onSearchSuccess);
      }
      else {
        $('#result-count').html('');
        $('#query').html('');
      }

      return false;
    }

    function resultDivVisibility(val, isSidebar) {
      if (isSidebar) {
        $('div[layout="sidebar"] [user-id="' + val.id + '"].sidebar-search-connected').hide();
        $('div[layout="sidebar"] [user-id="' + val.id + '"].sidebar-search-result').show();
      }
      else {
        $('div[user-id=' + val.id + '].search-connected').hide();
        $('div[user-id=' + val.id + '].search-result').show();
      }
    }

    context.JK.SearchResultScreen.onSearchSuccess = function(response) {
      $('#sidebar-search-results').show();
      searchResults(response, true);
      searchResults(response, false);
      context.JK.bindHoverEvents();
    }

    function searchResults(response, isSidebar) {
      var resultCount=0;
      var selector, template_name;
      selector = isSidebar ? '#sidebar-search-results' : '#search-results';
      $(selector).html('');

      if (response.search_type === 'musicians') {
        resultCount = response.musicians.length;
        // TODO: generalize this for each search result type (band, musician, et. al.)
        template_name = isSidebar ? "#template-musicians-sidebar-search-result" : "#template-musicians-search-result";
        
        $.each(response.musicians, function(index, val) {
          // fill in template for Connect pre-click
          var args = {
            userId: val.id, 
            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
            profile_url: "/client#/profile/" + val.id,
            userName: val.name,
            location: val.location,
            instruments: getInstrumentHtml(val.instruments)
          };
          selector = isSidebar ? '#sidebar-search-results' : '#search-results';
          $(selector).append(context.JK.fillTemplate($(template_name).html(), args));

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

          selector = isSidebar ? '#sidebar-search-results' : '#search-results';
          $(selector).append(invitationSentHtml);

          // wire up button click handler if search result is not a friend or the current user
          if (isSidebar) {
            var $sidebar = $('div[layout=sidebar] div[user-id=' + val.id + ']');
            if (val.is_friend || val.pending_friend_request || val.id === context.JK.currentUserId) {
              // hide the button if the search result is already a friend
              $sidebar.find('.btn-connect-friend').hide();
            }
            else {
              $sidebar.find('.btn-connect-friend').click(sendFriendRequest);
            }
          }
          else {
            var $searchResults = $('div[layout-id=searchResults] div[user-id=' + val.id + ']');
            if (val.is_friend || val.pending_friend_request || val.id === context.JK.currentUserId) {
              $searchResults.find('.btn-connect-friend').hide();
            }
            else {
              $searchResults.find('.btn-connect-friend').click(sendFriendRequest);
            }
          }
          resultDivVisibility(val, isSidebar);
        });
      }

      else if (response.search_type === 'bands') {
        resultCount = response.bands.length;
        template_name = isSidebar ? "#template-bands-sidebar-search-result" : "#template-bands-search-result";

        $.each(response.bands, function(index, val) {
          // fill in template for Connect pre-click
          var searchResultHtml = context.JK.fillTemplate($(template_name).html(), {
            bandId: val.id, 
            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
            profile_url: "/client#/bandProfile/" + val.id,
            bandName: val.name,
            location: val.location
          });

          selector = isSidebar ? '#sidebar-search-results' : '#search-results';
          $(selector).append(searchResultHtml);
          resultDivVisibility(val, isSidebar);
        });
      }

      else if (response.search_type === 'fans') {
        resultCount = response.fans.length;
        template_name = isSidebar ? "#template-fans-sidebar-search-result" : "#template-fans-search-result";

        $.each(response.fans, function(index, val) {
            // fill in template for Connect pre-click
            var searchResultHtml = context.JK.fillTemplate($(template_name).html(), {
            userId: val.id, 
            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
            profile_url: "/client#/profile/" + val.id,
            userName: val.name,
            location: val.location
            });
            selector = isSidebar ? '#sidebar-search-results' : '#search-results';
            $(selector).append(searchResultHtml);
            resultDivVisibility(val, isSidebar);
        });
      }

      if (isSidebar) {
        // show header
        $('#sidebar-search-header').show();
      }
      else {
        $('#result-count').html(resultCount);
        if (resultCount === 1) {
        $('#result-count').append(" Result for: ");
        }
        else {
          $('#result-count').append(" Results for: ");
        }
      }
    }

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

    function friendRequestCallbackSearchResults(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 $btn = $(this)

      if ($btn.is('.disabled')) {
        logger.debug("ignoring send friend request on disabled btn")
        return;
      }
      var userId = $btn.parent().attr('user-id');

      if ($(this).closest('#sidebar-search-results')) {
        rest.sendFriendRequest(app, userId, friendRequestCallbackSidebar)
          .done(function() {
            app.notify({title: 'Friend Request Sent', text: 'Your friend request has been sent'})
            $btn.addClass('disabled')
          })
      }
      else {
        rest.sendFriendRequest(app, userId, friendRequestCallbackSearchResults)
          .done(function() {
            app.notify({title: 'Friend Request Sent', text: 'Your friend request has been sent'})
            $btn.addClass('disabled')
          })

      }
    }

    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].asset;
            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();
      initializeSearchNavLinks();
    };
  }
})(window,jQuery);