function saveseladd(doc)
{
if(document.selection)
{
doc.sel = document.selection.createRange().duplicate();
}
}
function click_bbadd(aid, Tag, Close)
{
var changed = 0;

var Open = '[' + Tag + ']';
if(!Close)
var Close = '[/' + Tag + ']';
else
Close = '[/' + Close + ']';
var doc = document.getElementById(aid);
doc.focus();
sel1 = doc.value.substr(0, doc.selectionStart);
sel2 = doc.value.substr(doc.selectionEnd);
sel = doc.value.substr(doc.selectionStart, doc.selectionEnd - doc.selectionStart);
s_val = sel;
s_val_len = sel.length;

if(Tag == 'cut')
{
var Open = '[' + Tag + ']';
var Close = '';
}

if(Tag == 'img')
{
var more = 'Ссылка_на_картинку';
if(s_val_len == 0) {
var Open = '[' + Tag + '=Описание]'+more;
} else {
if (s_val.indexOf('http') === -1) { var Open = '[' + Tag + '='+ s_val +']'+more; changed = 2; } else { var Open = '[' + Tag + '=Описание]'; changed = 1; }
}
}

if(Tag == 'url')
{
var more = 'Название_ссылки';
if(s_val_len == 0) {
var Open = '[' + Tag + '=http://]'+more;
} else {
if (s_val.indexOf('http') === -1) { var Open = '[' + Tag + '=http://]'; changed = 1; } else { var Open = '[' + Tag + '='+ s_val +']'+more; changed = 2; }
}
}

//Объединение
var ss = doc.scrollTop;
if (changed == 2) { sel = ''; }
doc.value = sel1 + Open + sel + Close + sel2;

if (changed == 0) { doc.selectionStart = sel1.length + Open.length; doc.selectionEnd = doc.selectionStart + sel.length; }
if (changed == 1) { doc.selectionStart = sel1.length + Tag.length+2; doc.selectionEnd = sel1.length + Open.length-1; }
if (changed == 2) { doc.selectionStart = sel1.length + Tag.length+3+ s_val.length; doc.selectionEnd = doc.selectionStart + more.length; }
doc.scrollTop = ss;
return false;
}