var _ = require('underscore')
var Backbone = require('backbone')
var utils = require('../utils')
var lang = require('../translations')
var autosize = require('autosize')

var EditorView = Backbone.View.extend({
  el: '#editor',

  initialize: function (options) {
    _.bindAll(this, 'render', 'focus', 'blur', 'desktopFocus', 'handleCyrillic')

    this.model.on('change:id', this.render)
    this.model.on('change:content', this.handleCyrillic)
    this.model.on('update', this.render)

    autosize(this.$el)
    this.setPlaceholder()
    this.render()
  },

  // only re-render when content changed
  render: function () {
    var content = this.model.get('content')
    if (content === this.$el.val()) return
    // strip html tags from documents.
    // this is just for migration from contenteditable to textarea.
    // we can remove this later on.
    content = content.replace(/<br>/ig, '\n').replace(/<\/br>/ig, '\n').replace(/<div>/ig, '\n').replace(/<[^>]+>/ig, '').replace(/\&amp;/ig, '&')
    this.$el.val(content || '')
    autosize.update(this.$el)
  },

  focus: function () {
    if (utils.isDesktop) return this.$el.focus()
    // doesn't seem to work for textarea on iOS at all. maybe it works on other platforms.
    setTimeout(_.bind(this.$el.focus, this.$el), 500)
  },

  desktopFocus: function () {
    if (utils.isDesktop) this.focus()
  },

  blur: function () {
    this.$el.blur()
  },

  events: {
    'input': 'updateOpenDoc'
  },

  updateOpenDoc: function () {
    this.model.set('content', this.$el.val())
    this.trigger('typing')
  },

  // if a cyrillic doc is detected change to cyrillic font
  handleCyrillic: function (doc) {
    // see http://kourge.net/projects/regexp-unicode-block
    var isCyrillic = doc.get('content').match('[\u0400-\u04FF\u0500-\u052F]')
    if (!isCyrillic) return
    this.$el.addClass('cyrillic')
    this.model.off(null, this.handleCyrillic)
  },

  setPlaceholder: function () {
    this.$el.attr('placeholder', lang.emptyDoc)
  }

})

module.exports = EditorView

@@ -711,298 +711,8 @@
 urn%0A
-    // strip html tags from documents.%0A    // this is just for migration from contenteditable to textarea.%0A    // we can remove this later on.%0A    content = content.replace(/%3Cbr%3E/ig, '%5Cn').replace(/%3C%5C/br%3E/ig, '%5Cn').replace(/%3Cdiv%3E/ig, '%5Cn').replace(/%3C%5B%5E%3E%5D+%3E/ig, '').replace(/%5C&amp;/ig, '&')%0A
     

Remove migration code that was removing html tags cc #263