function getSelection(ta)
 { var bits = [ta.value,'','',''];
   if(document.selection)
     { var vs = '#$%^%$#';
       var tr=document.selection.createRange()
       if(tr.parentElement()!=ta) return null;
       bits[2] = tr.text;
       tr.text = vs;
       fb = ta.value.split(vs);
       tr.moveStart('character',-vs.length);
       tr.text = bits[2];
       bits[1] = fb[0];
       bits[3] = fb[1];
     }
   else
     { if(ta.selectionStart == ta.selectionEnd) return null;
       bits=(new RegExp('([\x00-\xff]{'+ta.selectionStart+'})([\x00-\xff]{'+(ta.selectionEnd - ta.selectionStart)+'})([\x00-\xff]*)')).exec(ta.value);
     }
    return bits;
 }

function matchPTags(str)
 { str = ' ' + str + ' ';
   ot = str.split(/\[[B|U|I].*?\]/i);
   ct = str.split(/\[\/[B|U|I].*?\]/i);
   return ot.length==ct.length;
 }

function addPTag(ta,pTag)
 { bits = getSelection(ta);
   if(bits)
     { if(!matchPTags(bits[2]))
         { alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
           return;
         }
       ta.value = bits[1] + '[' + pTag + ']' + bits[2] + '[/' + pTag + ']' + bits[3];
     }
 }

	function displayDiv(obj)
    {
        var divstyle = new String();
        divstyle = document.getElementById(obj).style.display;
        if(divstyle.toLowerCase()=="block" || divstyle == "")
        {
            document.getElementById(obj).style.display = "none";
        }
        else
        {
            document.getElementById(obj).style.display = "block";
        }
    }
	
function addATag(ta,pTag)
 { bits = getSelection(ta);
   if(bits)
     { if(!matchPTags(bits[2]))
         { alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
           return;
         }
       ta.value = bits[1] + '<a href="' + bits[2] + '">link title goes here</a>' + bits[3];
     }
 }
 
 function addIMGTag(ta,pTag)
 { bits = getSelection(ta);
   if(bits)
     { if(!matchPTags(bits[2]))
         { alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
           return;
         }
       ta.value = bits[1] + '<img src="' + bits[2] + '" />' + bits[3];
     }
 }
 
 function addHTMLTag(ta,pTag)
 { bits = getSelection(ta);
   if(bits)
     { if(!matchPTags(bits[2]))
         { alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
           return;
         }
       ta.value = bits[1] + '<' + pTag + '>' + bits[2] + '</' + pTag + '>' + bits[3];
     }
 }
