$(document).ready ->
  friends_loaded = false
  community_loaded = false

  load_friends_leaderboard = () ->
    unless friends_loaded
      friends_loaded = true
      url = '/dashboard/user_scores?friends=true'
      selector = '#leaderboard-friends'
      load_friends_list(url, selector)

  load_community_leaderboard = () ->
    unless community_loaded
      community_loaded = true
      url = '/dashboard/user_scores'
      selector = '#leaderboard-community'
      load_friends_list(url, selector)

  toggle = () ->
    toggle_on = $(this).attr('toggle_on')
    toggle_off = $(this).attr('toggle_off')
    $('#leaderboard-title-' + toggle_on).addClass('active')
    $('#leaderboard-' + toggle_on).addClass('active')
    $('#leaderboard-title-' + toggle_off).removeClass('active')
    $('#leaderboard-' + toggle_off).removeClass('active')
    if toggle_on == "friends"
      load_friends_leaderboard()
    else
      load_community_leaderboard()

  load_friends_list = (url, selector) ->
    $.ajax url,
      type: 'GET'
      dataType: 'html'
      error: (jqXHR, textStatus, errorThrown) ->
          # $(selector).html "Error Loading Friend List: #{textStatus}"
          $(selector).html ""
      success: (data, textStatus, jqXHR) ->
          $(selector).slideUp 'slow', ->
            $(selector).html(data)
            $("abbr.timeago").timeago()
            $(selector + ' ul>li').click ->
              $(selector + ' ul>li.score-card').addClass('hide')
              $(this).parent().find('li.score-card').removeClass('hide')
          $(selector).slideDown()

  
  $("a[toggle_on]").click(toggle)
    
  if $('#leaderboard-title-friends.active').length > 0
  	load_friends_leaderboard()

  if $('#leaderboard-title-community.active').length > 0
  	load_community_leaderboard()
    