     compress item for item in diff
 
   saveCompressedDiff: (compressedDiff) ->
+    if (@mode != 'server')
+      return
     acticle = new @Acticles()
     acticle.save {
       'diff': compressedDiff,
-      'document': @document
+      'document': @title
       }, {
       success: (object) ->
         @syncTime = object.updatedAt

  activate: (state) ->
    @cowriterView = new CowriterView(state.cowriterViewState)
    @modalPanel = atom.workspace.addModalPanel(item: @cowriterView.getElement(), visible: false)

    # Current document's title
    @title= 'demo'

    # Save new diff
    @Acticles = AV.Object.extend 'Acticles'

    # Query for new diff
    @query = new AV.Query 'Acticles'

    # Base time for syncing
    @syncTime = new Date()

    @editor = atom.workspace.getActiveTextEditor()
    @oldText = ''
    @newText = ''

    # Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    @subscriptions = new CompositeDisposable

    # Register command that toggles this view
    @subscriptions.add atom.commands.add 'atom-workspace', 'cowriter:toggle': => @toggle()

    # Server: Sends changes when change stops
    @subscriptions.add @editor.onDidStopChanging => @stop()

    # May suffered from unsafe-eval of CSP
    # Cilent: Refresh view every 3 seconds
    @interval = setInterval ( => @getDiff() ), 3000

  deactivate: ->
    @modalPanel.destroy()

      }

  getDiff: ->
    if (@mode != 'client')
      return
    # Only gets the newest changes
    @query.greaterThan 'updatedAt', @syncTime
    @query.equalTo 'document', @title
    @query.addAscending 'updatedAt'
    @query.find().then (response) =>
      console.log 'success'
      console.log response
      @applyDiff res['attributes']['diff'] for res in response

  applyDiff: (diff) ->
    console.log diff
    x = @editor.getText()
    str = ""
    position = 0
    process = (item) ->
      if item['added'] == true
        # added
        str += item['value']
      else if item['removed'] == true
        # removed
        position += item['count']
      else
        # remains unchanged
        str += x.slice position, position + item['count']
        position += item['count']
    # updates syncTime with lastest update
    @syncTime = diff['updatedAt']
    # apply diffs to current text one by one
    process item for item in diff
    @editor.setText str

  toggle: ->
    if @modalPanel.isVisible()
      if @mode == 'client'
        # Clear the interval
        clearInterval @interval
      console.log 'Cowriter closed!'
      @modalPanel.hide()
    else
