// --------------------------------------------
// Logout
// --------------------------------------------

var needPagesOnTop = true;
var needPagesOnBottom = false;

function preload() {
    new Image().src = "/i/hover/headerButtonLeft.png";
    new Image().src = "/i/hover/headerButtonBackground.png";

    new Image().src = "/i/hover/menuLeftRound.png";
    new Image().src = "/i/hover/menuApps.png";
    new Image().src = "/i/hover/menuDocuments.png";
    new Image().src = "/i/hover/menuEvents.png";
    new Image().src = "/i/hover/menuForum.png";
    new Image().src = "/i/hover/menuLinks.png";
    new Image().src = "/i/hover/menuNews.png";
    new Image().src = "/i/hover/menuQuestions.png";
}

function dialogLogout() {
    if (confirm("Вы уверены, что хотите выйти?")) {
        $authenticationLogout(responseLogout);
    }

    return false;
}

function responseLogout() {
    document.location.reload();
}

// --------------------------------------------
// Login
// --------------------------------------------

function startPasswordRecover() {
    dojo.byId("loginLabelLogin").innerHTML = 'Логин (если помните)';
    dojo.byId("loginInputPassword").style.display = 'none';

    dojo.byId("loginLabelPassword").innerHTML = '';
    dojo.byId("loginLabelPasswordRecover").innerHTML = '';

    dojo.byId("loginButtonSubmit").innerHTML = 'Вспомнить';

    dojo.byId("loginInputLogin").focus();
}

var _loginDialog = null;
var _loginLast = "";

function dialogLogin() {
    if (!_loginLast) {
        _loginLast = dojo.cookie("##_userLastLogin");

        if (!_loginLast) {
            _loginLast = "";
        }
    }

    var dialogDiv = dojo.byId("loginFormWrapper").childNodes[0];
    dialogDiv.parentNode.removeChild(dialogDiv);

    if (!_loginDialog) {
        _loginDialog = new dijit.Dialog({
            id: "loginDialog",
            title: "",
            refreshOnShow: true,
            hasTitle: false,
            hasShadow: false
        }, dialogDiv);
    }

    _loginDialog.startup();

    document.body.appendChild(_loginDialog.domNode);

    _loginDialog.show();

    if (_loginLast) {
        setTimeout('dojo.byId("loginInputLogin").value="' + _loginLast + '"; dojo.byId("loginInputPassword").focus();', 50);
    } else {
        setTimeout('dojo.byId("loginInputLogin").focus();', 50);
    }

    document.body.style.overflowX = "hidden";
    
    return false;
}

function hideLoginDialog() {
    _loginDialog.hide();

    var login = dojo.byId("loginInputLogin").value;
    var password = dojo.byId("loginInputPassword").value;

    var dialogDiv = dojo.byId('loginForm');

    dialogDiv.parentNode.removeChild(dialogDiv);
    var newLoginFormToMove = document.createElement("DIV");
    newLoginFormToMove.appendChild(dialogDiv);
    dojo.byId("loginFormWrapper").appendChild(newLoginFormToMove);

    dojo.byId("loginInputLogin").value = login;
    dojo.byId("loginInputPassword").value = password;

    _loginDialog = null;
    document.body.style.overflowX = "auto";
}

function submitLogin() {
    _loginLast = dojo.byId("loginInputLogin").value;
    dojo.cookie("##_userLastLogin", _loginLast);

    if (dojo.byId("loginInputPassword").style.display == 'none') {
        $authenticationRecoverPassword(_loginLast, responsePasswordRecovered);
    } else {
        $authenticationLogin(_loginLast, dojo.byId("loginInputPassword").value, null, responseLogin);
        hideLoginDialog();
    }
}

function responsePasswordRecovered(aAttributes, aObjects, aResultType) {
    if (aResultType == "OK") {
        alert("Подробности по продолжению процедуры восстановления пароля высланы вам в ящик e-mail");
        hideLoginDialog();
    } else {
        alert("Пользователь с указанным логином не найден, восстановление невозможно");
    }
}

function responseLogin(aAttributes, aObjects, aResultType, aResultDescription) {
    if (aResultType == "OK") {
        document.location.reload();
//        dojo.byId('loginFormForm').submit();
    } else if (aResultDescription == "NotActivated") {
        alert("Данная учетная запись не была активирована. Ссылка для активации должна была прийти вам в почту");
    } else {
        alert("Введен неверный логин или пароль. \nПопробуйте еще раз");
        dialogLogin();
    }
}

// --------------------------------------------
// Registration
// --------------------------------------------

var _registerDialog = null;
var _registerLogin = "";
var _registerEMail = "";
var _registerPassword = "";
var _registerPassword2 = "";

function dialogRegister() {
    var dialogDiv = document.createElement("DIV");
    dialogDiv.innerHTML =
        '<div id="registerForm">' +
            '<div id="registerLabelTitle">Регистрация</div>' +

            '<div id="registerLabelLogin">Имя пользователя:</div>' +
            '<input type="text" id="registerInputLogin" value="' + _registerLogin + '"/>' +
            '<div id="registerLabelEMail">E-mail:</div>' +
            '<input type="text" id="registerInputEMail" value="' + _registerEMail + '"/>' +
            '<div id="registerLabelPassword">Пароль:</div>' +
            '<input type="password" id="registerInputPassword" value="' + _registerPassword + '"/>' +
            '<div id="registerLabelPassword2">Еще раз пароль:</div>' +
            '<input type="password" id="registerInputPassword2" value="' + _registerPassword2 + '"/>' +

            '<div id="loginButtonCancel" onclick="_registerDialog.domNode.parentNode.removeChild(_registerDialog.domNode); _registerDialog.hide(); _registerDialog=null;  document.body.style.overflowX = \'auto\';">Передумал</div>' +
            '<div id="loginButtonSubmit" onclick="submitRegister();">Продолжить</div>' +

            '<div id="recaptcha_div"></div>' +
        '</div>';

    if (!_registerDialog) {
        _registerDialog = new dijit.Dialog({
            id: "registerDialog",
            title: "",
            refreshOnShow: true,
            hasTitle: false,
            hasShadow: false
        }, dialogDiv);
    }

    _registerDialog.startup();

    document.body.appendChild(_registerDialog.domNode);

    _registerDialog.show();

    setTimeout('dojo.byId("registerInputLogin").focus();', 50);

    document.body.style.overflowX = "hidden";

    setTimeout('Recaptcha.create("6LeTXQcAAAAAACdAttrJ-V-SPNKa0iMv9kDKTH6F", "recaptcha_div", { theme: "white" });', 50);

    return false;
}

function submitRegister() {
    _registerLogin = dojo.byId("registerInputLogin").value;
    _registerEMail = dojo.byId("registerInputEMail").value;

    _registerPassword = dojo.byId("registerInputPassword").value;
    _registerPassword2 = dojo.byId("registerInputPassword2").value;

    if (_registerPassword != _registerPassword2) {
        alert("Пароли не совпадают, повторите еще раз");
        dojo.byId("registerInputPassword").focus();
    } else if (_registerPassword == "") {
        alert("Введите непустой пароль");
        dojo.byId("registerInputPassword").focus();
    } else if (_registerLogin == "") {
        alert("Введите непустое имя пользователя");
        dojo.byId("registerInputLogin").focus();
    } else {
        $authenticationSendRegistrationMail(
                _registerEMail, _registerLogin,
                _registerPassword,
                Recaptcha.get_response(), Recaptcha.get_challenge(), responseRegister);

        var aNode = _registerDialog.domNode;
        aNode.parentNode.removeChild(_registerDialog.domNode);

        _registerDialog.hide();
        _registerDialog = null;
        document.body.style.overflowX = "auto";
    }
}

function responseRegister(aAttributes, aObjects, aResultType, aResultDescription) {
    if (aResultType == "OK") {
        alert("По указанному адресу выслано письмо с дальнейшими инструкциями. Если оно не приходит, посмотрите в спаме");
    } else if (aResultDescription == "ReCAPTCHA.failed") {
        alert("Вы неправильно ввели буквы с картинки. Попробуйте еще раз");
        dialogRegister();
    } else if (aResultDescription == "AlreadyExists") {
        alert("Пользователь с указанным логином уже существует. Попробуйте другой");
        dialogRegister();
    } else if (aResultDescription == "WrongEMail") {
        alert("Указанная в качестве EMail строка не похожа на EMail, введите другой пожалуйста");
        dialogRegister();
    } else if (aResultDescription == "SimplePassword") {
        alert("Слишком простой пароль. Даже я, сервер, подобрал его на раз");
        dialogRegister();
    } else {
        alert("Что-то пошло не так. Попробуйте еще раз");
    }
}

// --------------------------------------------
// Other things
// --------------------------------------------

function reloadPage() {
    document.location.reload();
}

function updateNews() {
    loadPageData("EntryNews", '', "newsList", 10, 1, 1, "Long", "PublishDateTime", false, "newsindex", true, true, null, null, putDaysIntoNews);
}

function putDaysIntoNews(aAttributes, aObjects, aResultType, aResultDescription) {
    updatePageData(aAttributes, aObjects, aResultType, aResultDescription, "putDaysIntoNews");
    removeSubsequentDaysFromNews();
}

function removeSubsequentDaysFromNews() {
    var newsItems = document.getElementById("newsList").getElementsByTagName("DIV");

    var lastDay = "";
    var lastDayDiv = null;

    for (var i in newsItems) {
        if (newsItems[i].className == "newsDayDay") {
            if (newsItems[i].innerHTML != lastDay) {
                lastDay = newsItems[i].innerHTML;
                lastDayDiv = newsItems[i].parentNode;
            } else {
                newsItems[i].innerHTML = "";

                var innerItems = newsItems[i].parentNode.childNodes;
                var newsItem = null;
                for (var j in innerItems) {
                    if (innerItems[j].className == "newsItem") {
                        newsItem = innerItems[j];
                        break;
                    }
                }

                try {
                    newsItems[i].parentNode.removeChild(newsItem);
                    newsItems[i].parentNode.parentNode.removeChild(newsItems[i].parentNode);
                    lastDayDiv.appendChild(newsItem);
                } catch(e) {
                    alert(dojo.toJson(e));
                }
            }
        }
    }
}

function updateDocs() {
    loadPageData("EntryDocument", '', "docsList", 10, 1, 1, "Long", "PublishDateTime", false, "default", true, true);
}

function updateQuestions() {
    loadPageData("EntryQuestion", '', "questionsList", 20, 1, 1, "Long", "PublishDateTime", false, "default", true, true);
}

function updateShorts() {
    loadPageData("EntryShort", '', "shortsList", 5, 1, 1, "Long", "PublishDateTime", false, "default", true, true);
}

function updateSections() {
    loadPageData("Root", '(Id, `NotEquals`, `1`)', "sectionsList", 10000, 1, 1, "String", "Title", true);
}

function updateAnswers(aQuestionId) {
    loadPageData("Answer", '(Number, `Long`, `ParentQuestionId`, `Equals`, `' + aQuestionId + '`)', "answersList", 20, 1, 1, "String", "CreatedTime", true);
}

function rebuildSearchIndex() {
    $systemRebuildSearchIndex(indexRebuilded);
}

function indexRebuilded() {
    alert("Search index was rebuilded.");
}

var searchSectionsDone = 0;
var searchSectionsCount = 5;
var somethingFound = false;

function updateSearchResults(aSearchString) {
    searchSectionsDone = 0;
    searchSectionsCount = 3;
    somethingFound = false;
    dojo.byId("searchText").value = aSearchString;

    dojo.byId("nothingFound").innerHTML = "Ищем…";
    dojo.byId("nothingFound").style.display = "block";

    loadPageData("EntryNews", "(FullText, `" + aSearchString + "`)", "searchNews", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchNewsLoaded);
    loadPageData("EntryDocument", "(FullText, `" + aSearchString + "`)", "searchDocuments", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchDocumentsLoaded);
    loadPageData("EntryQuestion", "(FullText, `" + aSearchString + "`)", "searchQA", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchQuestionsLoaded);
    loadPageData("EntryShort", "(FullText, `" + aSearchString + "`)", "searchShorts", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchShortsLoaded);
}

function updateTagSearchResults(aTagId) {
    searchSectionsDone = 0;
    searchSectionsCount = 3;
    somethingFound = false;

    dojo.byId("nothingFound").innerHTML = "Ищем…";
    dojo.byId("nothingFound").style.display = "block";

    loadPageData("EntryNews", "(List, `TagIds`, `Contains`, `" + aTagId + "`)", "searchNews", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchNewsLoaded);
    loadPageData("EntryDocument", "(List, `TagIds`, `Contains`, `" + aTagId + "`)", "searchDocuments", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchDocumentsLoaded);
    loadPageData("EntryQuestion", "(List, `TagIds`, `Contains`, `" + aTagId + "`)", "searchQA", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchQuestionsLoaded);
    loadPageData("EntryShort", "(List, `TagIds`, `Contains`, `" + aTagId + "`)", "searchShorts", 10, 1, 1, "Long", "Date", false, "search", false, true, null, null, searchShortsLoaded);
}

function checkIfAnythingFound() {
    if (searchSectionsDone == searchSectionsCount && !somethingFound) {
        dojo.byId("nothingFound").innerHTML = "Ничего не нашлось";
        dojo.byId("nothingFound").style.display = "block";
    }
}

function insertHeader(aListDivId, aHeaderText) {
    var list = dojo.byId(aListDivId);
    var parent = list.parentNode;
    parent.removeChild(list);

    var header = document.createElement("H1");
    header.innerHTML = '<div class="pageHeader">' + aHeaderText + '</div>';

    parent.appendChild(header);
    parent.appendChild(list);

    if (somethingFound) {
        dojo.byId("nothingFound").innerHTML = "";
        dojo.byId("nothingFound").style.display = "none";
    }
}

function searchNewsLoaded(aAttributes, aObjects) {
    searchSectionsDone++;

    if (!aAttributes["html"]) {
        var toRemove = dojo.byId("lastNews");
        toRemove.parentNode.removeChild(toRemove);
        checkIfAnythingFound();
    } else {
        somethingFound = true;
        updatePageData(aAttributes, aObjects);

        insertHeader("searchNews", "Новости");
    }
}

function searchDocumentsLoaded(aAttributes, aObjects) {
    searchSectionsDone++;

    if (!aAttributes["html"]) {
        var toRemove = dojo.byId("lastDocuments");
        toRemove.parentNode.removeChild(toRemove);
        checkIfAnythingFound();
    } else {
        somethingFound = true;
        updatePageData(aAttributes, aObjects);

        insertHeader("searchDocuments", "Документы");
    }
}

function searchQuestionsLoaded(aAttributes, aObjects) {
    searchSectionsDone++;

    if (!aAttributes["html"]) {
        var toRemove = dojo.byId("lastQuestions");
        toRemove.parentNode.removeChild(toRemove);
        checkIfAnythingFound();
    } else {
        somethingFound = true;
        updatePageData(aAttributes, aObjects);

        insertHeader("searchQA", "Вопросы");
    }
}

function searchShortsLoaded(aAttributes, aObjects) {
    searchSectionsDone++;

    if (!aAttributes["html"]) {
        var toRemove = dojo.byId("lastShorts");
        toRemove.parentNode.removeChild(toRemove);
        checkIfAnythingFound();
    } else {
        somethingFound = true;
        updatePageData(aAttributes, aObjects);

        insertHeader("searchShorts", "Заметки");
    }
}

function searchOnSite() {
    if (dojo.byId("searchText").value) {
        document.location = "/search/" + dojo.byId("searchText").value;
        return false;
    } else {
        return false;
    }
}

// --------------------------------------------
// Document/News approval
// --------------------------------------------

function approveDocument(aDocumentId, aCallback) {
    $entryDocumentApproved(aDocumentId, aCallback);
}

function approveNews(aNewsId, aCallback) {
    $entryNewsApproved(aNewsId, aCallback);
}

function approveShort(aShortId, aCallback) {
    $entryShortApproved(aShortId, aCallback);
}

function unapproveDocument(aDocumentId, aCallback) {
    $entryDocumentApprovedNot(aDocumentId, aCallback);
}

function unapproveNews(aNewsId, aCallback) {
    $entryNewsApprovedNot(aNewsId, aCallback);
}

function unapproveShort(aShortId, aCallback) {
    $entryShortApprovedNot(aShortId, aCallback);
}

// --------------------------------------------
// Saving user
// --------------------------------------------

function saveUser(aUserId) {
    var newPassword = null;

    if (dojo.byId("edit_newPassword").value != "" &&
            dojo.byId("edit_newPassword").value != dojo.byId("edit_newPassword2").value) {
        alert("Пароли не совпадают, повторите еще раз");
        return;
    } else if (dojo.byId("edit_newPassword").value != "") {
        newPassword = dojo.byId("edit_newPassword").value;
    }

    $adminEditUser(
            newAvatarJivaId,
            dojo.byId("edit_email").value,
            dojo.byId("edit_authorFullName") ? dojo.byId("edit_authorFullName").value : null,
            dojo.byId("edit_authorJabber") ? dojo.byId("edit_authorJabber").value : null,
            dojo.byId("edit_authorWorkPlace") ? dojo.byId("edit_authorWorkPlace").value : null,
            dojo.byId("edit_authorWorkTitle") ? dojo.byId("edit_authorWorkTitle").value : null,
            dojo.byId("checkbox_mailNewAnswers").checked ? 1 : 0,
            dojo.byId("checkbox_mailNewComments").checked ? 1 : 0,
            newPassword,
            dojo.byId("checkbox_useGravatar").checked ? 1 : 0,
            aUserId,
            userWasSaved);
}


function userWasSaved(aAttributes, aObjects, aResultType, aResultDescription) {
    if (aResultType == "OK") {
        document.location = "/user/" + aAttributes["UserId"];
    } else if (aResultDescription == "WrongEMail") {
        alert("Указанная в качестве EMail строка не похожа на EMail, введите другой пожалуйста");
    } else if (aResultDescription == "SimplePassword") {
        alert("Слишком простой пароль. Даже я, сервер, подобрал его на раз");
    }
}

// --------------------------------------------
// Questions and answers
// --------------------------------------------

function postAnswer(aTextAreaId, aQuestionId) {
    $entryAnswerWasAdded(dojo.byId(aTextAreaId).value, aQuestionId, function() { document.location.reload(); });
}

function removeAnswer(aAnswerId) {
    if (confirm('Вы уверены, что хотите удалить ответ?')) {
        $entryAnswerWasDeleted(aAnswerId, function() { document.location.reload(); });
    }
}

var _editingAnswerId = -1;

function editAnswer(aAnswerId) {
    dojo.byId('answerContent_' + aAnswerId).innerHTML =
            '<h1>Отредактировать ответ</h1>' +
            '<div class="editTextarea" style="height: 400px;">' +
                '<textarea id="edit_answerLong_' + aAnswerId + 'Wiki">Source is loading…</textarea>' +
                '<div id="preview_answerLong_' + aAnswerId + 'Wiki" class="edit_preview"></div>' +
                '<div class="edit_hint">Текст ответа на вопрос (вики-форматирование) <span onclick="togglePreview(\'answerLong_' + aAnswerId + '\', this); return false;">Предпросмотр</span></div>' +
            '</div>' +
            '<div style="clear: both;"></div>' +
            '<div class="funkyButton" style="float: right; width: 400px; font-size: 11pt;" ' +
                    'onclick="postEditedAnswer(\'edit_answerLong_' + aAnswerId + 'Wiki\', ' + aAnswerId + ');">Отослать отредактированный ответ</div>';

    _editingAnswerId = aAnswerId;
    $entryLoadAnswerSource(aAnswerId, answerSourceLoaded);
}

function answerSourceLoaded(aAttributes) {
    dojo.byId('edit_answerLong_' + _editingAnswerId + "Wiki").value = aAttributes["AnswerSource"];
    dojo.byId('edit_answerLong_' + _editingAnswerId + "Wiki").focus();
}

function postEditedAnswer(aTextAreaId, aAnswerId) {
    $entryAnswerWasEdited(aAnswerId, dojo.byId(aTextAreaId).value, function() { document.location.reload(); });
}

function selectAnswer(aAnswerId) {
    $entryAnswerWasSelected(aAnswerId, function() { document.location.reload(); });
}

// --------------------------------------------
// Questions and answers
// --------------------------------------------

var _currentUserLogin = '';
var _currentUserId = -1;
var _lastCommentButtonPressed = null;

function startCommenting(aObjectId, aUserId, aUserLogin, aButton) {
    if (_lastCommentButtonPressed == aButton) {
        aButton.innerHTML = "Комментировать";
        _lastCommentButtonPressed = null;
        submitNewComment(aObjectId);
    } else {
        aButton.innerHTML = "Сохранить";
        _lastCommentButtonPressed = aButton;

        if (dojo.byId('newCommentField')) {
            dojo.byId('newCommentField').parentNode.removeChild(dojo.byId('newCommentField'));
        }

        _currentUserId = aUserId;
        _currentUserLogin = aUserLogin;

        var newCommentDiv = document.createElement("DIV");
        newCommentDiv.innerHTML = '<div class="commentText" id="newCommentField">' +
                                  '<input type="text" onkeyup="commentChanged(event, ' + aObjectId + ');" maxlength="200" id="newCommentInput"/>' +
                                  '</div>';

        dojo.byId('comments_' + aObjectId).appendChild(newCommentDiv);
        dojo.byId('newCommentInput').focus();
    }
}

function commentChanged(event, aObjectId) {
    if (!event) {
        event = window.event;
    }

    if (event.keyCode == 13) {
        if (_lastCommentButtonPressed != null) {
            _lastCommentButtonPressed.innerHTML = "Комментировать";
            _lastCommentButtonPressed = null;
        }

        submitNewComment(aObjectId);
    }
}

function submitNewComment(aObjectId) {
    var commentText = dojo.byId('newCommentInput').value;

    if (commentText.length > 200) {
        commentText = commentText.substr(0, 200);
    }

    if (commentText) {
        $entryCommentWasAdded(commentText, aObjectId, commentAddedSuccesfully);
    }
}

function commentAddedSuccesfully(aAttributes, aObjects, aResultType) {
    if (aResultType == "OK") {
        dojo.byId('newCommentField').parentNode.removeChild(dojo.byId('newCommentField'));

        var newCommentDiv = document.createElement("DIV");
        newCommentDiv.innerHTML = '<div class="commentText">' + aAttributes["CommentText"] + ' — <a href="/user/' + _currentUserId + '">' +
                                  '<span class="commentAuthor">' + _currentUserLogin + '</span></a> ' +
                                  '<span class="commentRemoveText" onclick="removeComment(' + aAttributes["CommentId"] + ', this); return false;">Удалить</span>' +
                                  '</div>';

        dojo.byId('comments_' + aAttributes["ParentId"]).appendChild(newCommentDiv);
    } else {
        alert('Comment adding failed. Kick a developer, please. :)');
    }
}

function removeComment(aCommentId, aSpan) {
    if (confirm('Вы правда решились удалить комментарий?')) {
        aSpan.parentNode.parentNode.removeChild(aSpan.parentNode);
        $entryCommentWasRemoved(aCommentId);
    }
}

function sendMessageToAuthor(aAuthorId, aMessageText, aReCAPTCHA, aReCAPTCHAChallenge, aEMail, aName, aCallback) {
    $otherSendMessageToAuthor(aAuthorId, aMessageText, aReCAPTCHA, aReCAPTCHAChallenge, aEMail, aName, aCallback);
}