#FB.init appId: '168928633304849'

#Ember.Application.initializer
  #name: 'authentication',
  #initialize: (container, application)->
    ## register the Facebook authenticator so the session can find it
    #container.register 'authenticators:facebook', App.FacebookAuthenticator
    #Ember.SimpleAuth.setup(container, application)

@App = Ember.Application.create
  LOG_TRANSITIONS: true
  rootElement: '#ember-app-container'
  obtain_token: (message)->
    message ||= ''
    auth_win = window.open $obtain_token_url, "_blank", "location=no"
    auth_win.addEventListener "loadstart", (event)=>
      if event.url.match 'close_window'
        user_id = event.url.match(/user_id=([\w+-]+)/)[1]
        auth_token = event.url.match(/authentication_token=([\w-]+)/)[1]
        @handleAuthInfo(user_id, auth_token)
        auth_win.close()
    true
  handleAuthInfo: (user_id, auth_token)->
    Qstorage.setItem 'user_id', user_id
    Qstorage.setItem 'auth_token', auth_token
    controller = @__container__.lookup('controller:application')
    controller.setCurrentList()
    controller.set 'notice', t('messages.authenticated')
App.deferReadiness()
Ember.$.ajaxPrefilter (options) ->
  if options.type.toUpperCase() == 'GET'
    if auth_token = Qstorage.getItem('auth_token')
      if options.data
        options.data += "&auth_token=#{auth_token}&app_version=#{$app_version}"
      else
        options.data = "auth_token=#{auth_token}&app_version=#{$app_version}"
  if options.type.toUpperCase() == 'POST'
    if auth_token = Qstorage.getItem('auth_token')
      if options.data
        if typeof(options.data) == 'string'
          if options.data[0] == '{' || options.data[0] == '[' # json
            object = JSON.parse(options.data)
            object.auth_token = auth_token
            object.app_version = $app_version
            options.data = JSON.stringify(object)
          else
            options.data += "&auth_token=#{auth_token}&app_version=#{$app_version}"
        else
          options.data.auth_token = auth_token
      else
        options.data = "auth_token=#{auth_token}"
  true

Ember.$.ajaxSetup
  error: (jqXHR, textStatus, errorThrown)->
    console.log "Error: #{textStatus}: #{errorThrown}"
    if jqXHR.status == 401
      App.__container__.lookup('route:application').unauthorized()
