(function($) {

  $.fn.mekury = function() {
    var $this = this
      , pos = 0;

    var api = {
      reset: function() {
        pos = 0;
        $this
          .bind('mousemove.mekury', mousemoveHandler)
          .bind('mouseout.mekury', mouseoutHandler)
          .trigger('mousemove');
      },
      stop: function() {
        $this.unbind('.mekury');
      }
    };

    var mouseX;

    var mousemoveHandler = function(e) {
      mouseX = e.pageX || mouseX;
      if (mouseX < $this.width() / 2) {
        if (pos >= 0) {
          pos = -1;
          $this.trigger('mekuryleft');
        }
      } else {
        if (pos <= 0) {
          pos = 1;
          $this.trigger('mekuryright');
        }
      }
    };

    var mouseoutHandler = function(e) {
      var target = e.toElement || e.relatedTarget;
      if (target === null) {
        $this.trigger('mekuryout');
        pos = 0;
      }
    };

    this
      .bind('mousemove.mekury', mousemoveHandler)
      .bind('mouseout.mekury', mouseoutHandler);

    return this.data('mekuryApi', api);
  };

}(jQuery));
