   # Types must be supported by the server.
   # callback(error, doc)
   open: (docName, type, callback) ->
-
     return callback 'connection closed' if @state is 'stopped'
 
     # Wait for the connection to open

        return

      docName = msg.doc
      if docName isnt undefined
        @lastReceivedDoc = docName
      else
        msg.doc = docName = @lastReceivedDoc

      if @docs[docName]

        @docs[docName]._onMessage msg
      else
        console?.error 'Unhandled message', msg

    @connected = false
    @socket.onclose = (reason) =>
      @setState 'disconnected', reason
      if reason in ['Closed', 'Stopped by server']
        @setState 'stopped', @lastError or reason

    @socket.onerror = (e) =>
      @emit 'error', e

    @socket.onopen = =>
      @lastError = @lastReceivedDoc = @lastSentDoc = null
      @setState 'handshaking'

    @socket.onconnecting = =>
      @setState 'connecting'

  setState: (state, data) ->

    else
      @lastSentDoc = docName

    #console.warn 'c->s', data
    data = JSON.stringify(data) if useSockJS?
    @socket.send data

