/**
 * Textarea handling thanks to http://livepipe.net/control/textarea
 */
var IntoTextarea = Class.create(
{
  initialize: function (el)
  {
    this._el = el;
    this._opts = Object.extend(
    {
      plugins: []
    }, arguments[1] || {});

    this._create();
  },

  _create: function ()
  {
    var toolbar = new Element('div', { className: 'IntoTextarea-toolbar' });

    $A(this._opts.plugins).each(function (plugin)
    {
      eval('var p = new IntoTextareaPlugin_' + plugin + '(this);');
      toolbar.insert(p);
    }.bind(this));

    this._el.insert({ before: toolbar });
  },

  getSelection: function()
  {
    if (!!document.selection)
      return document.selection.createRange().text;
    else if (!!this._el.setSelectionRange)
      return this._el.value.substring(this._el.selectionStart, this._el.selectionEnd);
    else
      return false;
  },

  replaceSelection: function(text)
  {
    var scrollTop = this._el.scrollTop;

    if (!!document.selection)
    {
      this._el.focus();
      var range = (this.range) ? this.range : document.selection.createRange();
      range.text = text;
      range.select();
    }
    else if (!!this._el.setSelectionRange)
    {
      var selectionStart = this._el.selectionStart;
      this._el.value = this._el.value.substring(0, selectionStart) + text + this._el.value.substring(this._el.selectionEnd);
      this._el.setSelectionRange(selectionStart + text.length, selectionStart + text.length);
    }
    
    this._el.focus();
    this._el.scrollTop = scrollTop;
  },

  wrapSelection: function (before, after)
  {
    var sel = this.getSelection();

    // remove the wrapping if the selection has the same before/after
    if (sel.indexOf(before) === 0 && sel.lastIndexOf(after) === (sel.length - after.length))
      this.replaceSelection(sel.substring(before.length, sel.length - after.length));
    else
      this.replaceSelection(before + sel + after);
  }
});
