var srcSave;
var saveSelectionVal;

function saveSelection(src)
{
    srcSave=src;
    var selection=new Selection(src)
    saveSelectionVal=selection.getCaret();
}

function restoreSelection()
{
    var selection=new Selection(srcSave)
    selection.setCaret(saveSelectionVal.start,saveSelectionVal.end);
}

function drawIcon(left,ttop,width,id,title,command)
{
    atop=0;
    btop=-ttop-44;
   document.write("<td><div style=\"width:"+width+"px;height:22px;\">");
   document.write("<span unselectable='on' style=\"position:absolute;clip: rect(0px "+width+"px 22px 0px)\">");
   document.write("<img unselectable='on' id=\""+id+"\" ");
   document.write("title=\""+title+"\" onclick=\""+command+"\" src=\""+imgpath+"ace.gif\" ");
   document.write("style=\"position:absolute;top:-"+ttop+"px;left:-"+left+"px;\" ");
   //document.write("onmouseover=\"if(this.en==false)return;alert(atop);this.style.pixelTop='"+atop+"px;'\" ");
   //document.write("onmousedown=\"if(this.en==false)return;this.style.pixelTop='"+btop+"px;'\" ");
   //document.write("onmouseup=\"if(this.en==false)return;this.style.pixelTop='"+atop+"px;'\" ");
   //document.write("onmouseout=\"if(this.en==false)return;this.style.pixelTop='-"+ttop+"px;'\" ");
   document.write("GALLERYIMG=\"no\" ");
   document.write(">");
   document.write("<table width="+width+"><tr><td unselectable='on' onselectstart='return false' style=\"position:absolute;top:4px;left:7px;\" id=\""+id+"Text\"></td></tr></table>");
   document.write("</span>");
   document.write("</div></td>");
}

opentags=new Array();
bbstarttags = new Array('[b]', '[i]', '[u]', '[quote]', '[code]', '[list=%]','[img]',  '[url=%]','[color=%]','[size=%]','[name=%]','[list]' );
bbendtags=    new Array('[/b]','[/i]','[/u]','[/quote]','[/code]','[/list]', '[/img]', '[/url]', '[/color]', '[/size]', '[/name]' ,'[/list]');

function wrapAroundText(txtarea,starttag,endtag,mode)
{
    var selection=new Selection(txtarea);
    var selectedText=selection.getText();
    var curpos=selection.getCaret();
    var newtext=starttag+selectedText+endtag;
    selection.setText(newtext);
    // update caret/selection  - no selection
    var length=0;
    if(selectedText.length==0)
        {
        if(mode==1)
            length=starttag.length;
        else
            length=newtext.length;
        selection.setCaret(curpos.start+length,curpos.start+length);
        }
    // selected text
    else
        {
        length=newtext.length;
        selection.setCaret(curpos.start,curpos.end+length);
        }
}

function bbsimplestyle(bbnumber,src)
{
    src.focus();
    wrapAroundText(src,bbstarttags[bbnumber],bbendtags[bbnumber],1);
}

function bbsettingstyle(bbnumber,setting)
{
    popupHide()

    starttag=bbstarttags[bbnumber];
    starttag=starttag.replace('%',setting);
    srcSave.focus();
    restoreSelection();
    wrapAroundText(srcSave,starttag,bbendtags[bbnumber],1);
/*
    selectedText = document.selection.createRange().text;
    if (selectedText)
        {
        // Add tags around our selection
        document.selection.createRange().text=starttag+selectedText+bbendtags[bbnumber];
        srcSave.focus();
        selectedText='';
        return;
        }
    var add=starttag+bbendtags[bbnumber];
    srcSave.value+=add;
    updateCaretPosition(srcSave,add.length);
*/
}

function bblist(bbnumber,setting,src)
{
    var listitems=new Array();
    while(true)
        {
        var item=prompt("Enter in a list item.  Enter in a blank item or press cancel when you are done",'');
        if(item==null || item.length==0)
            {
            break;
            }
        else
            listitems.push(item);
        }
    if(listitems.length>0)
        {
        src.focus();
        var add=bbstarttags[bbnumber].replace('%',setting)+'\n';
        for(i=0;i<listitems.length;i++)
            {
            var item=listitems[i];
            add+='[*]'+item+'\n';
            }
        add+=bbendtags[bbnumber]+'\n';
        src.value+=add;
        updateCaretPosition(src,add.length);
        }
}

function updateCaretPosition(src,length)
{
    var selection=new Selection(src);
    src.focus();
    var pos=selection.getCaret().start+length;
    selection.setCaret(pos,pos);
}


function bblink(src)
{
    var bburl=prompt("Enter in the URL for this link","http://");
    if(bburl==null)
        {
        alert("You must enter a URL");
        return;
        }
    var vtext=prompt("Enter in the text you wish to have show up in the link","");
    if(vtext==null)
        {
        alert("You must enter text for the link");
        return;
        }
    starttag=bbstarttags[7];
    starttag=starttag.replace(/%/,bburl);
    var insert=starttag+vtext+bbendtags[7];
    src.value+=insert;
    updateCaretPosition(src,insert.length);
}

function bbimg(src)
{
    var url=prompt("Enter in the URL for this image","http://");
    if(url==null)
        {
        alert("You must enter the URL for the image");
        return;
        }
    var insert=bbstarttags[6]+url+bbendtags[6];
    src.value+=insert;
    updateCaretPosition(src,insert.length);
}

function doCmd(sCmd,src,sOption)
{
   popupHide()
   src.focus()

   var oSel = src.document.selection.createRange()
   var sType = src.document.selection.type
   var oTarget = (sType == "None" ? src.document : oSel)
   oSel.select()

   if(sCmd=="DialogImage")
      {
        ezw(imgedurl);
        srcSave=src;
      return true;
      }
   oTarget.execCommand(sCmd,false,sOption)
}
function ezw(url)
{
    var popleft=((document.body.clientWidth - 440) / 2)+window.screenLeft;
    var poptop=(((document.body.clientHeight - 460) / 2))+window.screenTop-40;
    window.open(url,"AAAA","scrollbars=YES,width=480,height=520,left="+popleft+",top="+poptop)
}

function popupShow(width,title,html)
{
   popupHide();
   var sHTML = "<link rel=\"stylesheet\" href=\""+imgpath+"ace.css\" type=\"text/css\">" +
      "<style>" +
      "  select{height: 22px; top:2px;   font:8pt verdana,arial,sans-serif}" +
      "  body {border: 0px lightgrey solid;width:100%}" +
      "  .bar{ border-top: #99ccff 1px solid; background: #316AC5; WIDTH: 100%; border-bottom: #000000 1px solid;height: 20px}" +
      "  .cellSymbol{border:solid black 1.0pt; border-left:none; padding:0in 2pt 0in 2pt; font-size:10pt; font-family:'Tahoma';}" +
      "  td {  font:8pt verdana,arial,sans-serif}" +
      "  div   {  font:10pt tahoma,arial,sans-serif}" +
      "</style>" +
      "<body style=\"overflow:hidden\" oncontextmenu=\"return false\" topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0 ONSELECTSTART=\"return event.srcElement.tagName=='INPUT'\">" +
      "<table border=\"0\" cellpadding=\"0\" width=\"100%\" cellspacing=\"0\" style=\"table-layout: fixed\" bgcolor=Gainsboro ID=\"tblPopup\">" +
      "<col width="+width+"><col width=13>" +
      "<tr><td>" +
      "  <div class=\"bar\" style=\"padding-left: 5px;\">" +
      "  <font size=2 face=tahoma color=white><b>"+title+"</b></font>" +
      "  </div>" +
      "</td>" +
      "<td onclick=\"parent.popupHide()\">" +
      "  <div class=\"bar\">" +
      "  <font size=2 face=tahoma color=white><b>X</b></font>" +
      "  </div>" +
      "</td>" +
      "</tr>" +
      "<tr>" +
      "<td colspan=2 style=\"border-left: #336699 1px solid;border-right: #336699 1px solid;border-bottom: #336699 1px solid;\" valign=top>" +
      "  <br>" +
      "  <div id=\"divPopup\" align=center>"+html+"</div>" +
      "  <br>" +
      "</td>" +
      "</tr>" +
      "</table>" +
      "</body>"
     try
       {
       idContentTmp=document.idContentTmp;
       idContentTmp.document.open("text/html","replace")
       idContentTmp.document.write(sHTML)
       idContentTmp.document.close()
       }
     catch(e)
       {
       idContentTmp=document.getElementById("idContentTmp").contentDocument;
       idContentTmp.open("text/html","replace")
       idContentTmp.write(sHTML)
       idContentTmp.close()
       var x=document.getElementById("idContentTmp").contentDocument;
       window.setTimeout("mozPopup()",100)
       return;
       }

   document.getElementById("idContentTmp").style.zIndex = 2
   document.getElementById("idContentTmp").style.visibility = ""

   idContentTmp.document.all.tblPopup.focus()

   document.getElementById("idContentTmp").style.width = idContentTmp.document.getElementById("tblPopup").offsetWidth+"px"
   document.getElementById("idContentTmp").style.height = idContentTmp.document.getElementById("tblPopup").offsetHeight+"px"
   if(document.body.clientWidth - document.getElementById("idContentTmp").offsetWidth > 0)
      document.getElementById("idContentTmp").style.pixelLeft=((document.body.clientWidth - document.getElementById("idContentTmp").offsetWidth) / 2);
   else
      document.getElementById("idContentTmp").style.pixelLeft=0;


}

function mozPopup()
{
    var idContentTmp=document.getElementById("idContentTmp");
    var x=document.getElementById("idContentTmp").contentDocument;
    x=x.getElementById("tblPopup");
    idContentTmp.style.zIndex = 2
    idContentTmp.style.visibility = ""

    idContentTmp.style.width=x.offsetWidth
    idContentTmp.style.height=x.offsetHeight
    if(document.body.clientWidth - idContentTmp.offsetWidth > 0)
       idContentTmp.style.pixelLeft=(document.body.clientWidth - idContentTmp.offsetWidth) / 2 ;
    else
       idContentTmp.style.pixelLeft=0
}

function popupHide()
{
   document.getElementById("idContentTmp").style.visibility = "hidden"
}

// firefox getelementbyid
function displayFontNameBox(src)
{
   saveSelection(src)
    var c1 = new Array("Arial","Arial Black","Arial Narrow","Comic Sans MS",
        "Courier New","System","Tahoma","Times New Roman","Verdana","Wingdings")
   var sHTML = "<table align=center border=0 width=100% height=100% cellpadding=0 cellspacing=2>";
    for (i=0;i<c1.length;i++)
        {
        sHTML+="<tr onclick=\"parent.bbsettingstyle(10,'"+c1[i]+"');\" onmouseover=\"this.style.color='tomato'\" onmouseout=\"this.style.color='black'\"><td align=center><font face=\""+c1[i]+"\" size=1>"+c1[i]+"</font></td></tr>"
        }
   sHTML+="</table>";
   popupShow(213,"Font Name",sHTML)
}
function displayFontSizeBox(src)
{
   saveSelection(src)
   var sHTML = "<table align=center border=0 width=100% height=100% cellpadding=0 cellspacing=0>"
    for(i=1;i<8;i++)
    {
    sHTML+="<tr onclick=\"parent.bbsettingstyle(9,"+i+");\" onmouseover=\"this.style.color='tomato'\" onmouseout=\"this.style.color='black'\"><td align=center><font size="+i+">Size&nbsp;"+i+"</font></td></tr>"
    }
   sHTML+="</table>"
   popupShow(253,"Font Size",sHTML)
}
function displayFgColorBox(src)
{
   saveSelection(src)
   var sHTML = writeColorPicker("idForeColor","parent.bbsettingstyle(8,idForeColor.value);",0);
   popupShow(433,"Foreground Color",sHTML)
}
function writeColorPicker(Name,Command,Type)
{
var OutputID = Name
var TextID = Name + "_1"
var ColorID = Name + "_2"
var c1 = new Array("FFFFCC","FFCC66","FF9900","FFCC99","FF6633","FFCCCC","CC9999","FF6699","FF99CC","FF66CC","FFCCFF","CC99CC","CC66FF","CC99FF","9966CC","CCCCFF","9999CC","3333FF","6699FF","0066FF","99CCFF","66CCFF","99CCCC","CCFFFF","99FFCC","66CC99","66FF99","99FF99","CCFFCC","33FF33","66FF00","CCFF99","99FF00","CCFF66","CCCC66","FFFFFF")
var c2 = new Array("FFFF99","FFCC00","FF9933","FF9966","CC3300","FF9999","CC6666","FF3366","FF3399","FF00CC","FF99FF","CC66CC","CC33FF","9933CC","9966FF","9999FF","6666FF","3300FF","3366FF","0066CC","3399FF","33CCFF","66CCCC","99FFFF","66FFCC","33CC99","33FF99","66FF66","99CC99","00FF33","66FF33","99FF66","99FF33","CCFF00","CCCC33","CCCCCC")
var c3 = new Array("FFFF66","FFCC33","CC9966","FF6600","FF3300","FF6666","CC3333","FF0066","FF0099","FF33CC","FF66FF","CC00CC","CC00FF","9933FF","6600CC","6633FF","6666CC","3300CC","0000FF","3366CC","0099FF","00CCFF","339999","66FFFF","33FFCC","00CC99","00FF99","33FF66","66CC66","00FF00","33FF00","66CC00","99CC66","CCFF33","999966","999999")
var c4 = new Array("FFFF33","CC9900","CC6600","CC6633","FF0000","FF3333","993333","CC3366","CC0066","CC6699","FF33FF","CC33CC","9900CC","9900FF","6633CC","6600FF","666699","3333CC","0000CC","0033FF","6699CC","3399CC","669999","33FFFF","00FFCC","339966","33CC66","00FF66","669966","00CC00","33CC00","66CC33","99CC00","CCCC99","999933","666666")
var c5 = new Array("FFFF00","CC9933","996633","993300","CC0000","FF0033","990033","996666","993366","CC0099","FF00FF","990099","996699","660099","663399","330099","333399","000099","0033CC","003399","336699","0099CC","006666","00FFFF","33CCCC","009966","00CC66","339933","336633","33CC33","339900","669933","99CC33","666633","999900","333333")
var c6 = new Array("CCCC00","996600","663300","660000","990000","CC0033","330000","663333","660033","990066","CC3399","993399","660066","663366","330033","330066","333366","000066","000033","003366","006699","003333","336666","00CCCC","009999","006633","009933","006600","003300","00CC33","009900","336600","669900","333300","666600","000000")
var sHTML = "";
sHTML += ("<table border=0 width=370 align=center cellpadding=0 cellspacing=0><tr><td width=45>  <table border=1 cellpadding=0 cellspacing=0><tr><td id='"+ColorID+"' width=25 height=25></td></tr></table>   <div id='"+TextID+"'><font size=1>&nbsp;</font></div> </td><td>&nbsp;</td><td>")
sHTML += ("<table cellpadding=0 cellspacing=1 bgcolor=black>")
if(Type==0)
    {
    for(var i=1;i<=6;i++)
        {
        sHTML += ("<tr>")
        for(var r=0;r<eval("c"+i).length;r++)
            {
            var colour = eval("c"+i+"[r]")
            sHTML += ("<td onclick=\""+OutputID+".value='"+colour+"';"+Command+"\" style=\"background-color:"+colour+";\" width=9 height=6 onmouseover=\""+ColorID+".style.background='#"+colour+"';"+TextID+".innerHTML='<font size=1>"+colour+"</font>'\"></td>")
            }
        sHTML += ("</tr>")
        }
    }
if(Type==1)
    {
    for(var i=1;i<=6;i++)
        {
        sHTML += ("<tr>")
        for(var r=0;r<eval("c"+i).length;r++)
            {
            var colour = eval("c"+i+"[r]")
            sHTML += ("<td onclick=\""+ColorID+".style.background='#"+colour+"';"+TextID+".innerHTML='<font size=1>"+colour+"</font>';"+OutputID+".value='"+colour+"';"+Command+"\" style=\"background-color:"+colour+";\" width=9 height=6 onmouseover=\"\"></td>")
            }
        sHTML += ("</tr>")
        }
    }
sHTML += ("</table>")
sHTML += ("<input type=hidden id='"+OutputID+"'>")
sHTML += ("</td></tr></table>")
return sHTML;
}

var oElStore;
var isLayerActive;

function buildToolbar(srcN)
{
//    drawIcon(23,110,23,"btnCut","Cut","doCmd('Cut',"+src+");")
//    drawIcon(46,110,23,"btnCopy","Copy","doCmd('Copy',"+src+");")
    src="document.getElementById('"+srcN+"')";
    drawIcon(69,110,23,"btnPaste","Paste","doCmd('Paste',"+src+");")
    drawIcon(0,0,110,"btnFontName","Font Name","displayFontNameBox("+src+")")
    drawIcon(110,0,96,"btnFontSize","Font Size","displayFontSizeBox("+src+")")
    drawIcon(92,330,23,"btnForeground","Text Color","displayFgColorBox("+src+")")
//    drawIcon(92,110,23,"btnUndo","Undo","doCmd('Undo',"+src+")")
//    drawIcon(115,110,23,"btnRedo","Redo","doCmd('Redo',"+src+")")
    drawIcon(138,110,23,"btnBold","Bold","bbsimplestyle(0,"+src+")")
    drawIcon(161,110,23,"btnItalic","Italic","bbsimplestyle(1,"+src+");")
    drawIcon(184,110,23,"btnUnderline","Underline","bbsimplestyle(2,"+src+");")
//    document.write("<br>")
    drawIcon(115,220,23,"btnInsertOrderedList","Ordered List","bblist(5,'1',"+src+");")
    drawIcon(138,220,23,"btnInsertUnorderedList","Unordered List","bblist(11,'',"+src+");")
    drawIcon(253,220,23,"btnExternalLink","Create/edit Link","bblink("+src+")")
    drawIcon(69,330,23,"btnInternalImage","Insert/update Image","bbimg("+src+")")

}
function _keypress(src)
{
    e=src.window.event
    if(e.keyCode==13 && e.shiftKey==false)
        {
        e.cancelBubble=true
        e.returnValue=false
        var oSel=src.document.selection.createRange()
        oSel.pasteHTML('<br>')
        oSel.select()
        oSel.moveEnd("character", 1);
        oSel.moveStart("character", 1);
        oSel.collapse(false);
        return false;
        }
    return true;
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/selection [v1.0]

Selection = function(input){
    this.isTA = (this.input = input).nodeName.toLowerCase() == "textarea";
};
with({o: Selection.prototype}){
    o.setCaret = function(start, end){
        var o = this.input;
        if(Selection.isStandard)
            o.setSelectionRange(start, end);
        else if(Selection.isSupported){
            var t = this.input.createTextRange();
            end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
            start -= o.value.slice(0, start).split("\n").length - 1;
            t.move("character", start), t.moveEnd("character", end), t.select();
        }
    };
    o.getCaret = function(){
        var o = this.input;
        if(Selection.isStandard)
            return {start: o.selectionStart, end: o.selectionEnd};
        else if(Selection.isSupported){
            var s = (this.input.focus(), document.selection.createRange()), r, start, end, value;
            if(s.parentElement() != o)
                return {start: 0, end: 0};
            if(this.isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !this.isTA)
                return r.setEndPoint("EndToStart", s), {start: r.text.length, end: r.text.length + s.text.length};
            for(var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
            r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
            s.text = $, start = o.value.indexOf($);
            if(document.execCommand && document.queryCommandSupported("Undo"))
                for(r in {0:0, 0:0})
                    document.execCommand("Undo");
            return o.value = value, this.setCaret(start, end), {start: start, end: end};
        }
        return {start: 0, end: 0};
    };
    o.getText = function(){
        var o = this.getCaret();
        return this.input.value.slice(o.start, o.end);
    };
    o.setText = function(text){
        var o = this.getCaret(), i = this.input, s = i.value;
        i.value = s.slice(0, o.start) + text + s.slice(o.end);
        this.setCaret(o.start += text.length, o.start);
    };
    new function(){
        var d = document, o = d.createElement("input"), s = Selection;
        s.isStandard = "selectionStart" in o;
        s.isSupported = s.isStandard || (o = d.selection) && !!o.createRange();
    };
}

