(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.RsvpSubmitDialog = function(app, sessionId) {
    var EVENTS = context.JK.EVENTS;
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var $dialog = null;
    var dialogId = 'rsvp-submit-dialog';
    var $btnSubmit = $("#btnSubmitRsvp");


    function beforeShow(data) {
      $('.error', $dialog).hide();
    }

    function afterShow(data) {
      $('.rsvp-instruments', $dialog).empty();

      rest.getSessionHistory(sessionId)
        .done(function(response) {
          if (response) {
            $('.session-name', $dialog).html(response.name);

            $('.scheduled-start', $dialog).html(response.pretty_scheduled_start_with_timezone);

            if (response.recurring_mode !== null && response.recurring_mode !== 'once') {
              $('.schedule-recurrence', $dialog).html("Recurs " + response.recurring_mode + " on this day at this time");
            }

            var hasOpenSlots = response.open_slots && response.open_slots.length > 0;

            if (response['is_unstructured_rsvp?']) {
              var checkedState = hasOpenSlots ? '' : 'checked="checked"'
              $('.rsvp-instruments', $dialog).append('<input type="checkbox" ' + checkedState + ' value="unstructured"/><span>Play Any Instrument You Like</span><br/>');
            }

            if (hasOpenSlots) {
              $.each(response.open_slots, function(index, val) {
                $('.rsvp-instruments', $dialog).append('<input type="checkbox" data-instrument-id="' + val.instrument_id + '" value="' + val.id + '"/><span>' + val.description + " (" + val.proficiency_desc + ")</span><br/>");
              });
            }
          }
        })
        .fail(app.ajaxError);
    }

    function afterHide() {
    }

    function showDialog() {
      return app.layout.showDialog(dialogId);
    }

    function events() {
      $btnSubmit.unbind('click');
      $btnSubmit.click(function(e) {
        e.preventDefault();
        var error = false;
        var slotIds = [];
        var selectedSlots = [];
        $("input:checked", '.rsvp-instruments').each(function(index) {
          var selection = $(this).attr('data-instrument-id');

          if ($.inArray(selection, selectedSlots) > -1) {
            $('.error', $dialog).html('You have selected the same instrument twice.').show();
            error = true;
            return;
          }
          selectedSlots.push(selection);
          slotIds.push($(this).val());
        });

        if (error) return;

        if (slotIds.length === 0) {
          $('.error', $dialog).html('You must select at least 1 instrument.').show();
          return;
        }

        // TODO: show spinner??
        rest.submitRsvpRequest(sessionId, slotIds)
          .done(function(response) {
            var comment = $.trim($('.txtComment', $dialog).val());
            if (comment.length > 0) {
              rest.addSessionInfoComment(sessionId, comment)
                .done(function(response) {

                })
                .fail(function(xhr, textStatus, errorMessage) {
                  error = true;
                  $('.error', $dialog).html("Unexpected error occurred while saving message (" + xhr.status + ")").show();
                });
            }

            if (!error) {
              $dialog.triggerHandler(EVENTS.RSVP_SUBMITTED);

              // Show confirmation & calendar; hide regular buttons.
              $(".rsvp-options").addClass("hidden")
              $(".rsvp-confirm").removeClass("hidden")
              $(".buttons").addClass("hidden")
            }
          })
          .fail(function(xhr, textStatus, errorMessage) {
            var error = JSON.parse(xhr.responseText);
            $('.error', $dialog).html(error.message);
            $('.error', $dialog).show();
          });

        return false;
      });
    }

    function initialize() {

      var dialogBindings = {
        'beforeShow' : beforeShow,
        'afterShow' : afterShow,
        'afterHide': afterHide
      };

      app.bindDialog(dialogId, dialogBindings);

      $dialog = $('[layout-id="' + dialogId + '"]');

      events();
    }

    this.initialize = initialize;
    this.showDialog = showDialog;
  }

  return this;
})(window,jQuery);