class window.Settings
  
  loadSettingsPage: ->
    unless _session.getUser().id?
      _ajax.go('/')
      false
    _session.secureLoad '/settings/', (data) ->
      false
    _ajax.setTitle 'Settings'
    false
  
  getAccountInfo: (callback) ->
    _session.query '/user/update/', {}, callback
    false
  
  saveAccountInfo: (params, callback) ->
    _session.query '/user/update', params, callback
    false
  
  updateLastfmLogin: ->
    log "Updating Last.fm info ..."
    if window.lastfm_popup.closed
      _session.query '/user/auth', {}, (ar) ->
        _session.setUser ar.user
        $('#lastfm_username').val(ar.user.lastfm_username)
        $('.lastfm-connect').hide()
    else
      setTimeout _settings.updateLastfmLogin, 100
    false


$('#preferences').live 'click', ->
  _ajax.go('/settings/');
  false

$('#settings-tabs li').live 'click', ->
  if not $(this).hasClass 'active'
    $('#settings-tabs li').removeClass 'active'
    $(this).addClass 'active'
    $('#settings-forms > div').hide()
    $('#settings-forms > .'+ $(this).find('a').attr('data-tab')).show()
  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

$('#settings-forms form').live 'submit', ->
  params = {}
  $(this).find('input, select').each ->
    if $(this).attr('name')
      if $(this).attr('type') is 'checkbox'
        params[$(this).attr('name')] = ($(this).attr('checked') is 'checked')
      else
        params[$(this).attr('name')] = $(this).val()
  _session.query '/user/update/', { params: params }
  false

$('#settings-forms input[type$="submit"]').live 'mouseup', ->
  $(this).parent().parent().parent().submit();
  false

$('#settings-forms input[type$="checkbox"]').live 'click', (e) ->
  sorry
  false