/*
 Triggers dragstart, drag, and dragstop events on your element.
 */
(function($) {
  $.fn.dragEvents = function() {

    return this.each(function() {
      var $el = $(this);
      var oldPosition, position = {};

      function mousedown(e) {
        updatePosition(e);
        oldPosition = $.extend({}, position);
        $(document).one('mouseup',function(e) {
          updatePosition(e);
          $(document).unbind('mousemove',triggerDrag);
          $el.triggerHandler('dragstop',[e]);
          updatePosition();
          return false;
        });
        $(document).bind('mousemove',triggerDrag);
        $el.triggerHandler('dragstart',[e]);
        return false;
      }

      function triggerDrag(e) {
        updatePosition(e);
        var delta = {
          x:position.x - oldPosition.x,
          y:position.y - oldPosition.y
        };
        $el.triggerHandler('drag',[delta]);
        return false;
      }

      function updatePosition(e) {
        if(!e) {
          position = {};
        } else {
          position.x = e.pageX;
          position.y = e.pageY;
        }
      }

      $el.mousedown(mousedown);
    });

  };
})(jQuery);
