text: "use strict";
  
  var _ = require('./underscore');
  var $ = require('jquery');
  
  var EventBus = require('./event-bus');
  
  var BlockReorder = function(block_element, mediator) {
    this.$block = block_element;
    this.blockID = this.$block.attr('id');
    this.mediator = mediator;
  
    this._ensureElement();
    this._bindFunctions();
  
    this.initialize();
  };
  
  Object.assign(BlockReorder.prototype, require('./function-bind'), require('./renderable'), {
  
    bound: ['onMouseDown', 'onDragStart', 'onDragEnd', 'onDrop'],
  
    className: 'st-block-ui-btn st-block-ui-btn--reorder st-icon',
    tagName: 'a',
  
    attributes: function() {
      return {
        'html': 'reorder',
        'draggable': 'true',
        'data-icon': 'move'
      };
    },
  
    initialize: function() {
      this.$el.bind('mousedown touchstart', this.onMouseDown)
        .bind('dragstart', this.onDragStart)
        .bind('dragend touchend', this.onDragEnd);
  
      this.$block.dropArea()
        .bind('drop', this.onDrop);
    },
  
    blockId: function() {
      return this.$block.attr('id');
    },
  
    onMouseDown: function() {
      this.mediator.trigger("block-controls:hide");
      EventBus.trigger("block:reorder:down");
    },
  
    onDrop: function(ev) {
      ev.preventDefault();
      ev.stopPropagation(); // to prevent event handling on outer blocks
  
      var dropped_on = this.$block,
      item_id = ev.originalEvent.dataTransfer.getData("text/plain"),
      block = $('#' + item_id);
  
      if (!_.isUndefined(item_id) && !_.isEmpty(block) &&
          dropped_on.attr('id') !== item_id &&
            dropped_on.attr('data-instance') === block.attr('data-instance') &&
            !$.contains(block[0], dropped_on[0]) // additional check for nested blocks: disallow dropping block inside the block itself
         ) {
         dropped_on.after(block);
       }
       this.mediator.trigger("block:rerender", item_id);
       EventBus.trigger("block:reorder:dropped", item_id);
    },
  
    onDragStart: function(ev) {
      var btn = $(ev.currentTarget).parent();
  
      ev.originalEvent.dataTransfer.setDragImage(this.$block[0], btn.position().left, btn.position().top);
      ev.originalEvent.dataTransfer.setData('Text', this.blockId());
  
      EventBus.trigger("block:reorder:dragstart");
      this.$block.addClass('st-block--dragging');
    },
  
    onDragEnd: function(ev) {
      EventBus.trigger("block:reorder:dragend");
      this.$block.removeClass('st-block--dragging');
    },
  
    render: function() {
      return this;
    }
  
  });
  
  module.exports = BlockReorder;
  