(->
  WPDocumentRevisions = undefined

  bind = (fn, me) ->
    ->
      fn.apply me, arguments

  WPDocumentRevisions = do ->
    `var WPDocumentRevisions`

    WPDocumentRevisions = ($) ->
      @updateTimestamps = bind(@updateTimestamps, this)
      @postAutosaveCallback = bind(@postAutosaveCallback, this)
      @overrideLock = bind(@overrideLock, this)
      @restoreRevision = bind(@restoreRevision, this)
      @enableSubmit = bind(@enableSubmit, this)
      @autosaveEnableButtons = bind(@autosaveEnableButtons, this)
      @hijackAutosave = bind(@hijackAutosave, this)
      @cookieFalse = bind(@cookieFalse, this)
      @cookieTrue = bind(@cookieTrue, this)
      @cookieDelete = bind(@cookieDelete, this)
      @buildContent = bind(@buildContent, this)
      @checkUpdate = bind(@checkUpdate, this)
      @$ = $
      @$('.revision').click @restoreRevision
      @$('#override_link').click @overrideLock
      @$('#document a').click @requestPermission
      @$(document).bind 'autosaveComplete', @postAutosaveCallback
      @$(document).bind 'documentUpload', @legacyPostDocumentUpload
      @$(':button, :submit', '#submitpost').prop 'disabled', true
      @$('#misc-publishing-actions a').click @enableSubmit
      @$('#sample-permalink').on 'change', @enableSubmit
      @$('input[type=text], textarea').on 'keyup', @enableSubmit
      @$('input, select').on 'change', @enableSubmit
      @$('#content-add_media').click @cookieFalse
      @$('#postimagediv .inside').click @cookieTrue
      @$('#publishing-action').click @buildContent
      @$('#submitdiv .inside').click @cookieDelete
      @$('#adminmenumain').click @cookieDelete
      @$('#wpadminbar').click @cookieDelete
      @$('#document').show()
      @$('#revision-log').show()
      @$('#revision-summary').hide()
      @bindPostDocumentUploadCB()
      @hijackAutosave()
      @checkUpdate()
      setInterval @updateTimestamps, 60000
      setInterval @checkUpdate, 1000
      return

    WPDocumentRevisions::hasUpload = false
    WPDocumentRevisions::secure = 'https:' == window.location.protocol
    WPDocumentRevisions::window = window.dialogArguments or opener or parent or top

    WPDocumentRevisions::hijackAutosave = ->
      @autosaveEnableButtonsOriginal = window.autosave_enable_buttons
      window.autosave_enable_buttons = @autosaveEnableButtons

    WPDocumentRevisions::autosaveEnableButtons = ->
      @window.document.$(document).trigger 'autosaveComplete'
      if @hasUpload
        return @autosaveEnableButtonsOriginal()
      return

    WPDocumentRevisions::enableSubmit = ->
      @$('#revision-summary').show()
      @$(':button, :submit', '#submitpost').removeAttr 'disabled'
      @$('#lock_override').prev().fadeIn()

    WPDocumentRevisions::restoreRevision = (e) ->
      e.preventDefault()
      if confirm(wp_document_revisions.restoreConfirmation)
        return window.location.href = @$(e.target).attr('href')
      return

    WPDocumentRevisions::overrideLock = ->
      @$.post ajaxurl, {
        action: 'override_lock'
        post_id: @$('#post_ID').val() or 0
        nonce: wp_document_revisions.nonce
      }, (data) ->
        if data
          @$('#lock_override').hide()
          @$('.error').not('#lock-notice').hide()
          @$('#publish, .add_media, #lock-notice').fadeIn()
          autosave()
        else
          alert wp_document_revisions.lockError

    WPDocumentRevisions::requestPermission = ->
      if window.webkitNotifications != null
        return window.webkitNotifications.requestPermission()
      return

    WPDocumentRevisions::lockOverrideNotice = (notice) ->
      if window.webkitNotifications.checkPermission() > 0
        window.webkitNotifications.RequestPermission lock_override_notice
      else
        window.webkitNotifications.createNotification(wp_document_revisions.lostLockNoticeLogo, wp_document_revisions.lostLockNoticeTitle, notice).show()

    WPDocumentRevisions::postAutosaveCallback = ->
      if @$('#autosave-alert').length > 0 and @$('#lock-notice').length > 0 and @$('#lock-notice').is(':visible')
        wp_document_revisions.lostLockNotice = wp_document_revisions.lostLockNotice.replace('%s', @window.document.$('#title').val())
        if window.webkitNotifications
          lock_override_notice wp_document_revisions.lostLockNotice
        else
          alert wp_document_revisions.lostLockNotice
        return location.reload(true)
      return

    WPDocumentRevisions::legacyPostDocumentUpload = (attachmentID, extension) ->
      @postDocumentUpload attachmentID, extension

    WPDocumentRevisions::human_time_diff = (from, to) ->
      d = undefined
      days = undefined
      diff = undefined
      hours = undefined
      mins = undefined
      d = new Date
      to = to or d.getTime() / 1000 + parseInt(wp_document_revisions.offset)
      diff = Math.abs(to - from)
      if diff <= 3600
        mins = Math.floor(diff / 60)
        mins = @roundUp(mins)
        if mins == 1
          return wp_document_revisions.minute.replace('%d', mins)
        else
          return wp_document_revisions.minutes.replace('%d', mins)
      else if diff <= 86400 and diff > 3600
        hours = Math.floor(diff / 3600)
        hours = @roundUp(hours)
        if hours == 1
          return wp_document_revisions.hour.replace('%d', hours)
        else
          return wp_document_revisions.hours.replace('%d', hours)
      else if diff >= 86400
        days = Math.floor(diff / 86400)
        days = @roundUp(days)
        if days == 1
          return wp_document_revisions.day.replace('%d', days)
        else
          return wp_document_revisions.days.replace('%d', days)
      return

    WPDocumentRevisions::roundUp = (n) ->
      if n < 1
        n = 1
      n

    WPDocumentRevisions::bindPostDocumentUploadCB = ->
      if typeof uploader == 'undefined' or uploader == null
        return
      uploader.bind 'FileUploaded', ((_this) ->
        (up, file, response) ->
          if response.response.match('media-upload-error')
            return
          _this.postDocumentUpload file.name, response.response
      )(this)

    WPDocumentRevisions::cookieFalse = ->
      wpCookies.set 'doc_image', 'false', 60 * 60, '/wp-admin', false, @secure
      return

    WPDocumentRevisions::cookieTrue = ->
      wpCookies.set 'doc_image', 'true', 60 * 60, '/wp-admin', false, @secure
      @$(':button, :submit', '#submitpost').removeAttr 'disabled'
      # Propagation will be stopped in postimagediv to stop document event setting cookie false.
      return

    WPDocumentRevisions::cookieDelete = ->
      wpCookies.set 'doc_image', 'true', -60, '/wp-admin', false, @secure
      return

    WPDocumentRevisions::updateTimestamps = ->
      @$('.timestamp').each ((_this) ->
        ->
          _this.$(_this).text _this.human_time_diff(_this.$(_this).attr('id'))
      )(this)

    WPDocumentRevisions::getDescr = ->
      `var content`
      # Extract data from TinyMCE window and clean up text.
      # On starting, the post_content is set to BOTH fields content and post_content. 
      iframe = @window.document.getElementById('content_ifr')
      if null == iframe
        content = @$('#post_content').val()
        if undefined == content or '' == content or /^\d+$/.test(content)
          return ''
        return content
      text = iframe.contentWindow.document.getElementById('tinymce').innerHTML
      if undefined == text
        content = @$('#post_content').val()
        if '' == content or /^\d+$/.test(content)
          return ''
        return content
      text = text.replace(/<br data-mce-bogus=\"1\">/g, '')
      text = text.replace(/<br><\/p>/g, '</p>')
      text = text.replace(/<p>\s*<\/p>/g, '')
      text

    WPDocumentRevisions::buildContent = ->
      # Create the desired content for post_content.
      # Will be the combination of document id from field post_content and description from content.
      content = @$('#post_content').val()
      newtext = @getDescr()
      attach = undefined
      if '' == content
        attach = [ '' ]
      else if /^\d+$/.test(content)
        attach = [ '<!-- WPDR ' + content + ' -->' ]
      else
        # match returns array, so ensure structure.
        attach = content.match(/!-- WPDR \s*\d+ -->/)
      # might have an extra space incldes in the id provided.
      newtext = newtext.replace(/<!-- WPDR \s*\d+ -->/, '')
      newtext = attach[0] + newtext
      if content != newtext
      	@enableSubmit()
      # set the desired text eeverywhere.
      @window.jQuery('#curr_content').val newtext
      @window.jQuery('#post_content').val newtext
      @window.jQuery('#content').val newtext
      return

    WPDocumentRevisions::postDocumentUpload = (file, attachmentID) ->
      if typeof attachmentID == 'string' and attachmentID.indexOf('error') != -1
        return @$('.media-item:first').html(attachmentID)
      if file instanceof Object
        file = file.name.split('.').pop()
      if @hasUpload
        return
      # On upload set the document identifier in the new format.
      docID = /\d+$/.exec(attachmentID)
      # This will throw away the description for an existing post - but it is in content.
      @window.jQuery('#post_content').val '<!-- WPDR ' + docID + ' -->'
      @window.jQuery('#message').hide()
      @hasUpload = true
      @window.tb_remove()
      @window.jQuery('#post').before(wp_document_revisions.postUploadNotice).prev().fadeIn().fadeOut().fadeIn()
      @enableSubmit()
      if @window.jQuery('#sample-permalink').length != 0
        return @window.jQuery('#sample-permalink').html(@window.jQuery('#sample-permalink').html().replace(/\<\/span>(\.[a-z0-9]{1,7})?@$/i, wp_document_revisions.extension))
      return

    WPDocumentRevisions::checkUpdate = ->
      # Check whether an update is needed - via a 3rd field as amalgam of two input fields.
      curr_content = @$('#curr_content').val()
      if undefined == curr_content
        return
      post_content = @$('#post_content').val()
      if curr_content == 'Unset'
        # Clunky process to miss the first update (and keep the save button inactive). 
        @$(':button, :submit', '#submitpost').prop 'disabled', true
        @$('#curr_content').val post_content
        return
      curr_text = @getDescr()
      if curr_text != curr_content or post_content != curr_content
        @buildContent()
        @enableSubmit()
      return

    WPDocumentRevisions
  jQuery ($) ->
    window.WPDocumentRevisions = new WPDocumentRevisions($)
  return
).call this

# ---
# generated by js2coffee 2.2.0
