ControllerExtensions = Ember.Mixin.create
  needs: ['application']
  ajaxError: (callback)->
    handler = (emberError)=>
      emberError = emberError.errors[0] if emberError.errors and emberError.errors.length
      console.log "Error: status #{emberError.status}"
      status = parseInt(emberError.status)
      if status is 401
        App.__container__.lookup('route:application').unauthorized()
      else
        callback.call(@, emberError)
    handler
  secured: (callback)->
    unless Qstorage.getItem('auth_token')
      return @transitionToRoute 'sign_in'
    callback.call(@) if callback
  modal: (name, options={})->
    options.model ||= Ember.Object.create()
    @send "openModal", name, options
  redirect_to: (route, args...)->
    route = 'index' if route == 'user_root'
    #route_object= App.Router.router.recognizer.names[route]
    route_object = @get "target.router.recognizer.names.#{route}"
    throw "Route #{route} cannot exist" unless route_object
    dynamic_segments = route_object.segments.reduce (sum, segment) ->
      if segment.name then sum + 1 else sum
    , 0
    route_args = [route]

    if dynamic_segments # needed because javascript for loop always fires, even when end is less than start :'(
      for isegment in [1..dynamic_segments]
        route_args.push args.shift()

    options = args.pop() || {}

    #route_args.push args if a
    @transitionToRoute.apply(@,route_args).then =>
      if options.message
        tkey = if options.message.indexOf('.') > -1 then options.message else "messages.#{options.message}"
        @set 'globals.notice', t(tkey)
#Ember.ArrayController.reopen ControllerExtensions
Ember.Controller.reopen ControllerExtensions
#Ember.ObjectController.reopen ControllerExtensions
#Ember.Controller.reopen
  #confirm: (options = {})->
    ##@showModal options
    ##$(document).foundation('reflow') # needed (stupid!!!)
    #r = @container.lookup('route:application')
    #r.send('confirm', options)
    ##window.confirm_cancel = options.cancel
    ##window.confirm_ok = options.ok
    ##$('#confirm-modal .confirm-title').html options.title if options.title
    ##$('#confirm-modal .confirm-content').html options.content if options.content
    ##@set 'controllers.application.confirm.content', options.content if options.content
    ##$('#confirm-modal').foundation('reveal', 'open') # this kills the ember actions
    ##$('#confirm-modal').css('visibility', 'visible').show()
    #$('#confirm-modal').foundation('reveal', 'open') #this kills the ember actions
    #$('#confirm-modal').css('visibility', 'visible').show()

#Ember.ArrayController.reopen
  #redirect_to: (route, options={})->
    #route = 'index' if route == 'user_root'
    #@transitionToRoute(route).then =>
      #if options.message
        #tkey = if options.message.indexOf('.') > -1 then options.message else "messages.#{options.message}"
        #@set 'globals.notice', t(tkey)
