 
   callback: =>
     hash = @popup.location.hash.slice(1)
-    params = qs = Readmill.utils.parseQueryString(hash)
+    params = qs = utils.parseQueryString(hash)
     @popup.close()
 
     if params.access_token

      obj[decode(key)] = decode value
    obj

class Readmill.Auth
  @AUTH_ENDPOINT: "http://localhost:8000/oauth/authorize"
  constructor: (options) ->
    {@clientId, @callbackUri, @authEndpoint} = options
    @authEndpoint = Readmill.Auth.AUTH_ENDPOINT unless @authEndpoint
  connect: ->
    params =
      response_type: "code"
      client_id: @clientId
      redirect_uri: @callbackUri
    qs = Readmill.utils.serializeQueryString(params)

    Readmill.Auth.callback = @callback

    @popup = @openWindow "#{@authEndpoint}?#{qs}"
    @deferred = new jQuery.Deferred()

class Readmill extends Annotator.Plugin
  @API_ENDPOINT: "http://localhost:8000"

  constructor: (options) ->
    super {}, options

    @auth  = new Readmill.Auth @options
    @store = new Readmill.Store

    token = options.accessToken || @store.get "access-token"
    @connected(token) if token

  connect: ->
    @auth.connect().then @_onConnectSuccess, @_onConnectError

  connected: (accessToken) ->
    @client = new Readmill.Client(accessToken: accessToken)
    @store.set "access-token", accessToken

  _onConnectSuccess: (params) =>
    @connected(params.access_token)

  _onConnectError: (error) =>

utils =
  serializeQueryString: (obj, sep="&", eq="=") ->
    esc = window.encodeURIComponent
    ("#{esc(key)}#{eq}#{esc(value)}" for own key, value of obj).join(sep)

  parseQueryString: (str, sep="&", eq="=") ->
    obj = {}
    decode = window.decodeURIComponent
