 _ = require 'underscore'
 Backbone = require 'backbone'
+Cookies = require 'cookies-js'
 template = -> require('./template.jade') arguments...
-Cookies = require 'cookies-js'
 
 module.exports = class ZigZagBanner extends Backbone.View
   className: 'zig-zag-banner'

    newMargin = offset + existingMargin
    @$el.css marginTop: newMargin

  sequence: (arr) ->
    _.map arr, (fn, i) =>
      dfd = $.Deferred()
      _.delay =>
        dfd.resolve fn()
      , (@segmentTransitionLength * (i + 1))
      dfd.promise()

  transitionIn: ->
    @render()
    _.defer =>
      @sequence [
        => @$one.addClass 'is-in'
        => @$two.addClass 'is-in'
        => @$three.addClass 'is-in'
        => @$el.addClass 'is-done'
      ]

  transitionOut: ->
    dfd = $.Deferred()
    @sequence([
      => @$el.removeClass 'is-done'
      => @$three.removeClass 'is-in'
      => @$two.removeClass 'is-in'
      => @$one.removeClass 'is-in'
    ]).then dfd.resolve
    dfd.promise()

  close: (e) ->
    e?.preventDefault()
    e?.stopPropagation()
    @transitionOut().then =>
      @remove()

      throw new Error('You must pass a name, $target, and message')

    if @backwards
      @$el.addClass('zig-zag-backwards').css marginLeft: @$target.outerWidth()

    if @persist
      if Cookies.get(@cookieName())?
        # Has already seen this... ignore
        return @remove()
      else
        # Will see this once until cookie expires
        Cookies.set @cookieName(), true, expires: 60 * 60 * 24 * 365

    @transitionIn()

  cookieName: ->
    "zig_zag_#{@name}"

  render: ->
    @$el.html @template(message: @message)
