// Extend default bb-editor
Object.extend(Chrome.BBCode, {
  insertColorTag: function(color) {
    if (Chrome.BBCode.field)
      $(Chrome.BBCode.field).wrapSelection('[color=' + color + ']', '[/color]');
    return false;
  },
  insertSizeTag: function(size) {
    if (Chrome.BBCode.field)
      $(Chrome.BBCode.field).wrapSelection('[size="' + size + '"]', '[/size]');
    return false;
  },
  insertImage: function() {
    if (Chrome.BBCode.field) {
      var url = window.prompt('Введите URL', 'http://');
      if (url)
        $(Chrome.BBCode.field).replaceSelection('[img]' + url + '[/img]', true);
    }
    return false;
  },
  insertUrl: function() {
    if (Chrome.BBCode.field) {
      var url = window.prompt('Введите URL', 'http://');
      if (url)
        $(Chrome.BBCode.field).wrapSelection('[url=' + url + ']', '[/url]');
    }
    return false;
  }
});

// Element.addMethods('TEXTAREA', {
//   wrapSelection: function(element, before, after)
//   {
//     if (document.selection) {
//       element.focus();
//       var selection = document.selection.createRange();
//       selection.text = before + selection.text + after;
//     } else if (element.selectionStart || element.selectionStart == 0) {
//       var scrollPos = element.scrollTop;
//       var startPos = element.selectionStart;
//       var endPos = element.selectionEnd;
//       element.value = element.value.substring(0, startPos)
//         + before
//         + element.value.substring(startPos, endPos)
//         + after
//         + element.value.substring(endPos, element.value.length);
//       if (element.setSelectionRange) {
//         if (endPos == startPos)
//           element.setSelectionRange(startPos + before.length, startPos + before.length);
//         else
//           element.setSelectionRange(endPos + before.length + after.length, endPos + before.length + after.length);
//       }
//       element.scrollTop = scrollPos;
//     } else {
//       element.value += before + after;
//     }
//     element.focus();
//     return element;
//   }
// });

gtBBCodeField = Class.create({
  initialize: function (element, buttonContainer, buttons)
  {
    Chrome.BBCode.field = $(element);
    this.element = $(element);
    this.buttonContainer = $(buttonContainer);
    if (!this.buttonContainer) {
      return;
    }

    if (buttons.indexOf('bold') > -1) {
      var boldButton = new Element('a', {href: '#'});
      boldButton.onclick = function () {return false;}
      boldButton.addClassName('bbcgray').addClassName('bbcbold').writeAttribute('title', 'полужирный');
      this.buttonContainer.appendChild(boldButton);
      boldButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        ev.element().blur();
        Chrome.BBCode.insertTag('b');
      }).bindAsEventListener(this));
      this.element.observe('keydown', (function (ev) {
        if ((ev.ctrlKey || ev.metaKey) && !ev.altKey && 66 == ev.keyCode) {
          Chrome.BBCode.field = this.element;
          Chrome.BBCode.insertTag('b');
          ev.stop();
        }
      }).bind(this));
    }

    if (buttons.indexOf('italic') > -1) {
      var italicButton = new Element('a', {href: '#'});
      italicButton.onclick = function () {return false;}
      italicButton.addClassName('bbcgray').addClassName('bbcitalic').writeAttribute('title', 'курсив');
      this.buttonContainer.appendChild(italicButton);
      italicButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        ev.element().blur();
        Chrome.BBCode.insertTag('i');
      }).bindAsEventListener(this));
      this.element.observe('keydown', (function (ev) {
        if ((ev.ctrlKey || ev.metaKey) && !ev.altKey && 73 == ev.keyCode) {
          Chrome.BBCode.field = this.element;
          Chrome.BBCode.insertTag('i');
          ev.stop();
        }
      }).bind(this));
    }

    if (buttons.indexOf('strike') > -1) {
      var strikeButton = new Element('a', {href: '#'});
      strikeButton.onclick = function () {return false;}
      strikeButton.addClassName('bbcgray').addClassName('bbcstrike').writeAttribute('title', 'перечеркнутый');
      this.buttonContainer.appendChild(strikeButton);
      strikeButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        ev.element().blur();
        Chrome.BBCode.insertTag('s');
      }).bindAsEventListener(this));
    }

    if (buttons.indexOf('size') > -1) {
      this.createSizeButton();
    }

    if (buttons.indexOf('forumsize') > -1) {
      this.createForumSizeButton();
    }

    if (buttons.indexOf('color') > -1) {
      this.createColorButton();
    }

    if (buttons.indexOf('link') > -1) {
      var linkButton = new Element('a', {href: '#'});
      linkButton.onclick = function () {return false;}
      linkButton.addClassName('bbcgray').addClassName('bbclink').writeAttribute('title', 'сделать ссылкой');
      this.buttonContainer.appendChild(linkButton);
      linkButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        ev.element().blur();
        Chrome.BBCode.insertUrl();
      }).bindAsEventListener(this));
    }

    if (buttons.indexOf('quote') > -1) {
      var quoteButton = new Element('a', {href: '#'});
      quoteButton.onclick = function () {return false;}
      quoteButton.addClassName('bbcgray').addClassName('bbcquote').writeAttribute('title', 'цитата');
      this.buttonContainer.appendChild(quoteButton);
      quoteButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        Chrome.BBCode.insertString('[quote]' + Chrome.getSelectedText() + '[/quote]', true);
        ev.element().blur();
      }).bindAsEventListener(this));
    }

    if (buttons.indexOf('image') > -1) {
      var imageButton = new Element('a', {href: '#'});
      imageButton.onclick = function () {return false;}
      imageButton.addClassName('bbcgray').addClassName('bbcimage').writeAttribute('title', 'вставить изображение');
      this.buttonContainer.appendChild(imageButton);
      imageButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        ev.element().blur();
        Chrome.BBCode.insertImage();
      }).bindAsEventListener(this));
    }

    if (buttons.indexOf('spoil') > -1) {
      var spoilButton = new Element('a', {href: '#'});
      spoilButton.onclick = function () {return false;}
      spoilButton.addClassName('bbcgray').addClassName('bbcspoil').writeAttribute('title', 'скрытый текст');
      this.buttonContainer.appendChild(spoilButton);
      spoilButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        ev.element().blur();
        Chrome.BBCode.insertTag('spoil');
      }).bindAsEventListener(this));
    }

    if (buttons.indexOf('video') > -1) {
      var videoButton = new Element('a', {href: '#'});
      videoButton.onclick = function () {return false;}
      videoButton.addClassName('bbcgray').addClassName('bbcvideo').writeAttribute('title', 'видео (youtube, pokertube, vimeo, rutube, вконтакте)');
      this.buttonContainer.appendChild(videoButton);
      videoButton.observe('click', (function (ev) {
        Chrome.BBCode.field = this.element;
        var embedCode = window.prompt('Вставьте EMBED-код:', '');
        if (embedCode) {
          Chrome.BBCode.field.replaceSelection('[video]' + embedCode + '[/video]');
          ev.element().blur();
        }
      }).bindAsEventListener(this));
    }

  },

  createSizeButton: function ()
  {
    var sizeButton = new Element('a', {href: '#'});
    sizeButton.onclick = function () {return false;}
    sizeButton.addClassName('bbcgray').addClassName('bbcsize').writeAttribute('title', 'размер текста');
    this.buttonContainer.appendChild(sizeButton);

    var popup = new Element('div');
    var html = '<table><tr>';
    html += '<td><a href="#" onclick="this.blur(); Chrome.BBCode.insertTag(\'size15\'); return false;"><span style="font-size: 1.5em">Крупнее</span></a></td>';
    html += '</tr><tr>';
    html += '<td><a href="#" onclick="this.blur(); Chrome.BBCode.insertTag(\'size20\'); return false;"><span style="font-size: 2.0em">Еще&nbsp;крупнее</span></a></td>';
    html += '</tr></table>';
    popup.update(html).setStyle({position: 'absolute', zIndex: 50, overflow: 'visible', cursor: 'default', width: 'auto', height: 'auto', clip: 'rect(auto, auto, auto, auto)', display: 'none'});
    this.buttonContainer.appendChild(popup);

    sizeButton.observe('click', function (ev) {
      ev.element().blur();
      popup.setStyle({left: sizeButton.offsetLeft + (Prototype.Browser.IE ? -38 : 0) + 'px', top: sizeButton.offsetTop + 19 + 'px'}).show();
    });

    document.observe('click', function (ev) {
      if (sizeButton != ev.element())
        popup.hide();
    });
  },

  createForumSizeButton: function ()
  {
    var sizeButton = new Element('a', {href: '#'});
    sizeButton.onclick = function () {return false;}
    sizeButton.addClassName('bbcgray').addClassName('bbcsize').writeAttribute('title', 'размер текста');
    this.buttonContainer.appendChild(sizeButton);

    var popup = new Element('div');
    var html = '<table><tr>';
    html += '<td><a href="#" onclick="this.blur(); Chrome.BBCode.insertSizeTag(\'4\'); return false;"><span style="font-size: 1.5em">Крупнее</span></a></td>';
    html += '</tr><tr>';
    html += '<td><a href="#" onclick="this.blur(); Chrome.BBCode.insertSizeTag(\'5\'); return false;"><span style="font-size: 2.0em">Еще&nbsp;крупнее</span></a></td>';
    html += '</tr></table>';
    popup.update(html).setStyle({position: 'absolute', zIndex: 50, overflow: 'visible', cursor: 'default', width: 'auto', height: 'auto', clip: 'rect(auto, auto, auto, auto)', display: 'none'});
    this.buttonContainer.appendChild(popup);

    sizeButton.observe('click', function (ev) {
      ev.element().blur();
      popup.setStyle({left: sizeButton.offsetLeft + (Prototype.Browser.IE ? -38 : 0) + 'px', top: sizeButton.offsetTop + 19 + 'px'}).show();
    });

    document.observe('click', function (ev) {
      if (sizeButton != ev.element())
        popup.hide();
    });
  },

  colors: {
    "#000000": "Black",
    "#A0522D": "Sienna",
    "#556B2F": "DarkOliveGreen",
    "#006400": "DarkGreen",
    "#483D8B": "DarkSlateBlue",
    "#000080": "Navy",
    "#4B0082": "Indigo",
    "#2F4F4F": "DarkSlateGray",
    "#8B0000": "DarkRed",
    "#FF8C00": "DarkOrange",
    "#808000": "Olive",
    "#008000": "Green",
    "#008080": "Teal",
    "#0000FF": "Blue",
    "#708090": "SlateGray",
    "#696969": "DimGray",
    "#FF0000": "Red",
    "#F4A460": "SandyBrown",
    "#9ACD32": "YellowGreen",
    "#2E8B57": "SeaGreen",
    "#48D1CC": "MediumTurquoise",
    "#4169E1": "RoyalBlue",
    "#800080": "Purple",
    "#808080": "Gray",
    "#FF00FF": "Magenta",
    "#FFA500": "Orange",
    "#FFFF00": "Yellow",
    "#00FF00": "Lime",
    "#00FFFF": "Cyan",
    "#00BFFF": "DeepSkyBlue",
    "#9932CC": "DarkOrchid",
    "#C0C0C0": "Silver",
    "#FFC0CB": "Pink",
    "#F5DEB3": "Wheat",
    "#FFFACD": "LemonChiffon",
    "#98FB98": "PaleGreen",
    "#AFEEEE": "PaleTurquoise",
    "#ADD8E6": "LightBlue",
    "#DDA0DD": "Plum",
    "#FFFFFF": "White"
  },

  createColorButton: function ()
  {
    var colorButton = new Element('a', {href: '#'});
    colorButton.onclick = function () {return false;}
    colorButton.addClassName('bbcgray').addClassName('bbccolor').writeAttribute('title', 'цвет текста');
    this.buttonContainer.appendChild(colorButton);

    var popup = new Element('div');
    var html = '<table><tr>';
    $H(this.colors).each(function (name, index) {
      if (0 == index % 8 && index)
        html += '</tr><tr>';
      html += '<td><a href="#" style="display: block;" onclick="this.blur(); Chrome.BBCode.insertColorTag(\'' + name[0] + '\'); return false;"><div title="' + name[1] + '" style="background-color: ' + name[0] + '; border:1px solid #ACA899; height:10px; width:10px;"></div></a></td>';
    });
    html += '</tr></table>';
    popup.update(html).setStyle({position: 'absolute', zIndex: 50, overflow: 'visible', cursor: 'default', width: 'auto', height: 'auto', clip: 'rect(auto, auto, auto, auto)', display: 'none'});
    this.buttonContainer.appendChild(popup);

    colorButton.observe('click', function (ev) {
      ev.element().blur();
      popup.setStyle({left: colorButton.offsetLeft + (Prototype.Browser.IE ? -38 : 0) + 'px', top: colorButton.offsetTop + 19 + 'px'}).show();
    });

    document.observe('click', function (ev) {
      if (colorButton != ev.element())
        popup.hide();
    });
  }

});

