$(document).ready ()->

Log.DEBUG = false

$("abbr.timeago").livequery ->
  $(@).timeago()

#reading

source = new EventSource('/stream');
source.addEventListener 'message', (event)->
  a = JSON.parse(event.data)
  console.log(a)

  if a.repo.status == "stop"
    $("#repo-#{a.repo.id} .fa-refresh").removeClass("fa-spin")
    $(".repo-#{a.repo.id}-spinner.build-status").addClass("hidden")
  if a.repo.status == "start"
    $("#repo-#{a.repo.id} .fa-refresh").addClass("fa-spin")
    $(".repo-#{a.repo.id}-spinner.build-status").removeClass("hidden")

  #if repo.id is current repo then reload page
  if current_repo && a.repo.id is current_repo.id && (a.repo.status is "stop" || a.repo.status is "downloaded" )
    Backbone.history.loadUrl()
    #current_repo.fetch()
    #if current_view.build
    #  current_view.build.fetch

NProgress.configure({ showSpinner: false })

$.ajaxSetup(
  beforeSend: ()->
    console.log "AJAX START!"
    NProgress.start()
)

$( document ).ajaxStop ()->
  console.log "AJAX STOP!"
  NProgress.done()

application class Perkins.AppLayout extends Backbone.Marionette.Layout

template: "#perkins-layout"

regions:
  menu: "#main-menu"
  content: "#main-content"
  sidebar: "#sidebar"

class Perkins.Views.ApplicationLayout extends Backbone.View

el: "body"
initialize: ->
  console.log "Initializing"
  @setupLayout()
  @displayMenus()
  @setupRouter()
  @setupLinks()
  @setupGlobalViews()

displayMenus: ->
  @appLayout.menu.show( new Perkins.Views.Menu )
  @appLayout.sidebar.show( new Perkins.Views.Sidebar )

getRepo: (login, name)->
  @repo = new Perkins.Models.Repo()
  @repo.set(name: "#{login}/#{name}")

setupRouter: ->
  @app_router = new Perkins.Routers.main(trailingSlashIsSignificant: false)

  @app_router.on 'route' , (opts)=>
    console.log("any route")

  @app_router.on 'route:getProfile', ()=>
    console.log("on profile")
    @.appLayout.content.show( new Perkins.Views.Profile )

  @app_router.on 'route:getDashboard', (actions)=>
    console.log("on dashboard")
    @.appLayout.content.show( new Perkins.Views.Dashboard )

  @app_router.on 'route:getRepo', (login, name)=>
    console.log("get repo")
    @getRepo(login , name)
    @repo.fetch
      success: =>
        @.appLayout.content.show( new Perkins.Views.Repo(model: @repo) )

  @app_router.on 'route:getRepoWithBuild', (login, name, id)=>
    console.log("get repo")
    @getRepo(login , name)
    @id = id
    @repo.fetch
      success: =>
        @.appLayout.content.show( new Perkins.Views.Repo(model: @repo, build_id: @id) )

  @app_router.on "route:getRepoBuilds", (login, name)=>
    console.log("repo builds")
    @getRepo(login, name)
    @repo.fetch
      success: =>
        @.appLayout.content.show( new Perkins.Views.RepoBuilds(model: @repo) )

  @app_router.on "route:getRepoConfig", (login, name)=>
    console.log("repo builds")
    @getRepo(login, name)
    @repo.fetch
      success: =>
        @.appLayout.content.show( new Perkins.Views.RepoConfig(model: @repo) )

  @app_router.on "route:getOrg", (name)=>
    @.appLayout.content.show( new Perkins.Views.Org(name: name) )

  @app_router.on "route:getMyRepos", ()=>
    console.log "MY REPOS"
    @.appLayout.content.show( new Perkins.Views.MyRepos )

  Backbone.history.start(pushState: true)

setupLinks: ->
  # Globally capture clicks. If they are internal and not in the pass
  # through list, route them through Backbone's navigate method.
  _this = this

  $("body").on "click", "a[href^='/']", (event) ->
    target = $(event.currentTarget)
    href = target.attr('href')

    # chain 'or's for other black list routes
    passThrough = href.indexOf('logout') >= 0 or $(event.currentTarget).data("remote") or $(event.currentTarget).data("dont-push")

    # Allow shift+click for new tabs, etc.
    if !passThrough && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey

      # Remove leading slashes and hash bangs (backward compatablility)
      url = href.replace(/^\//,'').replace('\#\/','')

      window.data_navigation = target.data("navigation")
      # Instruct Backbone to trigger routing events
      _this.app_router.navigate url, { trigger: true }

      return false

setupLayout: ->
  @appLayout = new Perkins.AppLayout

setupGlobalViews: ->
  window.error_view = new Perkins.Views.Err