var statusElement, remoteActionEndpoint, parentItem;

function setStatusDefault(text) {
  statusElement.attr('class', 'm-xhr-status');
  statusElement.show();
  statusElement.text(text);
}

function setStatusSuccess(text) {
  statusElement.addClass('s-success');
  statusElement.text(text);
}

function setStatusError(text) {
  statusElement.addClass('s-failure');
  statusElement.text(text);
}

function onDragDropFinish(key, value) {
  var reorderedItems = [];

  $.each($('.m-sortable tbody tr'), function(key, value) {
    reorderedItems.push($(value).find('.m-sort-column').attr('data-card-name'));
  });

  if (reorderedItems !== null && reorderedItems.length > 0) {
    setStatusDefault('Saving updated order.');

    Visualforce.remoting.Manager.invokeAction(remoteActionEndpoint, reorderedItems, parentItem, function(result, event) {
      if (event !== null && event.statusCode !== null && event.statusCode === 200) {
        setStatusSuccess('New sort order successfully saved!');
     } else {
        setStatusError('Error while saving sort order.');
      }
    });
  }
}

function initializeDragAndDrop(endpoint, parentContainer) {
  statusElement = $('#sort-order-save-status');
  remoteActionEndpoint = endpoint;
  parentItem = parentContainer;

  $('.m-sortable tbody').sortable({
    handle: '.m-sort-column',
    cursor: 'move',
    placeholder: 's-highlight',
    stop: onDragDropFinish
  });
}