class window.Settings
  
  getAccountInfo: (callback) ->
    _session.query '/user/update/', {}, callback
    false
  
  saveAccountInfo: (params, callback) ->
    _session.query '/user/update', params, callback
    false
  
  updateLastfmLogin: ->
    if window.lastfm_popup.closed
      log "Updating Last.fm info ..."
      _session.query '/user/auth', {}, (ar) ->
        _session.setUser ar.user
        if _session.user.lastfm_username not in ["", null]
          $('#settings .lastfm-off').hide()
          $('#settings .lastfm-on').show()
          $('#settings .lastfm-login').text _session.user.lastfm_username
        false
    else
      setTimeout _settings.updateLastfmLogin, 100
    false
  
  setFormFields: ->
    $('#settings input[name="name"]').val _session.user.name
    $('#settings select[name="lang"] option[value="'+_session.user.lang+'"]').attr("selected", true)
    $('select#lang').chosen()
    if _session.user.lastfm_username not in ["", null]
      $('#settings .lastfm-off').hide()
      $('#settings .lastfm-on').show()
      $('#settings .lastfm-login').text _session.user.lastfm_username
    else
      $('#settings .lastfm-on').hide()
      $('#settings .lastfm-off').show()
    false
  
  updateSettings: ->
    this.saveAccountInfo {
        params:
          name: $('#settings input[name="name"]').val()
          lang: $('#settings select[name="lang"]').val()
      }, (ar) ->
        _session.setUser ar.user
        $("#settings").modal 'hide'


$('#preferences').live 'click', ->
  if _session.getUser().id?
    $("#settings").modal 'show'
    _settings.setFormFields()
  false

$("#settings a.close-btn").live 'click', ->
  $("#settings").modal 'hide'
  false

$('#settings a.save-btn').live 'click', ->
  _settings.updateSettings()
  false

$('.lastfm-connect').live 'click', ->
  window.lastfm_popup = window.open _session.getUser().lastfm_login_url, "lastfm_popup", "status=1,width=960,height=585"
  setTimeout _settings.updateLastfmLogin, 100
  false
  
$('.lastfm-disconnect').live 'click', ->
  _settings.saveAccountInfo {
      params:
        lastfm_username: ""
        lastfm_key: ""
    }, (ar) ->
      _session.setUser ar.user
      $('#settings .lastfm-on').hide()
      $('#settings .lastfm-off').show()
      false
  false

$ ->
  $("#settings").modal keyboard: true, backdrop: true
  false