# Global Options for Messenger Plugin Messenger.options = {

extraClasses: 'messenger-fixed messenger-on-top messenger-on-right', # define the position of notification
theme: 'flat' # define styles here

}

$(document).on

ready: (e) ->  # This handles non ajax flash messages
  Flashtastic().showFlashMessage()

ajaxSuccess: (e, r) -> # This handles ajax flash messages
  Flashtastic().showFlashMessage()

ajaxError: (e) -> # This handles ajax errors
  opts = {
    # Catch All message for all ajax errors. Feel Free to customize.
    message: "There was an error while processing your request. Please try reloading the page."
    type: "error"
  }
  Flashtastic().showFlashMessage(opts)

================================================== # Flashtastic script that handles Rails flash messages ==================================================

do window.Flashtastic = ->

# private
# This function reads the cookie. duh!
readCookie = (name, c, C, i) ->
  return cookies[name]  if cookies
  c = document.cookie.split("; ")
  cookies = {}
  i = c.length - 1
  while i >= 0
    C = c[i].split("=")
    cookies[C[0]] = C[1]
    i--
  cookies[name]

# private
# This function deletes the cookie. duh!
deleteCookie = (name) ->
  document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"

# private
# This function cleans up junk from message.
cleanUpMessage = (msg) ->
  msg.replace(/\+/g,' ')

# private
# This function uses cookie info
# and constructs Messenger post
flashMessageHandler = (opts) ->
  if opts?
    Messenger().post
      type: opts['type']
      message: opts['message']
      hideAfter: 3
      showCloseButton: true
  else
    flash_hash = $.parseJSON(decodeURIComponent(readCookie("flashtastic_cookie")))
    deleteCookie('flashtastic_cookie')
    if flash_hash
      $.each flash_hash, (type, msg) ->
        Messenger().post
          type: type
          message: cleanUpMessage(msg)
          hideAfter: 3
          showCloseButton: true

showFlashMessage: flashMessageHandler # exposed it for public consumption