class window.Vkontakte
  
  api_id: null
  
  constructor: (@api_id) ->
  
  getApiId: ->
    @api_id
  
  init: ->
    window.vkAsyncInit = ->
      VK.init apiId: _vkontakte.getApiId()
      VK.Auth.getLoginStatus (response) ->
        _vkontakte.authInfo(response)

    setTimeout ->
      $('#vk_api_transport').append($('<script async="async" type="text/javascript" src="http://vkontakte.ru/js/api/openapi.js">'))
    , 0
  
  authInfo: (response) ->
    if typeof response isnt 'undefined' and response.session      
      _session = new Session(response.session)
      _session.query '/user/auth', {}, (ar) ->
        if ar.newbie
          VK.Api.call 'getVariable', key: 1281, (r) ->
            _session.query '/user/update', params: { name: r.response }, (ar2) ->
              _session.setUser ar2.user
              $('#username')
                .html (if _session.getUser().name then _session.getUser().name else '%username%')
              window._session = _session
              _ajax.detectPage()
              _session.displayAuthorizedContent()
              $('#authorized').css display: 'block'
              if ar.ok_reload
                 window.location.reload()
                 false
        else if ar.ok_reload
          window.location.reload()
          false
        else
          _session.setUser ar.user
        
        $('#username')
          .html (if _session.getUser().name then _session.getUser().name else '%username%')
          _session.displayAuthorizedContent()
        window._session = _session
        _ajax.detectPage()
        $('.fullscreen').hide();
      
      if response.session.expire?
        setTimeout ->
          _vkontakte.auth()
          false
        , response.session.expire * 1000 - new Date().getTime() + 1000
    else
      _session = new Session({})
      _session.setUser {}
      _session.hideAuthorizedContent()
      window._session = _session
      _ajax.detectPage()
      $('.fullscreen').hide();
  
  auth: ->
    VK.Auth.getLoginStatus (response) ->
      _vkontakte.authInfo(response)
      false
    , 8
    false

$('#login').live 'click', ->
  VK.Auth.login (response) ->
    _vkontakte.authInfo(response)
    false
  , 8
  false
$('#logout').live 'click', ->
  VK.Auth.logout (response) ->
    _vkontakte.authInfo(response)
    $('.button-container').hide()
    false
  false