#= require ./behavior

class window.SlidePagination extends window.Behavior
  init: ->
    @$dataContainer = $('.pagination-data-container', @$dom)
    @attach()

  slideActive: false

  pageForm: ->
    formId = @data('page-form')
    @$pageForm ?= $(formId)


  lockSlide: ->
    if @slideActive
      false
    else
      @slideActive = true

  unlockSlide: ->
    @slideActive = false

  slide: (url, direction) ->
    return unless @lockSlide()
   
    @load(url).done (html) =>
      $ajaxResult = $("<div id='temp-container'>" + html + "</div>")

      @animateTable($ajaxResult, ".tableContainer", direction, =>
        @unlockSlide()
        @attachBehaviors()
      )

  animateTable: ($ajaxResult, tableSelector, direction, completeCallback) ->
    $oldTable = $(tableSelector).addClass("old")
    $newTable = $(tableSelector, $ajaxResult).addClass("new")

    directionFactor = if direction == "right" then 1 else -1
    oldTableOffset = $oldTable.outerWidth() * directionFactor

    $newTable.css('left', oldTableOffset + "px")
    $oldTable.after($newTable)
    @updatePagination($newTable, $ajaxResult)

    animDuration = 300
    $oldTable.animate({ left: (oldTableOffset * -1) + "px" }, animDuration)
    $newTable.animate({ left: 0}, animDuration)

    setTimeout(
      ->
        $oldTable.remove()
        $newTable.removeClass("new")
        completeCallback()
      , animDuration
    )

  updatePagination: ($newTable, $ajaxResult) ->
    $(".pagination").remove()
    $newTable.after($(".pagination", $ajaxResult))

  load: (url) ->
    
    if(@pageForm().length)
      $.ajax
        type: @pageForm().attr('method')
        url: url
        data : @pageForm().serialize()
    else
     $.ajax
        type: "GET"
        url: url
 
  attach: ->
    self = @

    @$dom.on 'click', '.pagination li.active ~ li:not(li.disabled) > a', (e)->
      self.slide($(@).attr('href'), 'right')
      false

    @$dom.on 'click', '.pagination li:not(li.active,li.disabled) > a:not(.pagination li.active ~ li > a)', (e)->
      self.slide($(@).attr('href'), 'left')
      false

    @$dom.on 'click', '.pagination li.active, .pagination li.disabled', ->
      false

