/**
 * Простенький WYSIWYG редактор
 * Основан на jQuery
 *
 * @param {Object} textarea
 */
var SimpleEditor = function(textarea)
{
  var editorFolder = '/js/simpleditor/';

  this.textarea = textarea;
  var img = editorFolder + 'icons/';

  this.snip = {}; // Сниппеты с HTML кодом
  this.snip.container = '<div class="simple-editor"></div>';
  this.snip.iframe = '<iframe src="' + editorFolder + 'iframe.html?r=8"></iframe>';
  this.snip.clear = '<div style="clear:both"></div>';
  this.snip.icons = {
    b : '<img src="' + img + 'bold.gif" alt="Bold" />',
    i : '<img src="' + img + 'italic.gif" alt="Italic" />',
    u : '<img src="' + img + 'underline.gif" alt="Underline" />',
    s : '<img src="' + img + 'strike.gif" alt="Strikethrough" />',
    q : '<img src="' + img + 'quote.gif" alt="Quote" />',
    a : '<img src="' + img + 'url.gif" alt="URL" />'
  }

  this.init();
}
/**
 * Ссылка на контейнер с редактором
 * @type {Object}
 */
SimpleEditor.prototype.se = null;

SimpleEditor.prototype.init = function()
{
  $(this.textarea).hide();

  // Рисуем необходимые эл-ты управления
  $(this.textarea).wrap(this.snip.container);
  $(this.textarea).after(this.snip.iframe + this.snip.clear);
  $(this.textarea).before(this.snip.icons.b + this.snip.icons.i + this.snip.icons.u +
    this.snip.icons.s + this.snip.icons.q + this.snip.icons.a + this.snip.clear);

  // Сохраняем сслыки на объекты
  this.se = $(this.textarea).parent();
  this.iframe = $(this.se).find('iframe').get(0);

  var SE = this;

  // Инициализация фрейма
  $(this.iframe).load(function(){
    SE.iload();
  });

  // Оживляем кнопки
  $(this.se).find('img').click(function(){
    SE.tag($(this).attr('alt'));
  });
}
/**
 * Очищает данные в редакторе
 */
SimpleEditor.prototype.reset = function(text)
{
  $(this.textarea).html('<br>');
  this.iload();
}
/**
 * Инициализация фрейма
 */
SimpleEditor.prototype.iload = function()
{
  var iDoc = this.idocument();
  var html = $(this.textarea).html();

  var pattern = [/&lt;/i, /&gt;/i, /&amp;/i];
  var replace = ['<', '>', '&'];
  for (var i = 0, l = pattern.length; i < l; i++)
    while(html.search(pattern[i]) > -1)
      html = html.replace(pattern[i], replace[i]);

  iDoc.body.innerHTML = html;
  iDoc.designMode = 'On';
  try {
    // for Gecko Browsers
    iDoc.execCommand("useCSS", false, true);
  } catch (e) {}
}
/**
 * Возвращает ссылку на contentWindow.document в iframe
 */
SimpleEditor.prototype.idocument = function()
{
  this.doc = this.doc || this.iframe.contentWindow ? this.iframe.contentWindow.document : null;
  return this.doc;
}
/**
 * Применение тега
 */
SimpleEditor.prototype.tag = function(tagname)
{
  var iDoc = this.idocument();
  if (tagname != 'Quote' && tagname != 'URL') {
    iDoc.execCommand(tagname, false, "");
  } else {
    if (tagname == 'Quote') this.tagQuote();
    if (tagname == 'URL')   this.tagURL();
  }
  return false;
}
/**
 * Вставка ссылки
 */
SimpleEditor.prototype.tagURL = function()
{
  iDoc = this.idocument();
  var URL = prompt("Введите адрес сайта", "http://");

  if (iDoc.getSelection) {
    len = iDoc.getSelection();
  } else if (iDoc.selection) {
    len = iDoc.selection.createRange().text;
  }

  if (len != "") {
    iDoc.execCommand("CreateLink", false, URL);
  } else {
    var link = document.createElement('a');
    link.href = URL;
    link.innerHTML = prompt("Введите название сайта", "Сайт");
    this.insertNode(link);
  }
  return false;
}
/**
 * Вставка цитаты
 */
SimpleEditor.prototype.tagQuote = function()
{
  var iWin = this.iframe.contentWindow;
  var iDoc = this.idocument();

  var sel = (iDoc.selection) ? iDoc.selection : iWin.getSelection();
  var rng = (sel.createRange) ? sel.createRange() : sel.getRangeAt(sel.rangeCount - 1);

  if (rng.pasteHTML) { // IE
    html = '<span class="blockquote">' + rng.text + "</span><br />";
    rng.pasteHTML(html);
  } else if (rng.insertNode) { // Gecko
    var div = document.createElement("span");
    div.className = 'blockquote';
    div.innerHTML = sel;
    rng.deleteContents();
    rng.insertNode(div);
  }
  return false;
}
SimpleEditor.prototype.tagImg = function(src)
{
  var iDoc = this.idocument();
  iDoc.execCommand('InsertImage', false, src);

  return false;
}
SimpleEditor.prototype.insertNode = function(anode)
{
  var iWin = this.iframe.contentWindow;
  var iDoc = this.idocument();

  var ua = navigator.userAgent.toLowerCase();
  var isOpera = ua.indexOf("opera") != -1;
  var sel = (iDoc.selection) ? iDoc.selection : iWin.getSelection();
  var rng = (sel.createRange) ? sel.createRange() : sel.getRangeAt(sel.rangeCount - 1);
  if (rng.pasteHTML) { // IE
    var sp = document.createElement("span");
    sp.appendChild(anode);
    rng.pasteHTML(sp.innerHTML);
  } else if (rng.insertNode && !isOpera) { // Gecko
    rng.deleteContents();
    rng.insertNode(anode);
  } else if (isOpera) { // Opera
    var sp = document.createElement("span");
    sp.appendChild(anode);
    iDoc.body.innerHTML += sp.innerHTML;
  }
}
/**
 * Вставка цитаты
 *
 * @param {String} text текст цитаты
 * @param {String} cite автор цитаты
 */
SimpleEditor.prototype.addQuote = function (text, cite)
{
  cite = cite || '';
  this.idocument().body.innerHTML += '<blockquote cite="' + cite + '">' + text + "</blockquote>";
  return true;
}
/**
 * Вставка созданного текста из фрейма обратно в textarea
 */
SimpleEditor.prototype.getText = function ()
{
  var iDoc = this.idocument();
  $(this.textarea).val(iDoc.body.innerHTML);
  return $(this.textarea).val();
}
/**
 * Вставка созданного текста из фрейма обратно в textarea для всех найденых редакторов
 */
var SimpleEditorGetText = function()
{
  $('.simple-editor').each(function(){
    var iFrm = $(this).find('iframe').get(0);
    var iTxt = $(this).find('textarea').get(0);
    var iDoc = iFrm.contentWindow ? iFrm.contentWindow.document : null;
    if (iDoc) $(iTxt).val(iDoc.body.innerHTML);
  });
}
