/* Global Variables: Set global variables such as images directory */

// Images Directory
wysiwygUrl="/img/";
imagesDir =wysiwygUrl + "icons/";
smileysDir=wysiwygUrl + "smileys/"
cssDir =wysiwygUrl + "styles/";
popupsDir =wysiwygUrl + "popups/";


var ua = navigator.userAgent;
isMSIE = (navigator.appName == "Microsoft Internet Explorer");
isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);
isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
isGecko = ua.indexOf('Gecko') != -1;
isSafari = ua.indexOf('Safari') != -1;
isOpera = ua.indexOf('Opera') != -1;
isMac = ua.indexOf('Mac') != -1;
isNS7 = ua.indexOf('Netscape/7') != -1;
isNS71 = ua.indexOf('Netscape/7.1') != -1;

// Include Style Sheet
document.write('<link rel="stylesheet" type="text/css" href="' +cssDir+ 'styles.css">\n');


/* Toolbar Settings: Set the features and buttons available in the WYSIWYG
  Order of available commands in toolbar one */
var buttonName = new Array();
buttonName[0]  = "seperator";
buttonName[1]  = "bold";
buttonName[2]  = "italic";
buttonName[3]  = "underline";
buttonName[4]  = "strikethrough";
buttonName[5]  = "seperator";
buttonName[8]  = "justifyleft";
buttonName[9]  = "justifycenter";
buttonName[10] = "justifyright";
buttonName[11] = "seperator";
buttonName[12] = "unorderedlist";
buttonName[13] = "orderedlist";
buttonName[16] = "seperator";
buttonName[17] = "undo";
buttonName[18] = "redo";
buttonName[19] = "seperator";
buttonName[20] = "insertimage";
buttonName[21] = "createlink";
buttonName[22] = "seperator";
buttonName[23] = "viewSource";
buttonName[24] = "seperator";

// List of available actions and their respective ID and images
var ToolbarList = {
//Name            buttonID               buttonTitle           buttonImage                        buttonImageRollover
  "bold":         ['Bold',               'Bold',               imagesDir + 'bold.gif',            imagesDir + 'bold_on.gif', '[b]','[/b]', 'Bold: [b]text[/b]', 0],
  "italic":       ['Italic',             'Italic',             imagesDir + 'italics.gif',         imagesDir + 'italics_on.gif', '[i]','[/i]', 'Italic: [i]text[/i]', 0],
  "underline":    ['Underline',          'Underline',          imagesDir + 'underline.gif',       imagesDir + 'underline_on.gif', '[u]','[/u]', 'Underline: [u]text[/u]', 0],
  "strikethrough":['Strikethrough',      'Strikethrough',      imagesDir + 'strikethrough.gif',   imagesDir + 'strikethrough_on.gif', '[s]','[/s]', 'Strike text: [s]text[/s]' ,0],
  "seperator":    ['',                   '',                   imagesDir + 'seperator.gif',       imagesDir + 'seperator.gif'],
  "justifyleft":  ['Justifyleft',        'Justifyleft',        imagesDir + 'justify_left.gif',    imagesDir + 'justify_left_on.gif', '[align=left]','[/align]','set text align to left: [align=left]text[/align]', 0],
  "justifycenter":['Justifycenter',      'Justifycenter',      imagesDir + 'justify_center.gif',  imagesDir + 'justify_center_on.gif','[align=center]','[/align]','set text align to center: [align=center]text[/align]'],
  "justifyright": ['Justifyright',       'Justifyright',       imagesDir + 'justify_right.gif',   imagesDir + 'justify_right_on.gif', '[align=right]','[/align]','set text align to right: [align=right]text[/align]', 0],
  "unorderedlist":['InsertUnorderedList','InsertUnorderedList',imagesDir + 'list_unordered.gif',  imagesDir + 'list_unordered_on.gif', '[list=uord]\n', '[/list]', 0, 0],
  "orderedlist":  ['InsertOrderedList',  'InsertOrderedList',  imagesDir + 'list_ordered.gif',    imagesDir + 'list_ordered_on.gif', '[list=ord]\n', '[/list]', 0, 0],
  "undo":         ['Undo',               'Undo',               imagesDir + 'undo.gif',            imagesDir + 'undo_on.gif', '', '', 0, 0],
  "redo":         ['Redo',               'Redo',               imagesDir + 'redo.gif',            imagesDir + 'redo_on.gif', '', '', 0, 0],
  "insertimage":  ['InsertImage',        'InsertImage',        imagesDir + 'insert_picture.gif',  imagesDir + 'insert_picture_on.gif', '[img]','[/img]','"Insert Image: [img | =left | =right]http://image path[/img]"', 0],
  "createlink":   ['CreateLink',         'CreateLink',         imagesDir + 'insert_hyperlink.gif',imagesDir + 'insert_hyperlink_on.gif', '[url]','[/url]','Insert URL: [url]http://hvmdesign.com[/url] or [url=http://hvmdesign.com]High Velocity Media[/url]', 0],
  "viewSource":   ['ViewSource',         'ViewSource',         imagesDir + 'view_source.gif',     imagesDir + 'view_source_on.gif', '', '', 0, 0],
  "viewText":     ['ViewText',           'ViewText',           imagesDir + 'view_text.gif',       imagesDir + 'view_text_on.gif', '', '', 0, 0]
};

var smileys=Array();
smileys=[
['[sm:01]','Yellow_Flash_Colorz_PDT_01.gif'],
['[sm:02]','Yellow_Flash_Colorz_PDT_02.gif'],
['[sm:03]','Yellow_Flash_Colorz_PDT_03.gif'],
['[sm:04]','Yellow_Flash_Colorz_PDT_04.gif'],
['[sm:08]','Yellow_Flash_Colorz_PDT_08.gif'],
['[sm:09]','Yellow_Flash_Colorz_PDT_09.gif'],
['[sm:10]','Yellow_Flash_Colorz_PDT_10.gif'],
['[sm:11]','Yellow_Flash_Colorz_PDT_11.gif'],
['[sm:12]','Yellow_Flash_Colorz_PDT_12.gif'],
['[sm:13]','Yellow_Flash_Colorz_PDT_13.gif'],
['[sm:14]','Yellow_Flash_Colorz_PDT_14.gif'],
['[sm:15]','Yellow_Flash_Colorz_PDT_15.gif'],
['[sm:16]','Yellow_Flash_Colorz_PDT_16.gif'],
['[sm:17]','Yellow_Flash_Colorz_PDT_17.gif'],
['[sm:18]','Yellow_Flash_Colorz_PDT_18.gif'],
['[sm:19]','Yellow_Flash_Colorz_PDT_19.gif']
];

/*
[':=D','Yellow_Flash_Colorz_PDT_01.gif'],
['^-^','Yellow_Flash_Colorz_PDT_02.gif'],
[';=D','Yellow_Flash_Colorz_PDT_03.gif'],
['|=D','Yellow_Flash_Colorz_PDT_04.gif'],
[';=P','Yellow_Flash_Colorz_PDT_08.gif'],
[':=P','Yellow_Flash_Colorz_PDT_09.gif'],
[':=0','Yellow_Flash_Colorz_PDT_10.gif'],
['8=)','Yellow_Flash_Colorz_PDT_11.gif'],
['==)','Yellow_Flash_Colorz_PDT_12.gif'],
[':(','Yellow_Flash_Colorz_PDT_13.gif'],
[':=?','Yellow_Flash_Colorz_PDT_14.gif'],
[':-)','Yellow_Flash_Colorz_PDT_15.gif'],
[':-D','Yellow_Flash_Colorz_PDT_16.gif'],
[':hmm:','Yellow_Flash_Colorz_PDT_17.gif'],
[';=)','Yellow_Flash_Colorz_PDT_18.gif'],
[';-)','Yellow_Flash_Colorz_PDT_19.gif']
*/

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
  HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode){
  switch (where){
  case 'beforeBegin':
      this.parentNode.insertBefore(parsedNode,this)
  break;
  case 'afterBegin':
      this.insertBefore(parsedNode,this.firstChild);
  break;
  case 'beforeEnd':
      this.appendChild(parsedNode);
  break;
  case 'afterEnd':
      if (this.nextSibling) 
        this.parentNode.insertBefore(parsedNode,this.nextSibling);
      else this.parentNode.appendChild(parsedNode);
  break;
  }
  }

  HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr){
  var r = this.ownerDocument.createRange();
  r.setStartBefore(this);
  var parsedHTML = r.createContextualFragment(htmlStr);
  this.insertAdjacentElement(where,parsedHTML)
  }


  HTMLElement.prototype.insertAdjacentText = function(where,txtStr){
  var parsedText = document.createTextNode(txtStr)
  this.insertAdjacentElement(where,parsedText)
  }
};

/* Create viewTextMode global variable and set to 0
   enabling all toolbar commands while in HTML mode */

viewTextMode = 0;

function generate_wysiwyg(textareaID, smil, w, h) {
wysiwygWidth  = w;
wysiwygHeight = h;

// Hide the textarea 
$(textareaID).style.display = 'none'; 
    
// Pass the textareaID to the "n" variable.
var n = textareaID;
    
/* Toolbars width is 2 pixels wider than the wysiwygs
   toolbarWidth = parseFloat(wysiwygWidth) + 2; */
toolbarWidth = parseFloat(wysiwygWidth) ;

// Generate WYSIWYG toolbar one
var toolbar;
toolbar = '<table cellpadding="0" cellspacing="0" border="0" class="toolbar1" style="width:'+ toolbarWidth +'px;"><tr><td style="width: 6px;"><img src="'+ imagesDir +'seperator2.gif" alt="" hspace="3"></td>';
  
// Output all command buttons that belong to toolbar one
for (var i = 0; i <= buttonName.length;) {
    if (buttonName[i]) {
        var buttonObj           = ToolbarList[buttonName[i]];
        var buttonID            = buttonObj[0];
        var buttonTitle         = buttonObj[1];
        var buttonImage         = buttonObj[2];
        var buttonImageRollover = buttonObj[3];
        
        if (buttonName[i] == "seperator"){
            toolbar += '<td style="width: 12px;" align="center"><img src="'+ buttonImage +'" border="0" unselectable="on" width="2" height="18" hspace="2" unselectable="on"></td>';
        } else if (buttonName[i] == "viewSource"){
            toolbar += '<td style="width: 22px;">';
            toolbar += '<span id="HTMLMode'+ n +'"><img src="'+ buttonImage +'" border="0" unselectable="on" title="'+ buttonTitle +'" id="' +buttonID+ '" class="button" onClick="formatText(this.id,\''+ n +'\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\''+ buttonImageRollover +'\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\''+ buttonImage +'\';" unselectable="on"  width="20" height="20"></span>';
            toolbar += '<span id="textMode'+ n +'"><img src="'+ imagesDir +'view_text.gif" border="0" unselectable="on" title="viewText" id="ViewText" class="button" onClick="formatText(this.id,\''+ n +'\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\''+ imagesDir +'view_text_on.gif\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\''+ imagesDir +'view_text.gif\';" unselectable="on" width="20" height="20"></span>';
            toolbar += '</td>';
        } else {
            toolbar += '<td style="width: 22px;"><img src="'+ buttonImage +'" border="0" unselectable="on" title="'+ buttonTitle +'" id="'+ buttonID +'" class="button" onClick="formatText(this.id,\''+ n +'\');" onmouseover="if(className==\'button\'){className=\'buttonOver\'}; this.src=\''+ buttonImageRollover +'\';" onmouseout="if(className==\'buttonOver\'){className=\'button\'}; this.src=\''+ buttonImage +'\';" unselectable="on" width="20" height="20"></td>';
        }
    }
    i++;
}

toolbar += '<td>&nbsp;</td></tr></table>';  

/* Create iframe which will be used for rich text editing */
wysiwygWidth=wysiwygWidth-2;
wysiwygHeight=wysiwygHeight-2;
var iframe = '<iframe frameborder="0" id="wysiwyg'+ n +'" style="width:'+ wysiwygWidth +'px; height:'+ wysiwygHeight +'px;border: 1px inset #CCC;margin:1px 0 0 0;" src="/img/blank.htm"></iframe>\n';

//alert('wysiwyg'+ n);

// Insert after the textArea both toolbar one and two
$(n).insertAdjacentHTML("beforeBegin", toolbar + iframe);
$(n).style.border='1px inset #CCC';
$(n).style.marginTop='1px';

if(navigator.appName=='Microsoft Internet Explorer'){
    $(n).style.marginTop='0px';
}
var smilebar='';

//Insert Smileys
for (var i = 0; i < smileys.length;i++) { 
    smilebar+='<div class="smile" onClick="emoticon(\''+ n +'\',\''+ i +'\')"><img src=\''+ smileysDir + smileys[i][1] + '\'></div>';
}

$(smil).innerHTML = smilebar;

// Hide the "Text Mode" button
$("textMode" + n).style.display = 'none'; 
    
// Give the iframe the global wysiwyg height and width
$("wysiwyg" + n).style.height = wysiwygHeight + "px";
$("wysiwyg" + n).style.width = wysiwygWidth + "px";
    
// Pass the textarea's existing text over to the content variable
var content = $(n).value;
var doc = $("wysiwyg" + n).contentWindow.document;

function idoc(IFrame){
    if (typeof(IFrame) != "object") { var IFrame = document.createElement("iframe"); }
    var doc;
    if(IFrame.contentDocument)
        // For NS6
        doc = IFrame.contentDocument;// alert('FF');
    else if( IFrame.contentWindow ) 
        // For IE5.5 and IE6
        doc = IFrame.contentWindow.document;
    else if( IFrame.document )
        // For IE5
        doc = IFrame.document;
    else //other browser
      //  doc = IFrame.document;
    return doc;
}

//var doc = idoc($("wysiwyg" + n));

// Make the iframe editable in both Mozilla and IE
//doc.body.contentEditable = true;
if(navigator.appName=='Netscape'){ // ага, значит Мозилка
content='<html><head><title>Reply</title><link rel="stylesheet" type="text/css" href="/img/styles/wstyle.css" /></head><body> </body></html>';    
  //doc.execCommand("useCSS",false,true) // аргумент - третий в списке (true)!
doc.open();
doc.write(content);
doc.close();

  doc.designMode = "on";
 // doc.body.contentEditable = true;
} else {
content='<html><head><title>Reply</title><link rel="stylesheet" type="text/css" href="/img/styles/wstyle.css" /></head><body> </body></html>';    
//doc.innerHTML=content;
doc.open();
doc.write(content);
doc.close();
doc.designMode = "on";
}



  
// Update the textarea with content in WYSIWYG when user submits form
var browserName = navigator.appName;
if (browserName == "Microsoft Internet Explorer"){
    for (var idx=0; idx < document.forms.length; idx++){
        document.forms[idx].attachEvent('onsubmit', function() { updateTextArea(n); });
    }
} else {
    for (var idx=0; idx < document.forms.length; idx++){
        document.forms[idx].addEventListener('submit',function OnSumbmit() { updateTextArea(n); }, true);
    }
}

};

function emoticon(n,icon) {
    text=smileys[icon][0];
    var txtarea = $(n);
    if(txtarea.style.display != 'none'){
        text = ' '+ text +' ';
        if (txtarea.createTextRange && txtarea.caretPos){
            if (baseHeight != txtarea.caretPos.boundingHeight){
                txtarea.focus();
                storeCaret(txtarea);
            }
            var caretPos = txtarea.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text+ text +' ' : caretPos.text + text;
            txtarea.focus();
        } else
        if (txtarea.selectionEnd && (txtarea.selectionStart | txtarea.selectionStart == 0)){ 
            mozWrap(txtarea, text, "");
            return;
        } else {
            txtarea.value += text;
            txtarea.focus();
        }
    } else {
        wysiwyg_image_insert(smileysDir + smileys[icon][1],n);
    }
}

/*
  Function   : formatText()
  Description: replace textarea with wysiwyg editor
  Usage      : formatText(id, n, selected);
  Arguments  : id - The execCommand (e.g. Bold)
               n  - The editor identifier that the command affects (the textarea's ID)
               selected - The selected value when applicable (e.g. Arial) */
function formatText(id, n, selected) {
    // When user clicks toolbar button make sure it always targets its respective WYSIWYG
    $("wysiwyg" + n).contentWindow.focus();
    
    // When in Text Mode these execCommands are disabled
    var formatIDs = new Array("FontSize","FontName","Bold","Italic","Underline","Subscript","Superscript","Strikethrough","Justifyleft","Justifyright","Justifycenter","InsertUnorderedList","InsertOrderedList","Indent","Outdent","ForeColor","BackColor","InsertImage","InsertTable","CreateLink");
  
    // Check if button clicked is in disabled list
    for (var i = 0; i <= formatIDs.length;){
        if (formatIDs[i] == id) {
             var disabled_id = 1; 
        }
        i++;
    }
    
    // Check if in Text Mode and disabled button was clicked
    if (viewTextMode == 1 && disabled_id == 1) {
    for (var i = 0; i <= buttonName.length;) { 
        if (buttonName[i]) {
            var buttonObj = ToolbarList[buttonName[i]];
            var buttonID  = buttonObj[0];
            if(buttonID==id){
                var buttonTitle = buttonObj[1];
                var buttonImage = buttonObj[2];
                var buttonImageRollover = buttonObj[3];
                var lbr = buttonObj[4];
                var rbr = buttonObj[5];
                var hlp = buttonObj[6];
                var flag = buttonObj[7];

                //BBCODE ACTION
                var txtarea = $(n);
                if ((clientVer >= 4) && is_ie && is_win) {
                    theSelection = document.selection.createRange().text;
                    if (theSelection != '') {
                        document.selection.createRange().text = lbr + theSelection + rbr;
                        $(n).focus();
                        return;
                    }
                } else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
                    mozWrap(txtarea, lbr,  rbr);
                    return;
                }
                if (flag == 0) {
                    ToAdd = lbr;
                    ToolbarList[buttonName[i]][7]=1;
                    $(id).style.border='1px solid #CCC';
                    $(id).style.margin='0px';
                } else {
                    ToAdd = rbr;
                    ToolbarList[buttonName[i]][7]=0;
                    $(id).style.border='';
                    $(id).style.margin='';
                }
                PostWrite(ToAdd, n);
            }
        }
        i++;
    }
    } else {
        // InsertImage
        if (id == "InsertImage") {
            window.open(popupsDir + 'insert_image.html?wysiwyg=' + n,'_blank','location=0,status=0,scrollbars=0,resizable=0,width=400,height=300');
        } else if (id == "CreateLink") {
            // CreateLink
            window.open(popupsDir + 'insert_hyperlink.html?wysiwyg=' + n,'_blank','location=0,status=0,scrollbars=0,resizable=0,width=300,height=110');
        } else if (id == "ViewSource") {
            // ViewSource
            viewSource(n);
        } else if (id == "ViewText") {
            // ViewText
            viewText(n);
        } else {
            // Every other command
            $("wysiwyg" + n).contentWindow.document.execCommand(id, false, null);
            betterformat(n);
        }
    }
};

/*
   Trying to format text in better style
*/
function betterformat(n){
    var getDocument = $("wysiwyg" + n).contentWindow.document;
    var browserName = navigator.appName;
    
    var iHTML = getDocument.body.innerHTML;
    //Mozilla
    iHTML=iHTML.replace(/<span style="font-weight: bold;">([^=]*)<\/span>/g,'<b>$1</b>');
    iHTML=iHTML.replace(/<span style="font-style: italic;">([^=]*)<\/span>/g,'<i>$1</i>');
    iHTML=iHTML.replace(/<span style="text-decoration: underline;">([^=]*)<\/span>/g,'<u>$1</u>');
    iHTML=iHTML.replace(/<div style="text-align: ([^=]*);">([^=]*)<\/div>/g,'<p align=$1>$2</p>');
    iHTML=iHTML.replace(/<p style="text-align: ([^=]*);">([^=]*)<\/p>/g,'<p align=$1>$2</p>');
    
    //IE
    iHTML=iHTML.replace(/<(\/?)(EM|em)>/g,'<$1i>');
    iHTML=iHTML.replace(/<(\/?)(STRONG|strong)>/g,'<$1b>');
    //Opera
    iHTML=iHTML.replace(/<(?:DIV|div) align="([^=]*)">([^=]*)<\/(?:DIV|div)>/g,'<p align=$1>$2</p>');
    //iHTML=iHTML.replace(/<(\/?)(U|u)>/g,'<$1$2>');
    getDocument.body.innerHTML=iHTML;
}

/*
  Function    : wysiwyg_image_insert(image_url,n)
  Description : insert image into WYSIWYG in rich text
  Usage       : insertHTML('http://localhost/test.gif', "textareaID")
  Arguments   : html - The image being inserted (e.g. <img src='http://djko.com.ua/test.gif'>)
                n  - The editor identifier that the HTML will be inserted into (the textarea's ID)
*/

function wysiwyg_image_insert(image_url,n){
    if(!image_url) return
    try {
        $("wysiwyg" + n).contentWindow.document.execCommand("InsertImage", false, image_url);
    } catch(ex){
        alert(ex);
    }
    $("wysiwyg" + n).contentWindow.focus();
}

/*
  Function    : viewSource()
  Description : Shows the HTML source code generated by the WYSIWYG editor
  Usage       : showFonts(n)
  Arguments   : n   - The editor identifier (the textarea's ID)
*/

function viewSource(n) {
    // Hide the HTML Mode button and show the Text Mode button
    var wysiwyg=$("wysiwyg" + n);
    var textarea=$(n);
    textarea.style.display = '';       
    wysiwyg.style.display = 'none';
    html_editor_iframe2textarea(n);
    textarea.focus()
  
    $('HTMLMode' + n).style.display = 'none'; 
    $('textMode' + n).style.display = 'block';
    
    // set the font values for displaying HTML source
    // getDocument.body.style.fontSize = "12px";
    // getDocument.body.style.fontFamily = "Courier New"; 
    
  viewTextMode = 1;

};

//BEGIN реализация для нескольких визивигов на одной страничке
var wysiwyg_buffer=[]
function buffer2wysiwyg(n){
    try{
        $(n).contentWindow.document.body.innerHTML=wysiwyg_buffer[n];
    } catch(e) {
        setTimeout("buffer2wysiwyg('"+n+"')",0);
    }
}

function wysiwyg_settext(n, text){
    wysiwyg_buffer[n]=text;
    buffer2wysiwyg(n);
}
//END реализация для нескольких вусивигов на одной страничке

//перекючение из текска в висивиг
function html_editor_textarea2iframe(n){
    var wysiwyg=$("wysiwyg" + n);
    var textarea=$(n);
    if(wysiwyg.offsetWidth){ // wysiwyg is visible now
        wysiwyg.contentWindow.document.designMode='On';
        if(navigator.appName=='Netscape' || navigator.appName=='Opera'){
            wysiwyg.contentWindow.document.execCommand("useCSS",false,true);
        }
    }
    wysiwyg_settext(wysiwyg.id,bbcode2html(textarea.value));
}

// перекючение из висивиг в текст 
function html_editor_iframe2textarea(n){
    var wysiwyg=$("wysiwyg" + n);
    var textarea=$(n);
    s=wysiwyg.contentWindow.document.body.innerHTML;
    textarea.value= html2bbcode(s);
}

// функция на переключение редактора из одного режима в другой
function wysiwyg_switch_mode(n){
    var wysiwyg=$("wysiwyg" + n);
    var textarea=$(n);
    if(textarea.offsetWidth){
        wysiwyg.style.display = '';
        textarea.style.display = 'none';
        html_editor_textarea2iframe(name);      
        wysiwyg.focus();
    } else { // Редактор в визуальном режиме
        textarea.style.display = '';
        wysiwyg.style.display = 'none';
        html_editor_iframe2textarea(name);
        textarea.focus();
    }
}


function rplc(fnd,rpl,str){
    var result='';
    var spl=str.split(fnd);
    for (i=0;i<spl.length ;i++) {
        result+=spl[i];
        if(i<spl.length-1) result+=rpl;
    }
    return result;
}

//regular expressions for bbcode
function html2bbcode(text){
    s=text;
    s=s.replace(/<(?:div|DIV) class="?qu"?\/?>([\w\W]*?)<(?:br|BR\/?)>([\w\W]*?)<\/(?:div|DIV)>/gi,'[qu:$1]$2[/qu]');
    s=s.replace(/<(?:br|BR\/?)>/g,'\n');
    s=s.replace(/<[pP] align="?(\w+)"?>([\w\W]*)<\/[pP]>/g,'[align=$1]$2[/align]');
    s=s.replace(/<(?:img|IMG) src="([\w:\/\.]+)"\/?>/g,'[img]$1[/img]');
    s=s.replace(/<(\/?)([bB]|[uU]|(h1|H1)|(h2|H2)|[iI]|EM)>/g,'[$1$2]');
    s=s.replace(/<(?:a|A) href="([^=]*)">([^=]*)<\/(?:a|A)>/g,'[url=$1]$2[/url]');  //gut
    s=s.replace(/<(?:img|IMG) src=([\w"']+)>/g,'[/a]');
    s=s.replace(/<\/?[Pp]>/g,'');
    s=s.replace(/&nbsp;/g,' ');
    s=s.replace(/<(\/?)(?:strike|STRIKE)>/g,'[$1s]');
    s=s.replace(/<\/li>([^(li)]*)<li>\n?/gi,'\n');
    s=s.replace(/<ol>[^<]*<li>/gi,'[list=ord]\n');
    s=s.replace(/<ul>[^<]*<li>/gi,'[list=uord]\n');
    s=s.replace(/<\/li>(?:<\/ul>|<\/ol>)/gi,'\n[/list]');
    for (var i = 0; i < smileys.length;i++) { 
        s=rplc('[img]'+smileysDir+smileys[i][1]+'[/img]',smileys[i][0],s);
        s=rplc('[img]'+wysiwygUrl+smileysDir+smileys[i][1]+'[/img]',smileys[i][0],s);
    }

    s=s.replace(/<[\w\W]*>/g,'');
    return s;
}

function bbcode2html(text){
    s=text;
    s=s.replace(/\[qu:([^=]*?)\]([^=]*?)\[\/qu\]/gi,'<div class="qu">$1<br>$2</div>');  //gut
    for (var i = 0; i < smileys.length;i++) { 
        s=rplc(smileys[i][0],'[img]'+smileysDir+smileys[i][1]+'[/img]',s);
        s=rplc(smileys[i][0],'[img]'+wysiwygUrl+smileysDir+smileys[i][1]+'[/img]',s);
    }
    do {
        s=s.replace(/\[list=ord\]([^=]*)\n([^\n]*)\n([^=]*)\[\/list\]/gm,'[list=ord]$1\n<li>$2</li>$3[/list]');
    } while(s.search(/\[list=ord\]([^=]*)\n([^\n]*)\n([^=]*)\[\/list\]/)!=-1)
    s=s.replace(/\[list=ord\]\n?([^=]*)\[\/list\]/g,'<ol>$1</ol>');
    do {
        s=s.replace(/\[list=uord\]([\W\w]*)\n([^\n]*)\n([\W\w]*)\[\/list\]/gi,'[list=uord]$1\n<li>$2</li>$3[/list]');
    } while(s.search(/\[list=uord\]([^=]*)\n([^\n]*)\n([^=]*)\[\/list\]/i)!=-1)
    s=s.replace(/\[list=uord\]\n?([\W\w]*)\[\/list\]/g,'<ul>$1</ul>');
    s=s.replace(/\n/g,'<br>');
    s=s.replace(/  /g,'&nbsp; ');
    s=s.replace(/\[(\/?)([bB]|[uU]|(h1|H1)|(h2|H2)|[iI]|EM)\]/g,'<$1$2>');
    s=s.replace(/\[(\/?)s\]/g,'<$1strike>');
    s=s.replace(/\[img\]([\w:\/\.]+)\[\/img\]/g,'<img src="$1"/>');
    s=s.replace(/\[align=(\w+)\]([\w\W]*)\[\/align\]/g,'<p align="$1">$2</p>');
    s=s.replace(/\[url=([^=]*)\]([^=]*)\[\/url\]/g,'<a href="$1">$2</a>');  //gut

    return s;
}


/*
  Function   :viewSource()
  Description:Shows the HTML source code generated by the WYSIWYG editor
  Usage      :showFonts(n)
  Arguments  :n - The editor identifier (the textarea's ID)
*/
function viewText(n) { 
    var wysiwyg=$("wysiwyg" + n);
    var textarea=$(n);
        wysiwyg.style.display = '';
        textarea.style.display = 'none';
        html_editor_textarea2iframe(n);     
        wysiwyg.focus()

    // Hide the Text Mode button and show the HTML Mode button
    $('textMode' + n).style.display = 'none'; 
    $('HTMLMode' + n).style.display = 'block';
    viewTextMode = 0;
};

/*
  Function   :updateTextArea()
  Description:Updates the text area value with the HTML source of the WYSIWYG
  Usage      :updateTextArea(n)
  Arguments  :n   - The editor identifier (the textarea's ID)
*/
function updateTextArea(n) {
    viewSource(n); $(n).value = $("textarea" + n).contentWindow.document.body.innerHTML;
};

//+++++++++++++++++++++++++++++++++++++++++++++++++++++
var theSelection = false;

var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
             && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
             && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;
var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

function PostWrite(text, n) {
    if ($(n).createTextRange && $(n).caretPos) {
        var caretPos = $(n).caretPos;
        caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
    } else $(n).value += text;
    $(n).focus(caretPos);
}
function mozWrap(txtarea, open, close){
    var selLength = txtarea.textLength;
    var selStart = txtarea.selectionStart;
    var selEnd = txtarea.selectionEnd;
    if (selEnd == 1 || selEnd == 2) selEnd = selLength;

    var s1 = (txtarea.value).substring(0,selStart);
    var s2 = (txtarea.value).substring(selStart, selEnd)
    var s3 = (txtarea.value).substring(selEnd, selLength);
    txtarea.value = s1 + open + s2 + close + s3;
    return;
}

function autoResetDesignMode() {
        // Add fix for tab/style.display none/block problems in Gecko
        if (!isMSIE) eval('try { doc.designMode = "On"; } catch(e) {}');
}

autoResetDesignMode();
