function reloadCommonData() {
    $authenticationIsLoginned(isLoginedCallback);

    try {
        $renderGet("user", "self", updateSubDivs);
    } finally {
        $renderUserActions(showUserActions);
    }
}

function isLoginedCallback(aAttributes) {
    if (aAttributes["Loginned"] == "true") {
        dojo.byId("userLogin").innerHTML = "Пользователь: " + aAttributes["Login"] +
                                           "<br/><a href=\"#\" onclick=\"dialogLogout(); return false;\">Выйти из системы</a>";
    } else {
        dojo.byId("userLogin").innerHTML = "Пользователь: Гость<br/>" +
                                           "<a href=\"#\" onclick=\"dialogLogin(); return false;\">Войти в систему</a><br/>" +
                                           "<a href=\"#\" onclick=\"showSaveDialog('TypeUser'); return false;\">Зарегистрироваться</a><br/>";
    }
}

function rootReloaded(aAttributes) {
    document.location.href = "/";
}

/**
 * В ответе содержатся строки объекта + prefixName, который передан из запроса.
 * @param aAttributes
 */
function updateSubDivs(aAttributes, aObjects) {
    var prefix = aAttributes["prefixName"] + ".";

    if (!aObjects["object"]) {
        return;
    }

    var objectAttributes = aObjects["object"]._attributes;
    for (var attributeName in objectAttributes) {
        var div = document.getElementById(prefix + attributeName);
        if (div && objectAttributes[attributeName]) {
            div.innerHTML = objectAttributes[attributeName];
        }
    }
}

/**
 * Загружает отрендеренные сервером данные в правильный див.
 * @param aObjectType
 * @param aQuery
 * @param aParentDivId
 * @param aPageSize
 * @param aPage
 * @param aMaxDepth
 * @param aSortType
 * @param aSortAttributeName
 * @param aSortIsAsc
 */
function loadPageData(aObjectType, aQuery, aParentDivId,
                      aPageSize, aPage, aMaxDepth, aSortType,
                      aSortAttributeName, aSortIsAsc, aTemplate, aNotNeedSurroundingDiv, aLoadFromAllRoots,
                      aGroupBy, aGroupByType, aCallBack) {
    if (aObjectType == null) {
        aObjectType = (mainObjectsType == null ? "Entry" : mainObjectsType);
    }

    if (!aMaxDepth || aMaxDepth == "") {
        aMaxDepth = 0;
    }

    if (!aPage) {
        aPage = 1;
    }

    if (!aSortIsAsc) {
        aSortIsAsc = false;
    }

    var needSurroundingDiv = true;

    //noinspection RedundantIfStatementJS
    if (!aNotNeedSurroundingDiv) {
        needSurroundingDiv = true;
    } else {
        needSurroundingDiv = false;
    }

    if (aParentDivId && dojo.byId("" + aParentDivId)) {
        var divToAlter = document.getElementById(aParentDivId);
        var needToWipeIn = false; //(divToAlter.innerHTML && divToAlter.innerHTML != "No Comments :)" ? true : false);

        if (needToWipeIn) {
            dojo.fx.wipeOut({
                node: aParentDivId,
                duration: 100,
                onEnd: function() {
                    $renderList(aGroupBy, aGroupByType, null, aLoadFromAllRoots, aMaxDepth, needSurroundingDiv, aObjectType, aPage, aPageSize,
                            aParentDivId, null, aQuery.replace(/`/g, '"'),
                            aSortAttributeName, aSortIsAsc, aSortType, aTemplate, aCallBack ? aCallBack : updatePageData);
                }
            }).play();
        } else {
            $renderList(aGroupBy, aGroupByType, null, aLoadFromAllRoots, aMaxDepth, needSurroundingDiv, aObjectType, aPage, aPageSize,
                    aParentDivId, null, aQuery.replace(/`/g, '"'),
                    aSortAttributeName, aSortIsAsc, aSortType, aTemplate, aCallBack ? aCallBack : updatePageData);
        }
    }
}

/**
 * ид объекта, ид целевого дива, тип вставки - replace/top/bottom
 */
function loadSingleObject(aId, aDivId, aPositionInDiv, aNeedSurroundingDiv) {
    if (!aNeedSurroundingDiv) {
        aNeedSurroundingDiv = false;
    }

    if (aDivId && dojo.byId("" + aDivId)) {
        $renderList(null, null, aId, null, null, aNeedSurroundingDiv, null, null, null, aDivId, aPositionInDiv, "singleObject",
                null, null, null, null, updateSingleObject);
    }
}

function updateSingleObject(aAttributes) {
    var parentDivId = aAttributes["parentDivId"];
    var divToAlter = document.getElementById(parentDivId);
    var position = aAttributes["parentDivPosition"];

    if (position == "top") {
        divToAlter.innerHTML = aAttributes["html"] + divToAlter.innerHTML;
    } else if (position == "bottom") {
        divToAlter.innerHTML = divToAlter.innerHTML + aAttributes["html"];
    } else if (position == "replace") {
        divToAlter.innerHTML = aAttributes["html"];
    }
}

/**
 * В ответе должно быть:
 * 1. количество страниц (число, pagesCount)
 * 2. текущая страница (число, pageIndex)
 * 3. хтмл, который втыкаем в pageData (html)
 * 4. ид дива, куда втыкаем (parentDivId)
 * @param aAttributes
 */
function updatePageData(aAttributes, aObjects, aResultType, aResultDescription, aCallbackName) {
    var parentDivId = aAttributes["parentDivId"];
    var pageString = createPageDiv(aAttributes, parentDivId, aCallbackName);
    var divToAlter = document.getElementById(parentDivId);

    //    if (parentDivId == "") {
    //        alter(divToAlter.innerHTML)
    //    }

    var needToWipeIn = false; //(divToAlter.innerHTML && divToAlter.innerHTML != "No Comments :)" ? true : false);

    if (aAttributes["html"]) {
        divToAlter.innerHTML = '';

        if (needPagesOnTop) {
            divToAlter.innerHTML += pageString;
        }


        divToAlter.innerHTML += aAttributes["html"];

        if (needPagesOnBottom) {
            divToAlter.innerHTML += pageString;
        }

        //        divToAlter.normalize();
    }

    if (parentDivId.substring(0, 18) == "categoriesSelector") {
        updateCategoriesSelection();
    } else if (parentDivId.substring(0, 8) == "comments") {
        correctParentOpenLinks();
    }

    if (divToAlter.tagName == "SELECT" && divToAlter.options.length > 0) {
        divToAlter.selectedIndex = 0;

        if (updateRightsTable) {
            updateRightsTable();
        }
    }

    if (needToWipeIn) {
        dojo.fx.wipeIn({
            node: parentDivId,
            duration: 100
        }).play();
    }

    try {
        if (typeof(window['dp']) != "undefined") {
            dp.SyntaxHighlighter.ClipboardSwf = '/js/SyntaxHighlighter/clipboard.swf';
            dp.SyntaxHighlighter.HighlightAll('code');

            var pres = document.getElementsByTagName("TEXTAREA");
            for (var i = 0; i < pres.length; i++) {
                var pre = pres[i];

                if (pre.getAttribute("name") == "code") {
                    pre.parentNode.removeChild(pre);
                }
            }
        }
    } catch(e) {
        alert(dojo.toJson(e));
    }
}

function correctParentOpenLinks(aElement) {
    if (!aElement) {
        aElement = document.body;
    }

    for (var i = 0; i < aElement.childNodes.length; i++) {
        var element = aElement.childNodes[i];
        if (element.id != null && element.id != "") {
            var commentsElement = document.getElementById("comments" + element.id);
            if (commentsElement) {
                var aHrefElement = document.getElementById("commentsShow" + element.id)

                if (aHrefElement) {
                    if (commentsElement.innerHTML == "") {
                        aHrefElement.innerHTML = "Посмотреть комментарии";
                    } else {
                        aHrefElement.innerHTML = "Скрыть комментарии";
                    }
                }
            }
        }

        correctParentOpenLinks(element);
    }
}

var _editingEntryCategories = new Array();

function updateCategoriesSelection() {
    if (_editingEntryCategories.length != 0) {
        for (var i = 0; i < _editingEntryCategories.length; i++) {
            var element = document.getElementById("check" + _editingEntryCategories[i]);

            try {
                element.checked = true;
                eval(element.getAttribute("onchange"));
            } catch(ex) {
            }

            _editingEntryCategories.splice(i, 1);
            i--;
        }

        if (_editingEntryCategories.length != 0) {
            setTimeout("updateCategoriesSelection", 300);
        }
    }
}

/**
 * Удаляет все поддивы указанного дива кроме одного, также указанного.
 * @param aParentDivId
 * @param aDivIdToStay
 */
function removeAllButOne(aParentDivId, aDivIdToStay) {
    document.location.hash = "#id/" + aDivIdToStay;

    var parentDiv = document.getElementById(aParentDivId);
    for (var i = 0; i < parentDiv.childNodes.length; i++) {
        var element = parentDiv.childNodes[i];
        if (element.tagName == "DIV" && element.id != aDivIdToStay) {
            parentDiv.removeChild(element);
            i--;
        }
    }
}

/**
 * Создает листалку по страницам.
 * @param aAttributes
 */
function createPageDiv(aAttributes, aDivToScrollId, aCallbackName) {
    var scrollScript = "scrollPageToDiv('" + aDivToScrollId + "'); ";

    if (!aCallbackName) {
        aCallbackName = "updatePageData";
    }

    var pagesCount = new Number(aAttributes["pagesCount"]);

    if (pagesCount <= 1) {
        return "";
    }

    var pageIndex = new Number(aAttributes["pageIndex"]);
    var pageSize = new Number(aAttributes["pageSize"]);

    var type = aAttributes["objectType"];
    var query = aAttributes["query"];
    var divId = aAttributes["parentDivId"];

    var sortAttribute = aAttributes["sortAttribute"];
    var sortType = aAttributes["sortType"];
    var sortIsAsc = aAttributes["sortIsAsc"];
    var template = aAttributes["template"];

    var loadFromAllRoots = aAttributes["loadFromAllRoots"];
    var needSurroundingDiv = aAttributes["needSurroundingDiv"];

    var longStart = true;

    var startPage = pageIndex - 5;
    if (startPage <= 1) {
        startPage = 1;
        longStart = false;
    }
    
    var longEnd = true;

    var endPage = pageIndex + 5;
    if (endPage >= pagesCount) {
        endPage = pagesCount;
        longEnd = false;
    }

    var result = '<div class="pages" align="center">';

    if (pageIndex > 1) {
        result += '<div class="pagePrevious" onClick="' + scrollScript + pageLink(type, query, divId, pageIndex-1, pageSize, sortType, sortAttribute, sortIsAsc, template, needSurroundingDiv, loadFromAllRoots, aCallbackName) + '"><nobr>&larr;<span>Предыдущая</span></nobr></div>';
    } else {
        result += '<div class="pagePreviousDisabled"><nobr>&larr;<span>Предыдущая</span></nobr></div>';
    }

    if (longStart) {
        result += '<div class="pagePage" onClick="' + scrollScript + pageLink(type, query, divId, 1, pageSize, sortType, sortAttribute, sortIsAsc, template, needSurroundingDiv, loadFromAllRoots, aCallbackName) + '">1</div>';
        if (startPage > 2) {
            result += '<div class="pageHellip">&hellip;</div>';
        }
    }

    for (var i = startPage; i <= endPage; i++) {
        if (i == pageIndex) {
            result += '<div class="pageCurrent">' + i + '</div>';
        } else {
            result += '<div class="pagePage" onClick="' + scrollScript + pageLink(type, query, divId, i, pageSize, sortType, sortAttribute, sortIsAsc, template, needSurroundingDiv, loadFromAllRoots, aCallbackName) + '">' + i + '</div>';
        }
    }

    if (longEnd) {
        if (endPage < pagesCount - 1) {
            result += '<div class="pageHellip">&hellip;</div>';
        }
        result += '<div class="pagePage" onClick="' + scrollScript + pageLink(type, query, divId, pagesCount, pageSize, sortType, sortAttribute, sortIsAsc, template, needSurroundingDiv, loadFromAllRoots, aCallbackName) + '">' + pagesCount + '</div>';
    }

    if (pageIndex < pagesCount) {
        result += '<div class="pageNext" onClick="' + scrollScript + pageLink(type, query, divId, pageIndex+1, pageSize, sortType, sortAttribute, sortIsAsc, template, needSurroundingDiv, loadFromAllRoots, aCallbackName) + '"><nobr><span>Следующая</span>&rarr;</nobr></div>';
    } else {
        result += '<div class="pageNextDisabled"><nobr><span>Следующая</span>&rarr;</nobr></div>';
    }

    return result + "</div>";
}

/**
 * Скроллит страницу к началу дива
 * @param aDivId
 */
function scrollPageToDiv(aDivId) {
    var position = findDivOffset(document.getElementById(aDivId));

    var currentPosition = 0;
    if (window.scrollY) {
        currentPosition = window.scrollY;
    } else if (window.scrollTop) {
        currentPosition = window.scrollTop;
    }

    if (currentPosition > position) {
        if (window.scroll) {
            window.scroll(0, position);
        } else if (window.scrollY) {
            window.scrollY = position;
        }
    }
}

function findDivOffset(aDiv) {
    if (!aDiv) {
        return 0;
    }

    return aDiv.offsetTop + findDivOffset(aDiv.offsetParent);
}

/**
 * Создает элемент листалки по страницам
 * @param aType
 * @param aQuery
 * @param aDivId
 * @param aPage
 * @param aPageSize
 * @param aSortType
 * @param aSortAttribute
 * @param aSortIsAsc
 */
function pageLink(aType, aQuery, aDivId, aPage, aPageSize, aSortType, aSortAttribute, aSortIsAsc, template, needSurroundingDiv, loadFromAllRoots, aCallbackName) {
    var sortAttributes = "";
    if (aSortType && aSortAttribute && aSortIsAsc) {
        sortAttributes = ", '" + aSortType + "', '" + aSortAttribute + "', " + aSortIsAsc;
    }

    if (template) {
        template = ", '" + template + "'";
    } else {
        template = '';
    }

    if (!aCallbackName) {
        aCallbackName = "updatePageData";
    }

//aObjectType, aQuery, aParentDivId,
//                      aPageSize, aPage, aMaxDepth, aSortType,
//                      aSortAttributeName, aSortIsAsc, aTemplate, aNotNeedSurroundingDiv, aLoadFromAllRoots,
//                      aGroupBy, aGroupByType, aCallBack

    return "loadPageData('" + aType + "', '" + aQuery.replace(/\"/g, '`') + "', '" + aDivId + "', " + aPageSize + ", " + aPage + ", " +
                         "0" + sortAttributes + template + ", " + !needSurroundingDiv + ", " + loadFromAllRoots + ", " +
                         "null, null, " + //ToDo: тоже передавать
                         aCallbackName + ")";
}

var _objectNames = new Array();
_objectNames["TypeRoot"] = "Блоги";
_objectNames["TypeFile"] = "Файлы";
_objectNames["TypeEntry"] = "Записи";
_objectNames["TypeCategory"] = "Категории";
_objectNames["TypeComment"] = "Комментарии";
_objectNames["TypeUser"] = "Пользователи";

/**
 * Функция обработки результатов поиска. 
 */
function showSearchResults(aAttributes, aObjects) {
    var innerHTML = "";

    for (var attributeName in aAttributes) {
        if (attributeName.substring(0, 5) == "html.") {
            innerHTML += '<div class="searchResultCategory">' + _objectNames[attributeName.substring(5)] + "</div>" + aAttributes[attributeName];
        }
    }

    document.getElementById("pageData").innerHTML = innerHTML;
}

/**
 * Полученные действия распихиваем по дивам
 */
function showUserActions(aAttributes, aObjects) {
    for (var attributeName in aAttributes) {
        var element = document.getElementById("actions." + attributeName);
        if (element) {
            element.innerHTML = aAttributes[attributeName];
        }
    }
}
