var _tk_old_RTE2_GenerateToolBarHtml = null;
var _tk_old_RTE2_ShowToolbar = null;
var _tk_old_window_scroll = null;
var _tk_RTE2_Editors = new Array();

function _tk_switchRTE2_Functions() {
    if (typeof (RTE2_ShowToolbar) != "undefined") {
        _tk_old_RTE2_ShowToolbar = RTE2_ShowToolbar;
        _tk_old_RTE2_GenerateToolBarHtml = RTE2_GenerateToolBarHtml;
        RTE2_GenerateToolBarHtml = _tk_RTE2_GenerateToolBarHtml;
        RTE2_ShowToolbar = _tk_RTE2_ShowToolbar;
    }

    _tk_old_window_scroll = window.onscroll;
    window.onscroll = windowScrolled;
}

function _tk_RTE2_GenerateToolBarHtml(strBaseElementID, strWebLanguage, toolbarWidth, instanceVariables) {
    _tk_RTE2_Editors.push(strBaseElementID);

    // Once the toolbar has been added ensure it is visible
    setTimeout("_tk_RTE2EnsureVisible('" + strBaseElementID + "')", 50);

    return _tk_old_RTE2_GenerateToolBarHtml(strBaseElementID, strWebLanguage, toolbarWidth, instanceVariables);
}

function _tk_RTE2_ShowToolbar(strBaseElementID) {
    _tk_old_RTE2_ShowToolbar(strBaseElementID);

    // Ensure the toolbar is visible when it is re-displayed
    _tk_RTE2EnsureVisible(strBaseElementID);
}

function windowScrolled() {

    // Call any previous scrolling function
    if (_tk_old_window_scroll != null) _tk_old_window_scroll();

    // Are any edtors visible?
    for (var c = 0; c < _tk_RTE2_Editors.length; c++) {
        var oToolbar = RTE2_GetToolbar(_tk_RTE2_Editors[c]);

        if (oToolbar != null) {
            if (oToolbar.style.display == "") {
                _tk_RTE2EnsureVisible(_tk_RTE2_Editors[c]);
                return; // Only one can be visible
            }
        }
    }
}

function _tk_RTE2EnsureVisible(strBaseElementID) {
    var oToolbar = RTE2_GetToolbar(strBaseElementID);
    var oIFrame = RTE2_GetToolbarIFrame(strBaseElementID)

    // Is it off the top?
    if (document.documentElement.scrollTop > (oToolbar.parentNode.offsetTop + parseInt(oToolbar.style.top)) + 5) {
        var iTop = document.documentElement.scrollTop - oToolbar.parentNode.offsetTop + 5;
        oToolbar.style.top = iTop;
        oIFrame.style.top = iTop;
    }

    // Is it off the bottom?
    if (document.documentElement.scrollTop + document.documentElement.clientHeight < (oToolbar.parentNode.offsetTop + parseInt(oToolbar.style.top) + 70)) {
        var iTop = document.documentElement.scrollTop + document.documentElement.clientHeight - 70 - oToolbar.parentNode.offsetTop;
        oToolbar.style.top = iTop;
        oIFrame.style.top = iTop;
    }
}

setTimeout("_tk_switchRTE2_Functions()", 100);