/**
 * Замена веделенного текста
 *
 * @param text Текст которым нужно заменит выделеное
 * @param textarea Input или Textarea в которую будет добавляться текст
 * @param replace 1 - Заменять выделеное на text
 * @param left Текст который будет помещен перед text
 * @param right Текст который будет помещен после text
 *
 * @return void
 */
function writeSelection( text, textarea, replace, left, right ) {

    textarea.focus();
    if (document.selection)
    {
        if ( replace == 1 ) {
            document.selection.createRange().text = left+text+right;
        } else {
            document.selection.createRange().text = left+document.selection.createRange().text+right;
        }
    } else if (textarea.selectionStart != "undefined") {
        text_selected = textarea.value.substring( textarea.selectionStart, textarea.selectionEnd );
        text_start    = textarea.value.substring( 0, textarea.selectionStart );
        text_end      = textarea.value.substring( textarea.selectionEnd );

        if ( replace == 1 ) {
            textarea.value = text_start+left+text+right+text_end;
        } else {
            textarea.value = text_start+left+text_selected+right+text_end;
        }
    } else {
        textarea.value = left+text+right+textarea.value;
    }

}

/**
 * Добавление смайлика
 *
 * @param smile Код смайлика
 *
 * @param void
 */
function setSmile( smile, area ) {
    if ( area == 'reply' ) {
        writeSelection( smile, document.forms.post.info_reply, 1, '', '' );
    } else {
        writeSelection( smile, document.forms.post.info_text, 1, '', '' );
    }
}

/**
 * Добавление тега
 *
 * @param left Тег слева от текста
 * @param right Тег справа от текста
 *
 * @return void
 */
function setTag( left, right, area ) {
    if ( area == 'reply' ) {
        writeSelection( '', document.forms.post.info_reply, 0, left, right );
    } else {
        writeSelection( '', document.forms.post.info_text, 0, left, right );
    }
}
