(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.BandProfileScreen = function(app) {
      var NOT_SPECIFIED_TEXT = 'Not specified';
      var logger = context.JK.logger;
      var rest = context.JK.Rest();
      var bandId;
      var isMember = false;
      var isAdmin = false;
      var band = {};
      var instrument_logo_map = context.JK.getInstrumentIconMap24();
      var profileUtils = context.JK.ProfileUtils;
      var feed = new context.JK.Feed(app)
      var $root = $("#band-profile")
      var $history = $root.find("#band-profile-history")




      function beforeShow(data) {
          bandId = data.id;
          feed.setBand(bandId);
      }

      function beforeHide(data) {
        feed.setBand(null);
      }


      function afterShow(data) {
        // hide until we know if 'isMember'
        $("#btn-follow-band").hide();
        $("#btn-edit-band-profile").hide();
        $("#btn-edit-band-bio").hide();
        $("#btn-edit-band-info").hide();
        $("#btn-edit-band-members").hide();
        $("#btn-edit-band-delete").hide();

        resetForm();
        events();
        determineMembership()
          .done(function() {
            renderActive();
          })
          .fail(function(jqXHR) {
            app.notifyServerError(jqXHR, "Unable to talk to server")
          })
      }

      function resetForm() {
          $('#band-profile-instruments').empty();

          $('#band-profile-about').show();
          $('#band-profile-history').hide();
          $('#band-profile-members').hide();
          $('#band-profile-social').hide();

          $('.band-profile-nav a.active').removeClass('active');
          $('.band-profile-nav a#band-profile-about-link').addClass('active');
      }

      /****************** MAIN PORTION OF SCREEN *****************/

      function addFollowing(isBand, id) {
        var newFollowing = {};

        if (!isBand) {
          newFollowing.user_id = id;
        }
        else {
          newFollowing.band_id = id;
        }

        rest.addFollowing(newFollowing)
          .done(function() {
            if (isBand) {
              var newCount = parseInt($("#band-profile-follower-stats").text()) + 1;
              var text = newCount > 1 || newCount == 0 ? " Followers" : " Follower";
              $('#band-profile-follower-stats').html(newCount + text);
              configureBandFollowingButton(true);
            }
            else {
              configureMemberFollowingButton(true, id);
            }
            renderActive();
          })
          .fail(app.ajaxError);
      }

      function removeFollowing(isBand, id) {
        rest.removeFollowing(id)
          .done(function() {
            if (isBand) {
              var newCount = parseInt($("#band-profile-follower-stats").text()) - 1;
              var text = newCount > 1 || newCount == 0 ? " Followers" : " Follower";
              $('#band-profile-follower-stats').html(newCount + text);
              configureBandFollowingButton(false);
            }
            else {
              configureMemberFollowingButton(false, id);
            }
            renderActive();
          })
          .fail(app.ajaxError);
      }

      function configureBandFollowingButton(following) {
          $('#btn-follow-band').unbind("click");

          if (following) {
              $('#btn-follow-band').text('UNFOLLOW');
              $('#btn-follow-band').click(function() {
                  removeFollowing(true, bandId);
                  return false;
              });
          } else {
              $('#btn-follow-band').text('FOLLOW');
              $('#btn-follow-band').click(function() {
                  addFollowing(true, bandId);
                  return false;
              });
          }
      }

      function configureMemberFollowingButton(following, userId) {

          var $btnFollowMember = $('div[user-id=' + userId + ']', '#band-profile-members').find('#btn-follow-member');

          if (context.JK.currentUserId === userId) {
              $btnFollowMember.hide();
          } else {
              $btnFollowMember.unbind("click");

              if (following) {
                  $btnFollowMember.text('UNFOLLOW');
                  $btnFollowMember.click(function() {
                      removeFollowing(false, userId);
                      return false;
                  });
              }
              else {
                  $btnFollowMember.text('FOLLOW');
                  $btnFollowMember.click(function() {
                      addFollowing(false, userId);
                      return false;
                  });
              }
          }
      }

      // refreshes the currently active tab
      function renderActive() {

        if (isMember) {
            $("#btn-follow-band").hide();
            $("#btn-edit-band-profile").show();
            $("#btn-edit-band-bio").show();
            $("#btn-edit-band-info").show();
            $("#btn-edit-band-members").show();
            if (isAdmin) {
              $("#btn-edit-band-delete").show();
            }
          } else {
            $("#btn-follow-band").show();
            $("#btn-edit-band-bio").hide();
            $("#btn-edit-band-profile").hide();
            $("#btn-edit-band-info").hide();
            $("#btn-edit-band-members").hide();
            $("#btn-edit-band-delete").hide();
          }

          if ($('#band-profile-about-link').hasClass('active')) {
              renderAbout();
          } else if ($('#band-profile-history-link').hasClass('active')) {
              renderHistory();
          } else if ($('#band-profile-members-link').hasClass('active')) {
              renderMembers();
          } else if ($('#band-profile-social-link').hasClass('active')) {
              renderSocial();
          }
      }

      /****************** ABOUT TAB *****************/
      function renderAbout() {

          $('#band-profile-about').show();
          $('#band-profile-history').hide();
          $('#band-profile-members').hide();
          $('#band-profile-social').hide();

          $('.band-profile-nav a.active').removeClass('active');
          $('.band-profile-nav a#band-profile-about-link').addClass('active');



          bindAbout();
      }

      function bindAbout() {

        rest.getBand(bandId)
            .done(function(response) {
              band = response;
              if (band) {
                // name
                $('#band-profile-name').text(band.name);

                // avatar
                $('#band-profile-avatar').attr('src', context.JK.resolveAvatarUrl(band.photo_url));

                // location
                $('#band-profile-location').html(band.location);

                // stats
                var text = band.follower_count > 1 || band.follower_count == 0 ? " Followers" : " Follower";
                $('#band-profile-follower-stats').html(band.follower_count + text);

                text = band.session_count > 1 || band.session_count == 0 ? " Sessions" : " Session";
                $('#band-profile-session-stats').html(band.session_count + text);

                text = band.recording_count > 1 || band.recording_count == 0 ? " Recordings" : " Recording";
                $('#band-profile-recording-stats').html(band.recording_count + text);

                $('#band-profile-biography').text(band.biography);

                renderMusicalExperience()
                profileUtils.renderPerformanceSamples(band, $root, isAdmin)
                profileUtils.renderOnlinePresence(band,     $root, isAdmin)
                renderCurrentInterests()

                // wire up Follow click
                configureBandFollowingButton(band.is_following);
              }
              else {
                  logger.debug("No band found with bandId = " + bandId);
              }
            })
            .fail(function(xhr) {
              if(xhr.status >= 500) {
                  context.JK.fetchUserNetworkOrServerFailure();
              }
              else if(xhr.status == 404) {
                  context.JK.entityNotFound("Band");
              }
              else {
                  context.JK.app.ajaxError(arguments);
              }
            });
      }

      function renderMusicalExperience() {
        var genres = buildGenreList(band.genres)
        var gigs = (band.concert_count > 0) ? 'Has played ' + profileUtils.gigMap[band.concert_count] + ' live concert gigs' : NOT_SPECIFIED_TEXT;
        var bandType ;
        if (!band.band_type || typeof(band.band_type)=="undefined" || band.band_type==="") {
          bandType = "Not specified";
        } else if (band.band_type.toLowerCase()==="physical") {
          bandType = "Physical";
        } else if (band.band_type.toLowerCase()==="virtual") {
          bandType = "Virtual";
        } else {
          bandType = "Not specified";
        }

        var bandStatus ;
        if (!band.band_status || typeof(band.band_status)=="undefined" || band.band_status==="") {
          bandStatus = "Not specified";
        } else if (band.band_status.toLowerCase()==="amateur") {
          bandStatus = "Amateur Band";
        } else if (band.band_status.toLowerCase()==="professional") {
          bandStatus = "Professional Band";
        } else {
          bandStatus = "Not specified";
        }

        $root.find(".experience-genres").html(genres)
        $root.find(".experience-gigs").html(gigs)
        $root.find(".experience-status").html(bandStatus)
        $root.find(".experience-type").html(bandType)

      }

      function renderCurrentInterests() {
        if (band.add_new_members) {
          $root.find(".new-member-details").html(profileUtils.renderBandInstruments(band))
          $root.find(".interests-new-members").removeClass("hidden")
        } else {
          $root.find(".interests-new-members").addClass("hidden")
        }

        if (band.paid_gigs) {
          $root.find(".paid-gig-rate").html(band.hourly_rate)
          $root.find(".paid-gig-minimum").html(band.gig_minimum)
          $root.find(".interests-paid-gigs").removeClass("hidden")
        } else {
          $root.find(".interests-paid-gigs").addClass("hidden")
        }

        if (band.free_gigs) {
          $root.find(".interests-free-gigs").removeClass("hidden")
        } else {
          $root.find(".interests-free-gigs").addClass("hidden")
        }

      }


      /****************** SOCIAL TAB *****************/
      function renderSocial() {
          $('#band-profile-social-followers').empty();

          $('#band-profile-about').hide();
          $('#band-profile-history').hide();
          $('#band-profile-members').hide();
          $('#band-profile-social').show();

          $('.band-profile-nav a.active').removeClass('active');
          $('.band-profile-nav a#band-profile-social-link').addClass('active');

          bindSocial();
      }

      function bindSocial() {

        rest.getBandFollowers(bandId)
          .done(function(response) {
            $.each(response, function(index, val) {
              // var template = $('#template-profile-social').html();
              var template = $('#template-band-profile-social').html();
              var followerHtml = context.JK.fillTemplate(template, {
                  userId: val.id,
                  hoverAction: val.musician ? "musician" : "fan",
                  avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
                  userName: val.name,
                  location: val.location
              });

              $('#band-profile-social-followers').append(followerHtml);

              if (index === response.length-1) {
                context.JK.bindHoverEvents();
              }
            })
          })
          .fail(function(xhr) {
            if(xhr.status >= 500) {
              context.JK.fetchUserNetworkOrServerFailure();
            }
            else {
              context.JK.app.ajaxError(arguments);
            }
          });
      }

      /****************** HISTORY TAB *****************/
      function renderHistory() {
          $('#band-profile-about').hide();
          $('#band-profile-history').show();
          $('#band-profile-members').hide();
          $('#band-profile-social').hide();

          $('.band-profile-nav a.active').removeClass('active');
          $('.band-profile-nav a#band-profile-history-link').addClass('active');

          bindHistory();
      }

      function bindHistory() {
        feed.refresh();
      }

      function buildGenreList(genres) {
        var list = '';

        for (var i=0; i < genres.length; i++) {
          list = list.concat(genres[i].id);
          if (i !== genres.length - 1) {
            list = list.concat(', ');
          }
        }

        return list;
      }

      /****************** BANDS TAB *****************/
      function renderMembers() {
          $('#band-profile-members').empty();

          $('#band-profile-about').hide();
          $('#band-profile-history').hide();
          $('#band-profile-members').show();
          $('#band-profile-social').hide();

          $('.band-profile-nav a.active').removeClass('active');
          $('.band-profile-nav a#band-profile-members-link').addClass('active');

          bindMembers();
      }

      function bindMembers() {
        rest.getBandMembers(bandId, false)
          .done(function(response) {
            bindMusicians(response, false);
          })
          .fail(function(xhr) {
            if(xhr.status >= 500) {
              context.JK.fetchUserNetworkOrServerFailure();
            }
            else {
              context.JK.app.ajaxError(arguments);
            }
          });
      }

      function bindPendingMembers() {
        rest.getBandMembers(bandId, true)
          .done(function(response) {
            if (response && response.length > 0) {
              $("#band-profile-members").append("<br/><br/><h2><b>Pending Band Invitations</b></h2>");
              bindMusicians(response, true);
            }
          })
          .fail(function(xhr) {
            if(xhr.status >= 500) {
              context.JK.fetchUserNetworkOrServerFailure();
            }
            else {
              context.JK.app.ajaxError(arguments);
            }
          });
      }

      function bindMusicians(musicians, isPending) {

          if (!isPending && isMember) {
            bindPendingMembers();
          }

          if(!isPending) {
            $('#band-profile-members').empty(); // for race conditions seen most often in testing
          }

          $.each(musicians, function(index, musician) {
              var instrumentLogoHtml = '';
              if ("instruments" in musician && musician.instruments != null) {
                  for (var j=0; j < musician.instruments.length; j++) {
                      var instrument = musician.instruments[j];
                      var inst = '../assets/content/icon_instrument_default24.png';
                      if (instrument.instrument_id in instrument_logo_map) {
                          inst = instrument_logo_map[instrument.instrument_id].asset;
                      }
                      instrumentLogoHtml += '<img src="' + inst + '" width="24" height="24" />&nbsp;';
                  }
              }
              var bandAdmin = musician.band_admin;
               var template = $('#template-band-profile-members').html();
               var memberHtml = context.JK.fillTemplate(template, {
                  userId: musician.id,
                  band_admin: bandAdmin,
                  is_pending: isPending,
                  invitation_id: isPending ? musician.invitation_id : '',
                  profile_url: "/client#/profile/" + musician.id,
                  avatar_url: context.JK.resolveAvatarUrl(musician.photo_url),
                  name: musician.name,
                  location: musician.location,
                  biography: musician.biography,
                  friend_count: musician.friend_count,
                  follower_count: musician.follower_count,
                  recording_count: musician.recording_count,
                  session_count: musician.session_count,
                  instruments: instrumentLogoHtml
               });

               $('#band-profile-members').append(memberHtml);

               // wire up Follow button click handler
               configureMemberFollowingButton(musician.is_following, musician.id);
               configureRemoveMemberButton(musician.id, isPending, bandAdmin);

               // TODO: wire up Friend button click handler
               // var friend = isFriend(musician.id);
               // configureMemberFriendButton(friend, musician.id);
           });
        if (isPending) {
          $('div[pending-member=true] .btn-reinvite-member').each(function() {
            var btn = $(this);
            btn.show();
            btn.unbind('click');
            btn.click(function() {
              var inviteid = $(this).closest('.band-profile-members').attr('invitation-id');
              rest.resendBandInvitation(bandId, inviteid)
                .done(function (response) {
                  app.notifyAlert('Band Invitation', 'Your invitation has been re-sent');
                }).fail(app.ajaxError);
            });
          });
        }
      }

    function configureRemoveMemberButton(userId, isPending, bandAdmin) {
          var $divMember = $('div[user-id=' + userId + ']', '#band-profile-members');
          var $btnRemoveMember = $divMember.find('.btn-remove-member');
          if (isMember && !isPending && !bandAdmin) {
              $btnRemoveMember.show();
              $btnRemoveMember.unbind("click");
              $btnRemoveMember.click(function() {
                var confirmMemberDeleteTxt;
                if (userId == context.JK.currentUserId)
                  confirmMemberDeleteTxt = 'Are you sure you want to delete yourself from the band?';
                else
                  confirmMemberDeleteTxt = 'Are you sure you want to delete this member from the band?';
                var confirmDialog = new context.JK.ConfirmDialog(app, "DELETE", confirmMemberDeleteTxt, "Edit Band Membership",
                  function() {
                    app.layout.closeDialog('confirm');
                    rest.removeBandMember(bandId, userId)
                      .done(function() {
                        $divMember.remove();
                        if (userId == context.JK.currentUserId) {
                          $('#btn-edit-band-profile').hide();
                          $('#btn-edit-band-bio').hide();
                          $('#btn-edit-band-info').hide();
                          $('#btn-edit-band-members').hide();
                          $('.btn-remove-member').each(function(idx) { $(this).hide(); });
                          $('.btn-reinvite-member').each(function(idx) { $(this).hide(); });
                        }
                      })
                      .fail(app.ajaxError);
                  });
                confirmDialog.initialize();
                context.JK.app.layout.showDialog('confirm');
                return false;
              });
          } else {
              $btnRemoveMember.hide();
          }
      }

      // checks if person viewing the profile is also a band member
      function determineMembership() {
          var url = "/api/bands/" + bandId + "/musicians";
          return $.ajax({
               type: "GET",
               dataType: "json",
               url: url,
               processData:false,
               error: app.ajaxError
           })
            .done(function(response) {
              isAdmin = isMember = false;
              $.each(response, function(index, val) {
                if (val.id === context.JK.currentUserId) {
                  isMember = true;
                  if (val.band_admin) {
                    isAdmin = true;
                  }
                }
              });
            })
      }

      // events for main screen
      function events() {
          // wire up panel clicks
          $('#band-profile-about-link').unbind('click').click(renderAbout);
          $('#band-profile-history-link').unbind('click').click(renderHistory);
          $('#band-profile-members-link').unbind('click').click(renderMembers);
          $('#band-profile-social-link').unbind('click').click(renderSocial);

          $("#btn-edit-band-profile").unbind('click').click(function() {
              context.location = "/client#/band/setup/" + bandId + '/step0';
              return false;
          });
          $("#btn-edit-band-info").unbind('click').click(function() {
              context.location = "/client#/band/setup/" + bandId + '/step1';
              return false;
          });
          $("#btn-edit-band-bio").unbind('click').click(function() {
              context.location = "/client#/band/setup/" + bandId + '/step0';
              return false;
          });
          $("#btn-edit-band-members").unbind('click').click(function() {
              context.location = "/client#/band/setup/" + bandId + '/step2';
              return false;
          });
          $("#btn-edit-band-delete").unbind('click').click(function() {
            var confirmDialog = new context.JK.ConfirmDialog(app,
              "DELETE",
              "Are you sure you want to delete this band?  This is a permanent action which cannot be undone.",
              "Delete Band",
              function() {
                app.layout.closeDialog('confirm');
                rest.deleteBand(bandId)
                  .done(function() {
                    context.location = "/client#/profile/"+context.JK.currentUserId;
                  })
                  .fail(app.ajaxError);
              });
            confirmDialog.initialize();
            context.JK.app.layout.showDialog('confirm');
            return false;
          });
      }

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

          var $feedScroller = $history.find(".content-body-scroller")
          var $feedContent = $feedScroller.find(".feed-content")
          var $noMoreFeeds = $feedScroller.find('.end-of-list')
          var $refresh = $history.find('.btn-refresh-entries');
          var $sortFeedBy = $history.find('#feed_order_by');
          var $includeDate = $history.find('#feed_date');
          var $includeType = $history.find('#feed_show');


          feed.initialize($history, $feedScroller, $feedContent, $noMoreFeeds, $refresh, $sortFeedBy, $includeDate, $includeType, {time_range: 'all'})
      }


      this.initialize = initialize;
      this.beforeShow = beforeShow;
      this.afterShow = afterShow;
      return this;
    }
 })(window,jQuery);