(function(context, $) {

  context.JK.ShowMusicSession = function(app) {
    var logger = context.JK.logger;
    var rest = JK.Rest();
    var ui = new context.JK.UIHelper(app);
    var sessionId       = null;
    var $scope          = $(".landing-details");
    var $controls       = null;
    var $status         = null;
    var $playButton     = $('.play-button');
    var playing         = false;

    function like() {
      rest.addSessionLike(sessionId, JK.currentUserId)
        .done(function(response) {
          $("#spnLikeCount").html(parseInt($("#spnLikeCount").text()) + 1);
          $("#btnLike").unbind("click");
        });
    }

    function addComment() {
      var comment = $("#txtSessionComment").val();
      if ($.trim(comment).length > 0) {
        rest.addSessionComment(sessionId, JK.currentUserId, comment)
          .done(function(response) {
            $("#spnCommentCount").html(parseInt($("#spnCommentCount").text()) + 1);
            renderComment(comment, context.JK.currentUserId, context.JK.currentUserName,
              context.JK.currentUserAvatarUrl, $.timeago(Date.now()), context.JK.currentUserMusician, false);
            $("#txtSessionComment").val('');
          });
      }
    }

    function renderComment(comment, userId, userName, userAvatarUrl, timeago, musician, append) {
      var template = $('#template-landing-comment').html();
      var commentHtml = context.JK.fillTemplate(template, {
        avatar_url: userAvatarUrl,
        user_id: userId,
        hoverAction: musician ? "musician" : "fan",
        name: userName,
        comment: context._.unescape(comment),
        timeago: timeago
      });

      if (append) {
        $(".landing-comment-scroller").append(commentHtml);
      }
      else {
        $(".landing-comment-scroller").prepend(commentHtml);
      }

      context.JK.bindProfileClickEvents();
      context.JK.bindHoverEvents();
    }

    function stateChange(e, data) {
      if(data.displayText)
      {
        if(data.displayText == 'SESSION IN PROGRESS') {
          $status.text('LIVE SESSION IN PROGRESS');
        }
        else {
          $status.text(data.displayText);
        }
      }

      if(data.isEnd) stopPlay();

      if(data.isSessionOver) {
        $controls.removeClass('inprogress').addClass('ended')
      }
    }

    function startPlay() {
      logger.debug("user initiated play")
      var img = $('.play-icon', $playButton);
      img.attr('src', '/assets/content/icon_pausebutton.png');
      $controls.trigger('play.listenBroadcast');
      playing = true;
    }

    function stopPlay() {
      logger.debug("user initiated pause")
      var img = $('.play-icon', $playButton);
      $status.text('LIVE SESSION IN PROGRESS')
      img.attr('src', '/assets/content/icon_playbutton.png');
      $controls.trigger('pause.listenBroadcast');
      playing = false;
    }

    function togglePlay() {
      if(playing) {
        $status.text('LIVE SESSION IN PROGRESS');
        stopPlay();
      }
      else {
        startPlay();
      }
      return false;
    }

    function initialize(musicSessionId) {
      $controls       = $('.sessions-page .session-controls');
      $status         = $('.sessions-page .session-status')

      $('.timeago').timeago();
      $controls.listenBroadcast();
      $controls.bind('statechange.listenBroadcast', stateChange);
      context.JK.prettyPrintElements($('time.duration').show());
      context.JK.TickDuration(null);
      $playButton.click(togglePlay);

      sessionId = musicSessionId;

      $("#btnShare").click(function(e) {
        ui.launchShareDialog(sessionId, "session");
      });

      if (JK.currentUserId) {
        $("#btnPostComment").click(function(e) {
          if ($.trim($("#txtSessionComment").val()).length > 0) {
            addComment();
            $("#txtSessionComment").val('');
            $("#txtSessionComment").blur();
          }
        });
      }
      else {
        $("#txtSessionComment").attr("disabled", "disabled");
        $("#txtSessionComment").val("You must be logged in to add a comment.");
      }

      $("#btnLike").click(like);

      startPlay();
      pollForUpdates(musicSessionId);
    }

    function pollForUpdates(musicSessionId) {
      $(".landing-comment-scroller").empty();
      rest.getSessionHistory(musicSessionId)
        .done(function(response) {
          if (response && response.comments) {
            $("#spnCommentCount", $scope).html(response.comment_count);
            $("#spnLikeCount", $scope).html(response.like_count);
            $.each(response.comments, function(index, val) {
              renderComment(val.comment, val.creator.id, val.creator.name, 
                context.JK.resolveAvatarUrl(val.creator.photo_url), $.timeago(val.created_at), val.creator.musician, true);
            });
            setTimeout(function() {
              pollForUpdates(musicSessionId);
            }, 60000);
          }
        })
        .fail(function(xhr) {

        });
    }

    this.initialize = initialize;
  }

})(window, jQuery);