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)
  { 
  	ta			=	document.getElementById(ta);
	bits 		= 	getSelection(ta);
    
	openTag		=	'[' + pTag + ']';	//this will change for the likes of images
	closeTag	=	'[/' + pTag + ']';	//should be nullified for the likes of images
	
	if (pTag == "IMG") 
	{
    	imagePath = prompt('Enter Image URL:', 'http://');
    	if ((imagePath != null) && (imagePath != "")) 
		{
      		openTag		=	"[IMG SRC='" + imagePath + "'/]";
			closeTag	=	"";
    	}
	}
	
	
	if(bits)
      { if(!matchPTags(bits[2]))
          { alert('\t\tInvalid Selection\nSelection contains unmatched opening or closing tags.');
            return;
          }
        
		//print the opening tag
		//ta.value = bits[1] + '[' + pTag + ']' + bits[2] + '[/' + pTag + ']' + bits[3];
		
								ta.value 	= 	bits[1] + openTag;
		if (closeTag != "") 	ta.value 	+= 	bits[2] + closeTag;
								ta.value 	+= 	bits[3];
		
		
      }
  }