# on why local storage is used in the enter events
# http://stackoverflow.com/questions/8762635/getting-the-filename-during-the-dragenter-event
DragNDrop = Ember.Namespace.create()
DragNDrop.cancel = (e)->
    e.preventDefault()
    false

DragNDrop.Draggable = Ember.Mixin.create
  attributeBindings: 'draggable'
  draggable: 'true'
  dragStart: (e)->
    @set 'content.isDragging', true
    @set 'controller.isDragging', true
    @set 'controller.controllers.application.isDragging', true
    localStorage.setItem('draggingView', @get('elementId'))
    dataTransfer = e.originalEvent.dataTransfer
    dataTransfer.setData 'Text', @get('elementId')
  dragEnd: (e)->
    @set 'content.isDragging', false
    @set 'controller.isDragging', false
    @set 'controller.controllers.application.isDragging', false
    localStorage.removeItem 'draggingView' if localStorage.getItem 'draggingView'

DragNDrop.Droppable = Ember.Mixin.create
  dragEnter: (e)->
    if @dragEntered
      e.preventDefault()
      viewId = localStorage.getItem 'draggingView'
      view = Ember.View.views[viewId]
      @dragEntered view
    else
      DragNDrop.cancel(e)
  dragOver: DragNDrop.cancel
  dragLeave: ->
    if @dragLeft
      @dragLeft()
  drop: (e)->
    e.preventDefault()
    viewId = e.originalEvent.dataTransfer.getData('Text')
    view = Ember.View.views[viewId]
    return unless view
    # Calculate the element's center drop position relative to container
    position =
      left: Math.max(e.originalEvent.pageX - view.$el.offsetParent().offset().left - (view.$el.outerWidth()/2), 0)
      top:  Math.max(e.originalEvent.pageY - view.$el.offsetParent().offset().top - (view.$el.outerHeight()/2), 0)

    @dropped view, position if @dropped
    false

@DragNDrop = DragNDrop
