(function (context, $) {

  "use strict";

  context.JK = context.JK || {};
  context.JK.AccountSessions = function (app) {
    var logger = context.JK.logger;
    var $sessions = null;
    var rest = context.JK.Rest();
    var userId;
    var scheduledSessions = {};

    function beforeShow(data) {
      userId = context.JK.currentUserId;
    }

    function afterShow(data) {
      resetForm();
      renderAccountIdentity();
    }

    function resetForm() {
      // remove all display errors
      $('#account-sessions-content-scroller form .error-text').remove();
      $('#account-sessions-content-scroller form .error').removeClass("error");
      $("#account-scheduled-sessions table tbody").html("");
    }

    function cancelSession(e) {
      e.preventDefault();

      var session_id = $(e.target).attr('session-id');
      var cancelSessionDlg = new context.JK.SessionCancelDialog(app, session_id);
      cancelSessionDlg.initialize();
      context.JK.app.layout.showDialog('session-cancel-dialog');
    }

    function detailSession(e) {
      e.preventDefault();

      var session_id = $(e.target).attr('session-id');
      window.location = '/client#/account/sessionDetail/' + session_id;
    }

    function openSessionPage(e) {
      context.JK.popExternalLink('/sessions/' + $(this).attr('session-id') + '/details')
      return false;
    }

    function events() {
    }

    function appendSessions(template) {
      $("#account-scheduled-sessions table tbody").replaceWith(template);
      $sessions.find(".session-cancel-button").on('click', cancelSession);
      $sessions.find(".session-detail-button").on('click', detailSession);
      $sessions.find(".session-page-button").on('click', openSessionPage)
    }

    function populateSessions(sessionList) {
      $.each(sessionList, function(index, session) {
        var hasPending = false;
        if (session.user_id == context.JK.currentUserId) {
          if (session.pending_rsvp_requests.length > 0) {
            hasPending = true;
          }
          if (hasPending)
            session.notification_msg = "You have new RSVPs to review and approve, see details.";
          else
            session.notification_msg = "";
        }
        else {
          $.each(session.pending_rsvp_requests, function(index, request) {
            if (request.user_id == context.JK.currentUserId) {
              hasPending = true;
            }
          });
          if (hasPending)
            session.notification_msg = "Your RSVP has not been processed by session organizer yet";
          else
            session.notification_msg = "";
        }
        scheduledSessions[session.id] = session;
      });

      var template = context._.template(
        $('#template-account-session').html(),
        {sessions: sessionList, current_user: userId},
        {variable: 'data'}
      );

      appendSessions(template);
    }

    function renderAccountIdentity() {
      rest.findScheduledRsvpSessions({})
        .done(populateSessions)
        .fail(app.ajaxError);
    }

    function navToAccount() {
      resetForm();
      window.location = '/client#/account';
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow
      };
      app.bindScreen('account/sessions', screenBindings);
      $sessions = $('.account-sessions');
      events();
    }

    this.initialize = initialize;
    this.beforeShow = beforeShow;
    this.afterShow = afterShow;

    $(document).on("sessionCancelEvent", function() {
      resetForm();
      renderAccountIdentity();
    });

    return this;
  };

})(window, jQuery);
