//----------------------------------------------------------------------------------
// флаг "Оформление" показывает и скрывает панель оформления
//
function toggleDecorPanel(elem)
{
    $flag = $(elem);
    $form = $flag.closest("form");
    $decorPanel = $form.find(".decor-panel");
    $flag.prop("checked") ? $decorPanel.show() : $decorPanel.hide();
}

//----------------------------------------------------------------------------------
// возвращает textarea для текста сообщения по элементу формы
//
function messageTextarea(elem)
{
    $e = $(elem);
    $form = $e.closest("form");
    $message_text = $form.find("#MESSAGE_TEXT");
    return $message_text[0];
}

//----------------------------------------------------------------------------------
function onChangeColor(elem)
{
    $colorInput = $(elem);
    $colorSelector = $colorInput.closest(".color-selector");
    $colorCode = $colorSelector.find(".decorTextColorCode");
    $colorCode.val($colorInput.val().toUpperCase()).css({"color":$colorInput.val()});
}

//----------------------------------------------------------------------------------
function onChangeColorCode(elem)
{
    $colorCodeInput = $(elem);
    $colorSelector = $colorCodeInput.closest(".color-selector");
    $colorInput = $colorSelector.find(".decorTextColor");
    $colorInput.val($colorCodeInput.val());
    $colorCodeInput.css({"color":$colorInput.val()});
}

//----------------------------------------------------------------------------------
// вставка тэгов оформления (decor)
//
function decorateBold(b)         { insertTags(b, '<B>',    '</B>'); }
function decorateItalic(b)       { insertTags(b, '<I>',    '</I>'); }
function decorateUnderlined(b)   { insertTags(b, '<U>',    '</U>'); }
function decorateDeleted(b)      { insertTags(b, '<DEL>',  '</DEL>'); }

function decorateSuperscript(b)  { insertTags(b, '<SUP>',  '</SUP>'); }
function decorateSubscript(b)    { insertTags(b, '<SUB>',  '</SUB>'); }
function decorateMarked(b)       { insertTags(b, '<MARK>', '</MARK>'); }
function decorateOutline(b)      { insertTags(b, '<SPAN CLASS="OUTLINE">',  '</SPAN>'); }

function decorateMargin(b)       { insertTags(b, '<DIV CLASS="MARGIN">',  '</DIV>'); }
function decorateCenter(b)       { insertTags(b, '<CENTER>',  '</CENTER>'); }
function decorateDetails(b)      { insertTags(b, '<DETAILS><SUMMARY>Подробности</SUMMARY>\n',  '</DETAILS>'); }
function decoratePreformatted(b) { insertTags(b, '<PRE>',  '</PRE>'); }

function decorateFontColor(b)
{
    $colorInput = $(b);
    $colorSelector = $colorInput.closest(".color-selector");
    $colorInput = $colorSelector.find(".decorTextColor");

    insertTags(b, '<FONT COLOR="' + $colorInput.val().toUpperCase() + '">',  '</FONT>');
}

//----------------------------------------------------------------------------------
// вставляет смайлик
//
function insertSmile(s)
{
    $s = $(s);
    smile = '';

    if (s.id == "like") {
        smile = String.fromCharCode(55357,56397); // палец вверх

    } else if (s.id == "heart") {
        smile = String.fromCharCode(55357,56470); // сердце сверкающее

    } else if (s.id == "fire") {
        smile = String.fromCharCode(55357,56613); // огонь

    } else if (s.id == "facepalm") {
        smile = String.fromCharCode(55358,56614); // фейспалм
    }


    insertTags(s, smile, '');
}

//----------------------------------------------------------------------------------
// вставляет тэги вокруг выделенного текста или просто в позицию курсора
// (c) Wikipedia.org
//
function insertTags(b, tagOpen, tagClose, sampleText = "")
{
    var txtarea = messageTextarea(b);

    var clientPC = navigator.userAgent.toLowerCase(); // Get client info
    var is_gecko = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1)
        && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
    var is_safari = ((clientPC.indexOf('applewebkit')!=-1) && (clientPC.indexOf('spoofer')==-1));
    var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));

    if (clientPC.indexOf('opera') != -1) {
        var is_opera = true;
        var is_opera_preseven = (window.opera && !document.childNodes);
        var is_opera_seven = (window.opera && document.childNodes);
    }

    // IE
    if (document.selection  && !is_gecko) {
        var theSelection = document.selection.createRange().text;
        if (!theSelection) theSelection=sampleText;
        txtarea.focus();
        if (theSelection.charAt(theSelection.length - 1) == " ") { // exclude ending space char, if any
            theSelection = theSelection.substring(0, theSelection.length - 1);
            document.selection.createRange().text = tagOpen + theSelection + tagClose + " ";
        } else {
            document.selection.createRange().text = tagOpen + theSelection + tagClose;
        }

        // Mozilla
    } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
        var replaced = false;
        var startPos = txtarea.selectionStart;
        var endPos = txtarea.selectionEnd;
        if (endPos-startPos) replaced = true;
        var scrollTop = txtarea.scrollTop;
        var myText = (txtarea.value).substring(startPos, endPos);
        if (!myText)  myText=sampleText;
        if (myText.charAt(myText.length - 1) == " ") { // exclude ending space char, if any
            subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
        } else {
            subst = tagOpen + myText + tagClose;
        }
        txtarea.value = txtarea.value.substring(0, startPos) + subst +
        txtarea.value.substring(endPos, txtarea.value.length);
        txtarea.focus();
        //set new selection
        if (replaced) {
            var cPos = startPos+(tagOpen.length+myText.length+tagClose.length);
            txtarea.selectionStart = cPos;
            txtarea.selectionEnd = cPos;
        } else {
            txtarea.selectionStart = startPos+tagOpen.length;
            txtarea.selectionEnd = startPos+tagOpen.length+myText.length;
        }
        txtarea.scrollTop = scrollTop;

        // All other browsers get no toolbar.
        // There was previously support for a crippled "help"
        // bar, but that caused more problems than it solved.
    }
    // reposition cursor if possible
    if (txtarea.createTextRange) {
        txtarea.caretPos = document.selection.createRange().duplicate();
    }
}
