Adding vB code like to a textfield - correctly!

Hello. I have made a shout box with buttons to let the user add smileys, formatting etc. I have done this perfectly but my problem is this. When adding the code to the textfield for example [ b] and [ / b], it always adds to the end of the textfield and not where the cursor is on. How can I do this? Like for example in this forum I highlight a text and click on the B button the code [ b] and [ / b] wraps around and the highlighted text. :-/