/*!
 * Draggabilly v0.0.2
 * Make that shiz draggable
 */

( function( window ) {

'use strict';

// dependencies
var classie = window.classie;
var EventEmitter = window.EventEmitter;
var eventie = window.eventie;
var getStyleProperty = window.getStyleProperty;
var getSize = window.getSize;

var document = window.document;

// -------------------------- helpers -------------------------- //

// extend objects
function extend( a, b ) {
  for ( var prop in b ) {
    a[ prop ] = b[ prop ];
  }
  return a;
}

// ----- get style ----- //

var defView = document.defaultView;

var getStyle = defView && defView.getComputedStyle ?
  function( elem ) {
    return defView.getComputedStyle( elem, null );
  } :
  function( elem ) {
    return elem.currentStyle;
  };


// http://stackoverflow.com/a/384380/182183
function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    o && typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string"
  );
}

// -------------------------- requestAnimationFrame -------------------------- //

// https://gist.github.com/1866474

var lastTime = 0;
var prefixes = 'webkit moz ms o'.split(' ');
// get unprefixed rAF and cAF, if present
var requestAnimationFrame = window.requestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame;
// loop through vendor prefixes and get prefixed rAF and cAF
var prefix;
for( var i = 0; i < prefixes.length; i++ ) {
  if ( requestAnimationFrame && cancelAnimationFrame ) {
    break;
  }
  prefix = prefixes[i];
  requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ];
  cancelAnimationFrame  = cancelAnimationFrame  || window[ prefix + 'CancelAnimationFrame' ] ||
                            window[ prefix + 'CancelRequestAnimationFrame' ];
}

// fallback to setTimeout and clearTimeout if either request/cancel is not supported
if ( !requestAnimationFrame || !cancelAnimationFrame )  {
  requestAnimationFrame = function( callback ) {
    var currTime = new Date().getTime();
    var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
    var id = window.setTimeout( function() {
      callback( currTime + timeToCall );
    }, timeToCall );
    lastTime = currTime + timeToCall;
    return id;
  };

  cancelAnimationFrame = function( id ) {
    window.clearTimeout( id );
  };
}

// -------------------------- support -------------------------- //

var isTouch = 'createTouch' in document;
// events
var pointerStartEvent = isTouch ? 'touchstart' : 'mousedown';
var pointerMoveEvent = isTouch ? 'touchmove' : 'mousemove';
var pointerEndEvent = isTouch ? 'touchend' : 'mouseup';

var transformProperty = getStyleProperty('transform');
// TODO fix quick & dirty check for 3D support
var is3d = !!getStyleProperty('perspective');

// --------------------------  -------------------------- //

function Draggabilly( element, options ) {
  this.element = element;

  extend( this.options, options );

  this._create();

}

// inherit EventEmitter methods
extend( Draggabilly.prototype, EventEmitter.prototype );

Draggabilly.prototype.options = {
};

Draggabilly.prototype._create = function() {

  // properties
  this.position = {};
  this._getPosition();

  this.startPoint = { x: 0, y: 0 };

  this.startPosition = extend( {}, this.position );

  // set relative positioning
  var style = getStyle( this.element );
  if ( style.position !== 'relative' && style.position !== 'absolute' ) {
    this.element.style.position = 'relative';
  }

  // bind mousedown/touchstart event
  eventie.bind( this.element, pointerStartEvent, this );

};

// get left/top position from style
Draggabilly.prototype._getPosition = function() {
  // properties
  var style = getStyle( this.element );

  var x = parseInt( style.left, 10 );
  var y = parseInt( style.top, 10 );

  // clean up 'auto' or other non-integer values
  this.position.x = isNaN( x ) ? 0 : x;
  this.position.y = isNaN( y ) ? 0 : y;

  // add translate position
  if ( !transformProperty ) {
    return;
  }
  var transform = style[ transformProperty ];

  if ( transform.indexOf('matrix') !== 0 ) {
    return;
  }
  // split matrix(1, 0, 0, 1, x, y)
  var matrixValues = transform.split(',');
  // translate X value is in 12th or 4th position
  var xIndex = transform.indexOf('matrix3d') === 0 ? 12 : 4;
  var translateX = parseInt( matrixValues[ xIndex ], 10 );
  // translate Y value is in 13th or 5th position
  var translateY = parseInt( matrixValues[ xIndex + 1 ], 10 );
  this.position.x += translateX;
  this.position.y += translateY;
};

// -------------------------- events -------------------------- //

// trigger handler methods for events
Draggabilly.prototype.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

// returns the touch that we're keeping track of
Draggabilly.prototype.getTouch = function( touches ) {
  for ( var i=0, len = touches.length; i < len; i++ ) {
    var touch = touches[i];
    if ( touch.identifier === this.pointerIdentifier ) {
      return touch;
    }
  }
};

// ----- start event ----- //

Draggabilly.prototype.onmousedown = function( event ) {
  this.pointerStart( event, event );
};

Draggabilly.prototype.ontouchstart = function( event ) {
  // disregard additional touches
  if ( this.pointerIdentifier ) {
    return;
  }

  this.pointerStart( event, event.changedTouches[0] );
};

/**
 * @param {Event} event
 * @param {Event or Touch} pointer
 */
Draggabilly.prototype.pointerStart = function( event, pointer ) {
  event.preventDefault();

  this.pointerIdentifier = pointer.identifier || 1;

  this._getPosition();

  this.measureContainment();

  // point where drag began
  this.startPoint.x = pointer.pageX;
  this.startPoint.y = pointer.pageY;
  // position _when_ drag began
  this.startPosition.x = this.position.x;
  this.startPosition.y = this.position.y;

  // reset left/top style
  this.setLeftTop();

  this.dragX = 0;
  this.dragY = 0;

  // add events
  eventie.bind( window, pointerMoveEvent, this );
  eventie.bind( window, pointerEndEvent, this );

  classie.add( this.element, 'is-dragging' );

  // reset isDragging flag
  this.isDragging = true;

  this.emitEvent( 'start', [ event, pointer, this ] );

  // start animation
  this.animate();
};


Draggabilly.prototype.measureContainment = function() {
  var containment = this.options.containment;
  if ( !containment ) {
    return;
  }

  this.size = getSize( this.element );
  var elemRect = this.element.getBoundingClientRect();

  // use element if element
  var container = isElement( containment ) ? containment :
    // fallback to querySelector if string
    typeof containment === 'string' ? document.querySelector( containment ) :
    // otherwise it's the parent
    this.element.parentNode;

  this.containerSize = getSize( container );
  var containerRect = container.getBoundingClientRect();

  this.relativeStartPosition = {
    x: elemRect.left - containerRect.left,
    y: elemRect.top  - containerRect.top
  };
  // console.log( this.relativeStartPosition.x, this.relativeStartPosition.y );
};

// ----- move event ----- //

Draggabilly.prototype.onmousemove = function( event ) {
  this.pointerMove( event, event );
};

Draggabilly.prototype.ontouchmove = function( event ) {
  var touch = this.getTouch( event.changedTouches );
  if ( touch ) {
    this.pointerMove( event, touch );
  }
};

Draggabilly.prototype.pointerMove = function( event, pointer ) {
  this.dragX = pointer.pageX - this.startPoint.x;
  this.dragY = pointer.pageY - this.startPoint.y;

  if ( this.options.containment ) {
    var relX = this.relativeStartPosition.x;
    var relY = this.relativeStartPosition.y;
    this.dragX = Math.max( this.dragX, -relX );
    this.dragY = Math.max( this.dragY, -relY );
    this.dragX = Math.min( this.dragX, this.containerSize.width - relX - this.size.width );
    this.dragY = Math.min( this.dragY, this.containerSize.height - relY - this.size.height );
  }

  this.position.x = this.startPosition.x + this.dragX;
  this.position.y = this.startPosition.y + this.dragY;

  this.emitEvent( 'drag', [ event, pointer, this ] );
};


// ----- end event ----- //

Draggabilly.prototype.onmouseup = function( event ) {
  this.pointerEnd( event, event );
};

Draggabilly.prototype.ontouchend = function( event ) {
  var touch = this.getTouch( event.changedTouches );
  if ( touch ) {
    this.pointerEnd( event, touch );
  }
};

Draggabilly.prototype.pointerEnd = function( event, pointer ) {
  this.isDragging = false;

  delete this.pointerIdentifier;

  // use top left position when complete
  if ( transformProperty ) {
    this.element.style[ transformProperty ] = '';
    this.element.style.left = this.position.x + 'px';
    this.element.style.top =  this.position.y + 'px';
  }

  // remove events
  eventie.unbind( window, pointerMoveEvent, this );
  eventie.unbind( window, pointerEndEvent, this );

  classie.remove( this.element, 'is-dragging' );

  this.emitEvent( 'stop', [ event, pointer, this ] );

};

// -------------------------- animation -------------------------- //

Draggabilly.prototype.animate = function() {
  // only render and animate if dragging
  if ( !this.isDragging ) {
    return;
  }

  this.positionDrag();

  var _this = this;
  requestAnimationFrame( function animateFrame() {
    _this.animate();
  });

};

// transform translate function
var translate = is3d ?
  function( x, y ) {
    return 'translate3d( ' + x + 'px, ' + y + 'px, 0)';
  } :
  function( x, y ) {
    return 'translate( ' + x + 'px, ' + y + 'px)';
  };

// left/top positioning
Draggabilly.prototype.setLeftTop = function() {
  this.element.style.left = this.position.x + 'px';
  this.element.style.top  = this.position.y + 'px';
};

Draggabilly.prototype.positionDrag = transformProperty ?
  function() {
    // position with transform
    this.element.style[ transformProperty ] = translate( this.dragX, this.dragY );
  } : Draggabilly.prototype.setLeftTop;

// --------------------------  -------------------------- //


// publicize
window.Draggabilly = Draggabilly;

})( window );
