now = new Date()
ClockService = Ember.Object.extend
  minute_of_day: 60*now.getHours() + now.getMinutes()
  run_times: 0
  tick: (->
    clock = this
    Ember.run.later ->
      now = new Date()
      clock.set 'minute_of_day', 60*now.getHours() + now.getMinutes()
      clock.set 'run_times', 1 + clock.get('run_times')
    , 20000
  ).observes('run_times').on('init')
Ember.Application.initializer
  name: 'clockServiceInitializer'
  initialize: (container, application)->
    container.register 'clock:service', ClockService
    application.inject 'component:menu-product-categories', 'clock', 'clock:service'

Globals = Ember.Object.extend
  list: null
  notice: ''
  join_request_sent: false
Ember.Application.initializer
  name: 'Globals'
  initialize: (container, application)->
    container.typeInjection('component', 'store', 'service:store')
    application.register('global:variables', Globals, {singleton: true})
    application.inject('controller', 'globals', 'global:variables')
    application.inject('component', 'globals', 'global:variables')
    application.inject('route', 'globals', 'global:variables')

#Ember.Application.initializer
#  name: 'storeInComponents'
#  initialize: (container, application)->
#    container.typeInjection('component', 'store', 'store:main')
@App = Ember.Application.create
  LOG_TRANSITIONS: true
  rootElement: '#ember-app-container'
  ready: -> window.ember_ready = true

App.deferReadiness()

@App.modals = Ember.Namespace.create()
@Modals = @App.modals

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()
