//##############################################################################
//# ubbc.js                                                                    #
//##############################################################################
//# YaBB: Yet another Bulletin Board                                           #
//# Open-Source Community Software for Webmasters                              #
//# Version:        YaBB 2.2.1                                                 #
//# Packaged:       March 5, 2008                                              #
//# Distributed by: http://www.yabbforum.com                                   #
//# ===========================================================================#
//# Copyright (c) 2000-2008 YaBB (www.yabbforum.com) - All Rights Reserved.    #
//# Software by:  The YaBB Development Team                                    #
//#               with assistance from the YaBB community.                     #
//# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com           #
//#               Your source for web hosting, web design, and domains.        #
//##############################################################################

//YaBB 2.2.1 $Revision: 1.5.2.3 $

function submitproc() {
	if (window.submitted) return false;
	window.submitted = true;
	return true;
}

function storeCaret(text) { 
	if (text.createTextRange) text.caretPos = document.selection.createRange().duplicate();
}

function AddSelText(bbopen, bbclose) {
	if (document.postmodify.message.caretPos) {
		var old_length = document.postmodify.message.caretPos.text.length;
		document.postmodify.message.caretPos.text = bbopen + document.postmodify.message.caretPos.text + bbclose;
		if (old_length == 0) document.postmodify.message.caretPos.moveStart("character", -bbclose.length);
		else document.postmodify.message.caretPos.moveStart("character", -(bbclose.length + old_length));
		document.postmodify.message.caretPos.moveEnd("character", -bbclose.length);
		document.postmodify.message.caretPos.select();
	}
	else if (document.postmodify.message.setSelectionRange) {
		var selectionStart = document.postmodify.message.selectionStart;
		var selectionEnd = document.postmodify.message.selectionEnd;
		var currentTop = document.postmodify.message.scrollTop;		
		var replaceString = bbopen + document.postmodify.message.value.substring(selectionStart, selectionEnd) + bbclose;
		document.postmodify.message.value = document.postmodify.message.value.substring(0, selectionStart) + replaceString + document.postmodify.message.value.substring(selectionEnd);
		document.postmodify.message.setSelectionRange(selectionStart + bbopen.length, selectionEnd + bbopen.length);
		document.postmodify.message.scrollTop = currentTop;		
	}
	else document.postmodify.message.value += bbopen + bbclose;
	document.postmodify.message.focus()
}

function AddText(text) {
	AddSelText(text, '');
}

function AddSelTextUrl(bbopen, bbclose) {
	var thetext = '';
	var theurl = '';
	blopen = bbopen.substring(0, bbopen.length - 1)
	if (document.postmodify.message.caretPos) {
		tmpString=document.postmodify.message.caretPos.text.replace(/\s*(.+?)\s*$/i, "$1");
		var old_length = tmpString.length;
		spliturl = tmpString.split(" ");
		theurl = spliturl[0];
		if ( spliturl.length > 1 && (theurl.match(/\S\.\S/)) ) {
			for (var i=1; i < spliturl.length; i++) { thetext += spliturl[i]; if (i < (spliturl.length - 1)) { thetext += " " } }
			document.postmodify.message.caretPos.text = blopen + '=' + theurl + ']' + thetext + bbclose;
		}
		else document.postmodify.message.caretPos.text = bbopen + tmpString + bbclose;
		if (old_length == 0) document.postmodify.message.caretPos.moveStart("character", -bbclose.length);
		document.postmodify.message.caretPos.moveEnd("character", -bbclose.length);
		document.postmodify.message.caretPos.select();
	}
	else if (document.postmodify.message.setSelectionRange) {
		var markString = blopen + '=';
		var selectionStart = document.postmodify.message.selectionStart;
		var selectionEnd = document.postmodify.message.selectionEnd;
		var currentTop = document.postmodify.message.scrollTop;
		var tmpString = document.postmodify.message.value.substring(selectionStart, selectionEnd);
		spliturl=tmpString.replace(/\s*(.+?)\s*$/i, "$1");
		spliturl = spliturl.split(" ");
		theurl = spliturl[0];
		if ( spliturl.length > 1 && (theurl.match(/\S\.\S/)) ) {
			for (var i=1; i < spliturl.length; i++) { thetext += spliturl[i]; if (i < (spliturl.length - 1)) { thetext += " " } }
			markString = blopen + '=' + theurl + ']';
			replaceString = blopen + '=' + theurl + ']' + thetext + bbclose;
		}
		else replaceString = bbopen + tmpString + bbclose;
		document.postmodify.message.value = document.postmodify.message.value.substring(0, selectionStart) + replaceString + document.postmodify.message.value.substring(selectionEnd);
		document.postmodify.message.setSelectionRange(selectionStart + markString.length, selectionEnd + bbopen.length);
		document.postmodify.message.scrollTop = currentTop;		
	}
	else document.postmodify.message.value += bbopen + bbclose;
	document.postmodify.message.focus()
}

function emai1() {
	AddSelTextUrl("[email]","[/email]");
}


function hyperlink() {
	AddSelTextUrl("[url]","[/url]");
}

function hr() {
	AddText("[hr]");
}

function timestamp(thetime) {
	thetime += cntsec;
	AddText("[timestamp="+thetime+"]");
}

function size() {
	AddSelText("[size=12]","[/size]");
}

function edit() {
	AddSelText("[edit]","[/edit]");
}

function me() {
	AddText("/me");
}

function fntsize(size) {
	AddSelText("[size="+size+"]","[/size]");
	document.getElementById("fontsize").options[0].text = size;
	document.getElementById("fontsize").options[0].selected = true;
}

function font() {
	AddSelText("[font=Verdana]","[/font]");
}

function fontfce(font) {
	AddSelText("[font="+font+"]","[/font]");
	document.getElementById("fontface").options[0].text = font;
	document.getElementById("fontface").options[0].selected = true;
}

function highlight() {
	AddSelText("[highlight]","[/highlight]");
}

function me() {
        AddText("/me ");
}

function teletype() {
	AddSelText("[tt]","[/tt]");
}

function right() {
	AddSelText("[right]","[/right]");
}

function left() {
	AddSelText("[left]","[/left]");
}

function superscript() {
	AddSelText("[sup]","[/sup]");
}

function subscript() {
	AddSelText("[sub]","[/sub]");
}

function image() {
	AddSelText("[img]","[/img]");
}

function ftp() {
	AddSelText("[ftp]","[/ftp]");
}

function move() {
	AddSelText("[move]","[/move]");
}

function flash() {
	AddSelText("[media]","[/media]");
}

function pre() {
	AddSelText("[pre]","[/pre]");
}

function tcol() {
	AddSelText("[td]","[/td]");
}

function trow() {
	AddSelText("[tr]","[/tr]");
}

function table() {
	AddSelText("[table][tr][td]", "[/td][/tr][/table]");
}

function strike() {
	AddSelText("[s]","[/s]");
}

function underline() {
	AddSelText("[u]","[/u]");
}

function bold() {
	AddSelText("[b]","[/b]");
}

function italicize() {
	AddSelText("[i]","[/i]");
}

function quote() {
	AddSelText("[quote]","[/quote]");
}

function center() {
	AddSelText("[center]","[/center]");
}

function showcode() {
	AddSelText("[code]","[/code]");
}

function list() {
	AddSelText("[list][*]", "\n[/list]");
}

function showcolor(color) {
	AddSelText("[color="+color+"]","[/color]");
}

function smiley() {
	AddText(" :)");
}

function wink() {
	AddText(" ;)");
}

function cheesy() {
	AddText(" :D");
}

function grin() {
	AddText(" ;D");
}

function angry() {
	AddText(" >:(");
}

function sad() {
	AddText(" :(");
}

function shocked() {
	AddText(" :o");
}

function cool() {
	AddText(" 8-)");
}

function huh() {
	AddText(" :-?");
}

function rolleyes() {
	AddText(" ::)");
}

function tongue() {
	AddText(" :P");
}

function lipsrsealed() {
	AddText(" :-X");
}

function embarassed() {
	AddText(" :-[");
}

function undecided() {
	AddText(" :-/");
}

function kiss() {
	AddText(" :-*");
}

function cry() {
	AddText(" :'(");
}
function spoiler() {
	AddSelText("[spoiler]","[/spoiler]");
}

//beginning of formulaPopup script
var formulaPopupOpen = 0;
var formulaPopupHalfWidth = 150;
var formulaField = 30;
var input = document.createElement('input');
input.type = 'text';
input.style.width = '100px';
input.style.border = '1px solid #ffffa8';
input.style.paddingLeft = '1px';
input.style.paddingRight = '1px';
input.style.background='#ffffa8';
input.style.fontFamily='Courier, Courier New';
input.style.fontSize='12px';
input.style.verticalAlign='middle';

var link = document.createElement('a');
link.href = 'javascript:formulaPopup.parentNode.removeChild(formulaPopup);void(formulaPopupOpen=0);';
link.style.verticalAlign='middle';
link.style.color='red';
link.appendChild(document.createTextNode('X'));
link.onmouseover='return true; ';
link.title='Close';

var formulaPopup = document.createElement('div');
formulaPopup.className = 'formulaPopup';
formulaPopup.style.border='1px solid #404040';
formulaPopup.style.position='absolute';
formulaPopup.style.background='#ffffa8';
formulaPopup.appendChild(input);
formulaPopup.appendChild(link);

function formulaMouseOver(img)
{
  img.style.background = '#ffffa8';
}

function formulaMouseOut(img)
{
  img.style.background = '';
}

function formulaClick(img,evt)
{
  if (!formulaPopupOpen)
  {
    document.body.appendChild(formulaPopup);
    formulaPopupOpen=1;
  }

  input.value = img.alt;

  evt = evt || window.event;
  var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
  var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  var left = evt.clientX + scrollLeft;
  var top = evt.clientY + scrollTop;

  formulaPopupHalfWidth = img.alt.length*3.5;
  if(formulaPopupHalfWidth>150) formulaPopupHalfWidth=150;
  input.style.width = 2*formulaPopupHalfWidth+'px';
  if (left - formulaPopupHalfWidth < scrollLeft)
    formulaPopup.style.left = scrollLeft + 'px';
  else if (left + formulaPopupHalfWidth >= scrollLeft + window.innerWidth)
    formulaPopup.style.left = scrollLeft + window.innerWidth - 2*formulaPopupHalfWidth - formulaField + 'px';
  else
    formulaPopup.style.left = left - formulaPopupHalfWidth + 'px';

  formulaPopup.style.top = top + 'px';

  if (input.focus) input.focus();
  if (input.select) input.select();
  if (input.copy) input.copy();
}
// end of formulaPopup script

var selection='';
var quote_name='';
var quote_topic_id='';
var quote_msg_id='';
var quote_msg_id2='';
var quote_date=0;

var userSelection;
var IEselection;
var tag_stack=new Array();
var quote_str_stack=new Array();

function quoteSelection(_name, _topic_id, _msg_id, _date) {
    if (userSelection) {
            quote_name=_name;
            quote_topic_id=_topic_id;
            quote_msg_id=_msg_id;
            quote_date=_date;
            quote_str_stack.length=0;
            AddText('[quote author='+quote_name+' link='+quote_topic_id+'/'+quote_msg_id+'#'+quote_msg_id+' date='+quote_date+']'+
              convert_nodes_to_bbcodes(userSelection.getRangeAt(0).cloneContents())+
              ' [/quote] ');
            userSelection = '';
            return;
      } else if(IEselection) {
            quote_name=_name;
            quote_topic_id=_topic_id;
            quote_msg_id=_msg_id;
            quote_date=_date;
            tag_stack.length=0;
            AddText('[quote author='+quote_name+' link='+quote_topic_id+'/'+quote_msg_id+'#'+quote_msg_id+' date='+quote_date+']'+
              convert_html_to_bbcodes(IEselection.createRange().htmlText)+' [/quote] ');
            IEselection = '';
            return;
      } else {
            alertqq();
      }
}

if(!window.Node) {
  var Node={
    ELEMENT_NODE: 1,
    ATTRIBUTE_NODE: 2,
    TEXT_NODE: 3,
    CDATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8,
    DOCUMENT_NODE: 9,
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11,
    NOTATION_NODE: 12
  }
}

function toHexSextet(r,g,b) {
  var rh=parseInt(r,10).toString(16);
  if(rh.length==1) rh='0'+rh;
  var gh=parseInt(g,10).toString(16);
  if(gh.length==1) gh='0'+gh;
  var bh=parseInt(b,10).toString(16);
  if(bh.length==1) bh='0'+bh;
  return rh+gh+bh;
}

var smilies_hash=new Object();
smilies_hash['Улыбка']=':)';
smilies_hash['Подмигивание']=';)';
smilies_hash['Очень довольный']=':D';
smilies_hash['Смех']=';D';
smilies_hash['Злой']='>:(';
smilies_hash['Печаль']=':( ';
smilies_hash['Ужас']=':o';
smilies_hash['Класс']='8-)';
smilies_hash['Озадачен']=':-?';
smilies_hash['Круглые глаза']='::)';
smilies_hash['Язык']=':P';
smilies_hash['Смущённый']=':-[';
smilies_hash['Со сжатыми губами']=':-X';
smilies_hash['Нерешительный']=':-/';
smilies_hash['Поцелуй']=':-*';
smilies_hash['Плачущий']=":'(";

smilies_hash['Smiley']=':)';
smilies_hash['Wink']=';)';
smilies_hash['Cheesy']=':D';
smilies_hash['Grin']=';D';
smilies_hash['Angry']='>:(';
smilies_hash['Sad']=':( ';
smilies_hash['Shocked']=':o';
smilies_hash['Cool']='8-)';
smilies_hash['Huh']=':-?';
smilies_hash['Roll Eyes']='::)';
smilies_hash['Tongue']=':P';
smilies_hash['Embarrassed']=':-[';
smilies_hash['Lips Sealed']=':-X';
smilies_hash['Undecided']=':-/';
smilies_hash['Kiss']=':-*';
smilies_hash['Cry']=":'(";

function convert_nodes_to_bbcodes(n) {
  var bbc_str="";
  if(n.hasChildNodes()) { // recursion
    var childs_bbc_str="";
    for(var i=0;i<n.childNodes.length;i++) {
      childs_bbc_str=childs_bbc_str+convert_nodes_to_bbcodes(n.childNodes[i]);
    }

    switch(n.nodeType) {
      case Node.ELEMENT_NODE: // html-element which has childs
        switch(n.nodeName.toLowerCase()) {
          case 'i':
          case 'u':
          case 's':
          case 'tt':
          case 'center':
          case 'table':
          case 'tr':
          case 'td':
          case 'sup':
          case 'sub':
            bbc_str=bbc_str+'['+n.nodeName.toLowerCase()+']'
             +childs_bbc_str+'[/'+n.nodeName.toLowerCase()+']';
            break;
          case 'tbody':
            bbc_str=bbc_str+childs_bbc_str;
            break;
          case 'marquee':
            bbc_str=bbc_str+'[move]'+childs_bbc_str+'[/move]';
            break;
          case 'ul':
            bbc_str=bbc_str+'[list]'+childs_bbc_str+'[/list]';
            break;
          case 'li':
            bbc_str=bbc_str+'[*]'+childs_bbc_str;
            break;
          case 'b': // needs special processing if used as title for other bbcodes
            if(n.childNodes.length==1 &&
               n.firstChild.nodeType==Node.TEXT_NODE &&
               (n.firstChild.nodeValue=='Код:' ||
                n.firstChild.nodeValue=='Цитата:' ||
                n.firstChild.nodeValue=='Изменено: ' ||
                n.firstChild.nodeValue=='Code:' ||
                n.firstChild.nodeValue=='Quote:' ||
                n.firstChild.nodeValue=='Edited: ')) {} //do nothing
            else { bbc_str=bbc_str+'[b]'+childs_bbc_str+'[/b]'; }
            break; 
          case 'pre': // needs  special processing if used for [code]
            if(n.getAttribute("CLASS")=='code') {
              bbc_str=bbc_str+'[code]'+childs_bbc_str.replace(/\n$/,'')+'[/code]';
            } else { bbc_str=bbc_str+'[pre]'+childs_bbc_str+'[/pre]'; }
            break; 
          case 'span':
            if(n.getAttribute("CLASS")=='highlight') { // highlight
              bbc_str=bbc_str+'[highlight]'+childs_bbc_str+'[/highlight]';
              break;
            }
            if(n.getAttribute("CLASS")=='quoteheader') { // quote header
              var qstr='';
              if(n.getAttribute("AUTHOR"))
                qstr=qstr+' author='+n.getAttribute("AUTHOR");
              if(n.getAttribute("LINK"))
                qstr=qstr+' link='+n.getAttribute("LINK");
              if(n.getAttribute("DATE"))
                qstr=qstr+' date='+n.getAttribute("DATE");
              quote_str_stack.push(qstr);
              break;
            }
            if(n.attributes.length==1) {
              var c=n.getAttribute("STYLE");
              var d;
              if(d=c.match(/^\s*color\:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\);\s*$/i)) { // color
                bbc_str=bbc_str+'[color=#'+toHexSextet(d[1],d[2],d[3])+']'+
                  childs_bbc_str+'[/color]'; }
              else if(d=c.match(/^\s*font-size\:\s*(\d+)px;\s*$/i)) { // size
                bbc_str=bbc_str+'[size='+d[1]+']'+childs_bbc_str+'[/size]'; }
              else if(d=c.match(/^\s*font-family\:\s*([^;]+);\s*$/i)) { // font
                bbc_str=bbc_str+'[font='+d[1]+']'+childs_bbc_str+'[/font]'; }
              else {
//                alert('Warning: unexpected SPAN element '+c);
              }
            } else {
//              alert('Warning: unexpected SPAN element multi-attribute');
            }
            break;
          case 'div':
            if(n.attributes.length==1 && n.getAttribute("STYLE")) {
              var d=n.getAttribute("STYLE").match(/^\s*text-align\:\s*([^;]+);\s*$/i);
              if(d[1]=='left' || d[1]=='right') {
                bbc_str=bbc_str+'['+d[1]+']'+childs_bbc_str+'[/'+d[1]+']';
              } else {
//                alert('Warning: unexpected DIV element '+n.getAttribute("STYLE"));
              }
            } else if(n.getAttribute("CLASS")=='quote') {
              if(quote_str_stack.length) {
                bbc_str=bbc_str+'[quote'+quote_str_stack.pop()+']'+childs_bbc_str+'[/quote]';
              } else {
                bbc_str=bbc_str+'[quote]'+childs_bbc_str+'[/quote]';
              }
            } else if(n.getAttribute("CLASS")=='editbg') {
              bbc_str=bbc_str+'[edit]'+childs_bbc_str+'[/edit]';
            } else { 
//              alert('Warning: unexpected DIV element multi-attribute');
            }
            break;
          case 'a':
            var c=n.getAttribute("HREF");
            if(c.search(/^http\:/i)!=-1) {
              if(n.getAttribute("TARGET")=='_blank') {
                bbc_str=bbc_str+'[url='+c+']'+childs_bbc_str+'[/url]';
              } else {
                bbc_str=bbc_str+'[link='+c+']'+childs_bbc_str+'[/link]';
              }
            } else if(c.search(/^ftp\:/i)!=-1) {
              bbc_str=bbc_str+'[ftp]'+c+'[/ftp]';
            } else if(c.search(/^mailto\:/i)!=-1) {
              bbc_str=bbc_str+'[email='+c+']'+childs_bbc_str+'[/email]';
            } else {
//              alert('Warning: unexpected A element '+c);
            }
            break;
          default:
//            alert('Warning: unexpected element, name '+n.nodeName);
        }
        break;
      case Node.DOCUMENT_FRAGMENT_NODE:
        bbc_str=childs_bbc_str;
        break;
      default: // DOCUMENT, ATTRIBUTE, ENTITY_REFERENCE, ENTITY or unknown node
//        alert('Warning: unexpected node, type '+n.nodeType);
    }

  } else { // converting
    switch(n.nodeType) {
      case Node.ELEMENT_NODE:
        switch(n.nodeName.toLowerCase()) {
          case 'br':
            bbc_str=bbc_str+'\n';
            break;
          case 'hr':
            bbc_str=bbc_str+'[hr]';
            break;
          case 'img':
            var c=n.getAttribute('SRC');
            var a=n.getAttribute('ALT');
            if(c.search(/\/Templates\/Forum\//)!=-1 &&
               smilies_hash.hasOwnProperty(a)) { // smilies
              bbc_str=bbc_str+smilies_hash[a];
            } else if(a.charAt(0)=='$' && a.charAt(a.length-1)=='$') { // formula
              bbc_str=bbc_str+a;
            } else { bbc_str=bbc_str+'[img]'+c+'[/img]'; }
            break;
          default:
//            alert('Warning: unexpected element '+n.nodeName);
        }
        break;
      case Node.TEXT_NODE:
        bbc_str=bbc_str+n.nodeValue;
        break;
      case Node.DOCUMENT_FRAGMENT_NODE:
        bbc_str=childs_bbc_str;
        break;
      default: // ATTRIBUTE, CDATA_SELECTION*, ENTITY_REFERENCE,
        // ENTITY, PROCESSING_INSTRUCTION*, COMMENT*, DOCUMENT,
        // DOCUMENT_TYPE*, NOTATION* or unknown node (* --- no childs)
//        alert('Warning: unexpected node, type '+n.nodeType);
    }
  }
  return bbc_str;
}

function decode_html_special_chars(ht) {
  ht=ht.replace(/&amp;/g,'&');
  ht=ht.replace(/&nbsp;/g,' ');
  ht=ht.replace(/&gt;/g,'>');
  ht=ht.replace(/&lt;/g,'<');
  ht=ht.replace(/&#123;/g,'{');
  ht=ht.replace(/&#124;/g,'|');
  ht=ht.replace(/&#125;/g,'}');
  ht=ht.replace(/&quot;/g,'"');
  ht=ht.replace(/\n|\r/g,'');
  return ht;
}

function convert_html_to_bbcodes(ht) {
//alert(ht);
  var pos=ht.indexOf('<');
  if(pos>0) { // have portion of simple text, split
    return convert_html_to_bbcodes(ht.slice(0,pos))+
      convert_html_to_bbcodes(ht.slice(pos));
  } else if(pos==-1) { // simple text
//alert('Simple text: '+ht);
    return decode_html_special_chars(ht);
  } else { // pos=0, html tag comes first, process
    var bbc_str='';
    var tag=ht.match(/^<\/?([a-z]+)([^>]*)>/i);
    pos=tag[0].length; 
    if(tag[0].charAt(1)=='/') { // close tag
//alert('Close tag: '+tag[0]+', stack: '+tag_stack);
      bbc_str=tag_stack.pop();
    } else { // open tag
//alert('Open tag: '+tag[0]);     
      switch(tag[1].toLowerCase()) {
        case 'i':
        case 'u':
        case 's':
        case 'tt':
        case 'center':
        case 'table':
        case 'tr':
        case 'td':
        case 'sup':
        case 'sub':
          tag_stack.push('[/'+tag[1].toLowerCase()+']');
          bbc_str='['+tag[1].toLowerCase()+']';
          break;
        case 'tbody':
          tag_stack.push('');
          break;
        case 'marquee':
          tag_stack.push('[/move]');
          bbc_str='[move]';
          break;
        case 'ul':
          tag_stack.push('[/list]');
          bbc_str='[list]';
          break;
        case 'li':
          tag_stack.push('');
          bbc_str='[*]';
          break;
        case 'b': // needs special processing if used as title for other bbcodes
          var b=ht.match(/^<b>(?:Код\:|Цитата\:|Изменено\: |Code\:|Quote\:|Edited: )<\/b>/i);
          if(b!=null) {
            pos=b[0].length; // skip tag content
          } else {
            tag_stack.push('[/b]');
            bbc_str='[b]';
          }
          break; 
        case 'pre': // needs  special processing if used for [code]
          if(tag[2].match(/class=(?:"code"|code)/i)) {
            tag_stack.push('[/code]');
            bbc_str='[code]';
          } else {
            tag_stack.push('[/pre]');
            bbc_str='[pre]';
          }
          break;
        case 'span':
          var d;
          if(tag[2].match(/class=(?:"highlight"|highlight)/i)) { // highlight
            tag_stack.push('[/highlight]');
            bbc_str='[highlight]';
          } else if(tag[2].match(/class=(?:"quoteheader"|quoteheader)/i)) {
            var qstr='';
            if(d=tag[2].match(/author=(?:"([^\s]+)"|([^\s]+))/i)) qstr=qstr+' author='+d[1]+d[2];
            if(d=tag[2].match(/link=(?:"([\d#\/]+)"|([\d#\/]+))/i)) qstr=qstr+' link='+d[1]+d[2];
            if(d=tag[2].match(/date=(?:"(\d+)"|(\d+))/i)) qstr=qstr+' date='+d[1]+d[2];
            quote_str_stack.push(qstr);
            pos=ht.match(/^<span[\s\S]*?<\/span>/i)[0].length; // skip tag content
          } else if(d=tag[2].match(/style="color\:\s*#([0-9a-f]{6})"/i)) {
            tag_stack.push('[/color]');
            bbc_str='[color=#'+d[1]+']';
          } else if(d=tag[2].match(/style="font-size\:\s*(\d+)px"/i)) {
            tag_stack.push('[/size]');
            bbc_str='[size='+d[1]+']';
          } else if(d=tag[2].match(/style="font-family\:\s*([^"]+)"/i)) {
            tag_stack.push('[/font]');
            bbc_str='[font='+d[1]+']';
          } else {
//            alert('Warning: unexpected SPAN element '+tag[0]);
            tag_stack.push('');
          }
          break;
        case 'div':
          if(tag[2].match(/style="text-align\:\s*left"/i)) {
            tag_stack.push('[/left]');
            bbc_str='[left]';
          } else if(tag[2].match(/style="text-align\:\s*right"/i)) {
            tag_stack.push('[/right]');
            bbc_str='[right]';
          } else if(tag[2].match(/class=(?:"quote"|quote)/i)) {
            tag_stack.push('[/quote]');
            if(quote_str_stack.length) {
                bbc_str='[quote'+quote_str_stack.pop()+']';
              } else {
                bbc_str='[quote]';
              }
          } else if(tag[2].match(/class=(?:"editbg"|editbg)/i)) {
            tag_stack.push('[/edit]');
            bbc_str='[edit]';
          } else { 
//            alert('Warning: unexpected DIV element '+tag[0]);
            tag_stack.push('');
          }
          break;
        case 'a':
          var h=tag[2].match(/href="(([a-z]+)\:[^"]*)"/i);
          switch(h[2].toLowerCase(0)) {
            case 'http':
              if(tag[2].match(/target=(?:"_blank"|_blank)/i)) {
                tag_stack.push('[/url]');
                bbc_str='[url='+h[1]+']';
              } else {
                tag_stack.push('[/link]');
                bbc_str='[link='+h[1]+']';
              }
              break;
            case 'ftp':
              tag_stack.push('[/ftp]');
              bbc_str='[ftp]';
              break;
            case 'mailto':
              tag_stack.push('[/email]');
              bbc_str='[email='+h[1]+']';
              break;
            default:
//              alert('Warning: unexpected A element '+tag[0]);
              tag_stack.push('');
          }
          break;
//----------------------------------------------------------------
        case 'br':
          bbc_str="\n";
          break;
        case 'hr':
          bbc_str='[hr]';
          break;
        case 'img':
          var s=tag[2].match(/src="([^"]*)"/i)[1];
          var a=tag[2].match(/alt=("[^"]*"|[^"]\S*)/i)[1];
          if(a.charAt(0)=='"') { a=a.substring(1,a.length-1); }
          if(s.search(/\/Templates\/Forum\//)!=-1 &&
             smilies_hash.hasOwnProperty(a)) { // smilies
            bbc_str=smilies_hash[a];
          } else if(a.charAt(0)=='$' && a.charAt(a.length-1)=='$') { // formula
            bbc_str=a;
          } else {
            bbc_str='[img]'+s+'[/img]';
          }
          break;
        default:
//          alert('Warning: unexpected element '+tag[0]);
          tag_stack.push('');
      }
    } // end open tag processing
    return bbc_str+convert_html_to_bbcodes(ht.slice(pos));
  } // end first node processing
}

function get_selection() { 
  if (window.getSelection) {
    userSelection = window.getSelection();
  } else {
    IEselection=document.selection;
  }
}
