/*
*/
// Массив экземпляров объекта
var textAreaSelectionObjects = [];
// Получаем экземпляр объекта
function getTextAreaSelection(id) { // Получаем объект synhe
if (typeof(textAreaSelectionObjects[id]) == "undefined") {
textAreaSelectionObjects[id] = new textAreaSelectionHelper(id);
}
return textAreaSelectionObjects[id];
}
// Собственно объект, принимающий в качестве аргумента ID текстового поля
function textAreaSelectionHelper(id) {
var obj = document.getElementById(id);
this.target = obj;
// Создаем свойства carretHandler для доступа к объекту в контексте узла
// из обработчиков событий
this.target.carretHandler = this;
// Добавляем обработчик событий
this.target.onchange = _textareaSaver;
this.target.onclick = _textareaSaver;
this.target.onkeyup = _textareaSaver;
this.target.onmouseup = _textareaSaver;
this.target.onfocus = _textareaSaver;
if(!document.selection) this.target.onSelect = _textareaSaver;
// Свойства для запоминания позиции выделения
this.start=-1;
this.end=-1;
this.scroll=-1;
this.iesel=null;
}


/*for input only*/
function replace_in_input(my_id) { 
    
    var get_id = document.getElementById(my_id);

    var len = get_id.value.length;
    var start = get_id.selectionStart;
    var end = get_id.selectionEnd;
    var sel = get_id.value.substring(start, end);

    var replace = '#a#' + sel + '#/a#';

    // Here we are replacing the selected text with this one
    get_id.value = get_id.value.substring(0,start) + replace + get_id.value.substring(end,len);
}
/*for input only*/

// В прототип записываем методы
textAreaSelectionHelper.prototype = {
// Получим вделение
getSelectedText : function() {
    return this.iesel? this.iesel.text: (this.start>=0&&this.end>this.start)? this.target.value.substring(this.start,this.end): "";
},
// Установим текстовые фрагменты до выделения - text
// и после него, если нужно - secondtag
setSelectedText : function(text, secondtag) {
   
//alert( this.iesel + "\n" + this.start );

if (this.iesel) {
    if (typeof(secondtag) == "string") {
        var l = this.iesel.text.length;
        this.iesel.text = text + this.iesel.text + secondtag;
        this.iesel.moveEnd("character", -secondtag.length);
        this.iesel.moveStart("character", -l);
    } else {
        this.iesel.text = text;
    }
    this.iesel.select();
} else if (this.start >= 0 && this.end >= this.start) {
    var left = this.target.value.substring(0, this.start);
    var right = this.target.value.substr(this.end);
    var scont = this.target.value.substring(this.start, this.end);
    if (typeof(secondtag) == "string") {
        this.target.value = left + text + scont + secondtag + right;
        this.end = this.target.selectionEnd=this.start+text.length+scont.length;
        this.start = this.target.selectionStart = this.start + text.length;
    } else {
        this.target.value = left + text + right;
        this.end = this.target.selectionEnd = this.start + text.length;
        this.start = this.target.selectionStart = this.start + text.length;
    }
    this.target.scrollTop = this.scroll;
    this.target.focus();
} else {
    this.target.value += text + ((typeof(secondtag) == "string") ? secondtag: "");
    //this.target.value = text + this.target.value + secondtag;
    if (this.scroll >= 0) this.target.scrollTop = this.scroll;
}
},
getText : function() {
    return this.target.value;
},
setText : function(text) {
    this.target.value = text;
}
}
function _textareaSaver() {
if(document.selection) {
this.carretHandler.iesel = document.selection.createRange().duplicate();
} else if(typeof(this.selectionStart) != "undefined") {
this.carretHandler.start = this.selectionStart;
this.carretHandler.end = this.selectionEnd;
this.carretHandler.scroll = this.scrollTop;
} else {
this.carretHandler.start = this.carretHandler.end = -1;
}
}
// Клиентские функции, хотя можно обойтись и без них
function setAnc(id) {
getTextAreaSelection(id).setSelectedText('#a#', '#/a#');
}

