diff --git a/web/CatWarMod.js b/web/CatWarMod.js index 6f29d62..e119145 100644 --- a/web/CatWarMod.js +++ b/web/CatWarMod.js @@ -17,6 +17,7 @@ // ==/UserScript== (function (window, document, $) { + 'use strict'; const VERSION = '2.6'; @@ -3571,4 +3572,4 @@ function bbencode(html) { html = decodeHTML(html); return html; } -})(window, document, jQuery); \ No newline at end of file +})(window, document, $); diff --git a/web/cw.js b/web/cw.js index eff2026..fb5cb35 100644 --- a/web/cw.js +++ b/web/cw.js @@ -15,6 +15,7 @@ // @require https://cat.nyan404.ru/data/jquery-ui.js // ==/UserScript== (function (window, document, $) { + 'use strict'; if (typeof $ === 'undefined') return; const version = '1.54'; @@ -4209,4 +4210,4 @@ Y: span').first(); + if (white.length) { + white.children('a').css('color', ''); + white.css('background-color', $('#site_table').css('background-color')); + } + const footer = $('#footer'); + if (footer.length) { + const oldFooter = footer.html().split('
©'); + footer.html(oldFooter[0] + ` | Настройки
©` + oldFooter[1]); + } + let css = ` + #cwmod-popup-wrap { + position: fixed; + left: 0; + top: 0; + z-index: 2; + width: 100%; + height: 100%; + display: none; + justify-content: center; + align-items: center; + background-color: rgba(0, 0, 0, 0.5); + } + #cwmod-popup { + display: grid; + grid-gap: 1em; + max-height: 50vh; + width: 300px; + padding: 1em; + background: white; + color: black; + border: 1px solid black; + } + .cwmod-popup-btn:hover { text-decoration: none; } + .cwmod-popup-btn { display: none; text-align: center; color: #000033; text-decoration: underline; cursor: pointer; } + #cwmod-popup-reload { grid-area: reload; } + #cwmod-popup-cancel { grid-area: cancel; } + #cwmod-popup-hide { grid-area: hide; } + #cwmod-popup-text { grid-area: text; } + #cwmod-popup-text a { color: #123; } + #cwmod-popup-text a:hover { color: #246; } + + .reload #cwmod-popup { grid-template-areas: 'text text' 'reload cancel'; } + .reload #cwmod-popup-reload, .reload #cwmod-popup-cancel { display: block; } + .alert #cwmod-popup { grid-template-areas: 'text' 'hide'; } + .alert #cwmod-popup-hide { display: block; } + + .usn { user-select: none; } + .fs0 { font-size: 0; } + `; + addCSS(css); + body.append(` +
+
+
+
Обновить
+
Позже
+
Скрыть
+
+
+ `); + $(window).on('storage', function(e) { + if (e.originalEvent.key === 'cwmod_settings') { + const oldValue = JSON.parse(e.originalEvent.oldValue); + const newValue = JSON.parse(e.originalEvent.newValue); + Object.keys(newValue).forEach(function(key) { + if (thisPageSettings.indexOf(key) !== -1) { + if (oldValue[key] !== newValue[key]) { + let text = 'Настройки Варомода для этой страницы были изменены. Обновить страницу прямо сейчас, чтобы применить их?'; + showCwmodPopup('reload', text); + } + } + }); + } + }); + body.on('click', 'summary.cwmod-settings', function() { + const th = $(this); + const key = th.data('conf'); + setSettings(key, !th.parent().is('[open]')); + }); + body.on('change', 'select.cwmod-settings', function() { + const th = $(this); + const key = th.data('conf'); + let val = th.val(); + if (/^\d+$/.test(val)) val = Number(val); + setSettings(key, val); + $(`[data-show="${key}"]`).each(function() { + let cond = $(this).data('cond'); + const invert = /^!/.test(cond); + cond = cond.replace(/^!/, ''); + if (invert !== (cond === val)) $(this).show(); + else $(this).hide(); + }); + }); + body.on('change', 'input.cwmod-settings', function() { + const th = $(this); + const key = th.data('conf'); + const type = th.attr('type'); + let val; + if (type === 'checkbox') { + val = th.is(':checked'); + setSettings(key, val); + if (val) $(`[data-show="${key}"]`).show(); + else $(`[data-show="${key}"]`).hide(); + } + else if (type === 'range') { + val = th.val(); + setSettings(key, val); + } + }); + body.on('input', 'input.cwmod-settings', function() { + const th = $(this); + const key = th.data('conf'); + const type = th.attr('type'); + if (type === 'number') { + if (th.val()) setSettings(key, Number(th.val())); + } + else if (type === 'text') { + if (th.val()) setSettings(key, th.val()); + } + }); + body.on('click', '.cwmod-settings-set-default', function(e) { + e.preventDefault(); + const th = $(this); + const key = th.data('rel'); + const val = DEFAULTS[key]; + const input = $(`[data-conf="${key}"]`); + if (input.attr('type') === 'text') input.val(val); + setSettings(key, val); + }); + body.on('click', '.cwmod-settings-test-sound', function(e) { + e.preventDefault(); + const th = $(this); + const audio = new Audio(); + const volume = $(`[data-conf="${th.data('volume')}"]`).val(); + audio.src = getSettings(th.data('audio')); + audio.volume = volume; + audio.pause(); + audio.currentTime = 0; + audio.play(); + }); + if (globals.enableCatNotes) { + body.on('mouseenter', 'a:not(.headers)', function() { + const th = $(this); + const href = th.attr('href'); + if (!/cat\d+/.test(href)) return; + const catId = /\d+/.exec(href)[0]; + const note = getNoteByCatId(catId); + if (note) th.attr('title', note); + }); + } + body.on('mouseenter', '.headers', function() { + $(this).attr('title', 'Это раскрывающийся блок'); + }); + } + + function showCwmodPopup(type, text) { + $('#cwmod-popup-wrap').removeClass().addClass(type); + $('#cwmod-popup-text').html(text); + if ($('#cwmod-popup-wrap').css('display') === 'none') { + $('#cwmod-popup-wrap').css('display', 'flex'); + } + } + + function moonCalc() { + if (!$('#info').length) return; + addCSS(`.calc-error { color: darkred; }`); + $('#info').after('
'); + const infoObserver = new MutationObserver(function(mutations) { + mutations.forEach(function() { + const infoText = $('#info').text(); + if (!infoText.match('Дата')) { + $('#calc-age').empty(); + return; + } + const birthDateString = infoText.match(/\d{4}-\d\d-\d\d \d\d:\d\d/)[0].replace(' ', 'T'); + const nowDateString = dateToString(new Date); + const moonsNow = getMoonsFromDate(birthDateString, nowDateString); + let bornWord; + const sex = $('[src^="//e.catwar.net/avatar"]').first()[0].style.borderColor; + const isRegDate = (/регистрац/.test(infoText) && $('#age2_icon').length); + switch (sex) { + case 'pink': + bornWord = isRegDate ? 'Зарегистрировалась' : 'Родилась'; + break; + case 'blue': + bornWord = isRegDate ? 'Зарегистрировался' : 'Родилcя'; + break; + default: + bornWord = isRegDate ? 'Зарегистрировалось' : 'Родилoсь'; + } + const catTime = timestampToCatTime(Date.parse(birthDateString)); + const catTimeString = `${catTime.day} ${months[catTime.month]} ${catTime.year} года в ${leadingZero(catTime.hour)}:${leadingZero(catTime.minute)}`; + $('#calc-age').html(` +

Калькулятор возраста

+ +
лун +
${bornWord} ${catTimeString} по кошачьему времени. +

+ `); + updateMoonWord(moonsNow); + $('#calc-date').on('input', function() { + $('#calc-error-date').empty(); + const dateString = $('#calc-date').val(); + const date = Date.parse(dateString); + if (isNaN(date)) { + if (dateString.length) $('#calc-error-date').html('Ошибка!'); + return; + } + if (date < Date.parse(birthDateString)) { + $('#calc-error-date').html('Ошибка!'); + return; + } + const moons = getMoonsFromDate(birthDateString, dateString); + $('#calc-moons').val(moons); + updateMoonWord(moons); + }); + $('#calc-moons').on('input', function() { + $('#calc-error-moons').empty(); + const moons = Number($('#calc-moons').val()); + if (moons < 0 || isNaN(moons)) { + $('#calc-error-moons').html('Ошибка!'); + return; + } + $('#calc-date').val(getDateStringFromMoons(birthDateString, moons)); + updateMoonWord(moons); + }); + }); + }); + infoObserver.observe(document.querySelector('#info'), { + childList: true + }); + } + + function updateMoonWord(moons) { + $('#moon-word').html(declOfNum(moons, ['луна', 'луны', 'лун'])); + } + + function getMoonsFromDate(birthDateString, dateString) { + const birthday = Date.parse(birthDateString); + const date = Date.parse(dateString); + const moons = Math.floor(convertTime('ms d', date - birthday) / 4 * 10) / 10; + return moons; + } + + function getDateStringFromMoons(birthDateString, moons) { + const birthday = Date.parse(birthDateString); + const age = Math.round(convertTime('d ms', moons * 4)); + return dateToString(birthday + age); + } + + function changeAllBlogsPages() { + addBBcode(1); + let css = ` + #blogs-reload > a, .poll-hasAnswered1 { color: black; } + .tags-list { margin: 0; } + .tags-list > li { list-style-type: circle; } + #add-tags p, #add-tags li { line-height: 1.4em; } + .add-tag { + padding: 1px 5px; + background-color: rgba(255, 255, 255, 0.8); + color: black; + border-radius: 1rem; + white-space: nowrap; + cursor: pointer; + } + .add-tag::before { content: '+ '; color: #888; } + #search > p { margin-top: 0.5em; } + .comment-answer, .comment-cite { display: inline-block; margin-top: 5px; } + `; + if (globals.blogCiteButtonHide) { + css += `.comment-cite-wrap { display: none; }`; + } + if (isPage('blog')) { + if (globals.blogImgMaxWid) { + css += `img {max-width: ${globals.blogImgMaxWid}px}`; + } + } + if (isPage('sniff')) { + if (globals.sniffImgMaxWid) { + css += `img {max-width: ${globals.sniffImgMaxWid}px}`; + } + } + if (globals.blogAvatars) { + const width = globals.blogAvatarsSize; + const border = globals.blogAvatarsBorder; + const size = globals.blogAvatarsNoCrop ? 'contain' : 'cover'; + css += ` + .comment-avatar { + grid-area: avatar; + display: block; + width: ${width}px; + height: ${width}px; + ${border ? 'border: 1px solid black;' : ''} + background-size: ${size}; + background-repeat: no-repeat; + background-position: center; + } + .comment-info { grid-area: info; } + .comment-info + p { grid-area: p; } + .comment-text { grid-area: text; } + .comment-answer-buttons { grid-area: btns; } + .view-comment { + display: grid; + grid-template-areas: 'avatar info' 'avatar p' 'avatar text' 'btns btns'; + grid-template-columns: ${width + 2 * border}px auto;/*я пожалею об этом*/ + grid-column-gap: 10px; + } + `; + } + addCSS(css); + changeMainPage(); + changeViewPage(); + if (isPage('blogs?creation') || isPage('sniff?creation')) { + changeCreationPage(); + } + const viewObserver = new MutationObserver(function(mutations) { + mutations.forEach(function() { + if ($('#view').css('display') === 'none') { + hideCommentPreview(); + } + }); + }); + const creationObserver = new MutationObserver(function(mutations) { + mutations.forEach(function() { + if ($('#creation').css('display') === 'none') { + window.removeEventListener('beforeunload', beforeunload); + } + else { + changeCreationPage(); + } + }); + }); + viewObserver.observe($('#view')[0], { + attributes: true + }); + creationObserver.observe($('#creation')[0], { + attributes: true + }); + } + + function changeMainPage() { + $('#search > form > input[type="text"]').attr('placeholder', 'Поиск по ключевым словам'); + $('#search').append(`

`); + $('#search-ok').click(function() { + searchByTag($('#search-tag').val()); + }); + $('#search-tag').keypress(function(e) { + if (e.which == 13) { + searchByTag($('#search-tag').val()); + return false; + } + }); + } + + function changeViewPage() { + const p = $('#send_comment_form > p:last-child'); + p.prepend(` `); + $('#send_comment_form').after(` + + + `); + const WS = io.connect(window.location.origin, { + path: '/ws/blogs/socket.io' + , reconnectionDelay: 10000 + , reconnectionDelayMax: 20000 + }); + WS.on('creation preview', function(data) { + $('#comment-preview-div').html(data).show(); + $('#comment-preview-hide').show(); + }); + $('#comment-preview').click(function() { + WS.emit("creation preview", $('#comment').val()); + }); + $('#send_comment_form [type="submit"]').click(hideCommentPreview); + $('#comment-preview-hide').click(function(e) { + e.preventDefault(); + hideCommentPreview(); + }); + if (globals.blogCommentSmiles) { + p.append(` + + + + + + + + + + `); + } + if ($('#comment').length) { + const commentObserver = new MutationObserver(function(mutations) { + mutations.forEach(changeComments); + }); + commentObserver.observe(document.querySelector('#view_comments'), { + childList: true + }); + } + let selectionInfo = {}; + $('#view_comments').on('mouseup touchend', function() { + if (globals.blogCiteButtonHide) $('.comment-cite-wrap').hide(); + const sel = window.getSelection(); + if (!sel.isCollapsed && sel.anchorNode && sel.focusNode) { + if (sel.anchorNode.parentElement.classList.contains('.comment-cite')) return; + else selectionInfo = {}; + const anchor = { + elem: sel.anchorNode + , isComment: false + , id: 0 + }; + const focus = { + elem: sel.focusNode + , isComment: false + , id: 0 + }; + while (anchor.elem = anchor.elem.parentElement) { + if (anchor.elem.classList.contains('comment-text')) anchor.isComment = true; + if (anchor.elem.dataset.id) { + anchor.id = anchor.elem.dataset.id; + break; + } + } + while (focus.elem = focus.elem.parentElement) { + if (focus.elem.classList.contains('comment-text')) focus.isComment = true; + if (focus.elem.dataset.id) { + focus.id = focus.elem.dataset.id; + break; + } + } + if (anchor.isComment && focus.isComment && anchor.id === focus.id) { + selectionInfo.text = sel.toString(); + selectionInfo.id = parseInt(anchor.id, 10); + $(`[data-id="${selectionInfo.id}"] .comment-cite-wrap`).show(); + } + } + }); + $('#view_comments').on('click', '.comment-answer', function(e) { + e.preventDefault(); + answerComment($(this).parent().parent(), false); + }); + $('#view_comments').on('click', '.comment-cite', function(e) { + e.preventDefault(); + answerComment($(this).parent().parent().parent(), true, selectionInfo); + }); + } + + function hideCommentPreview() { + $('#comment-preview-hide').hide(); + $('#comment-preview-div').empty().hide(); + } + + function changeComments() { + addAnswerButtons(); + if (globals.blogAvatars) { + addCommentAvatars(); + } + } + + function addCommentAvatars() { + $('.view-comment:not(.has-avatar)').each(function() { + $(this).prepend('
'); + const commentId = $(this).data('id'); + const avatarSelector = `.view-comment[data-id="${commentId}"] > .comment-avatar`; + const avatarDiv = $(avatarSelector); + const author = $(this).children('.comment-info').children('.author'); + const catId = author.length ? getNumber(author.attr('href')) : 0; + // const storedAvatar = window.sessionStorage.getItem('avatar' + catId); + const storedAvatarJPG = '//e.catwar.net/avatar/' + catId + '.jpg' + const storedAvatarPNG = '//e.catwar.net/avatar/' + catId + '.png' + const storedAvatarGIF = '//e.catwar.net/avatar/' + catId + '.gif' + if (catId === 0) { + avatarDiv.css('background-image', `url(//e.catwar.net/avatar/0.jpg)`); + } + else { + avatarDiv.css('background-image', `url(${storedAvatarJPG}), url(${storedAvatarPNG}),url(${storedAvatarGIF}) `); + } + $(this).addClass('has-avatar'); + }); + } + + function addAnswerButtons() { + const answerButton = isDesktop ? 'Ответить' : '🗨'; + const citeButton = isDesktop ? 'Цитировать' : '💬'; + const addAnswer = globals.blogAnswerButton; + const addCite = globals.blogCiteButton; + $('.view-comment:not(.has-buttons)').each(function() { + let html = `

`; + const notMyComment = $(this).children('.comment-info').children('[data-candelete="0"]').css('display') !== 'none'; + if (addAnswer && notMyComment) { + html += `${answerButton}`; + } + if (addCite) { + html += ''; + if (addAnswer && notMyComment) html += ' | ' + html += `${citeButton}`; + } + $(this).append(html).addClass('has-buttons'); + }); + } + + function answerComment(comment, cite, selectionInfo) { + const commentInfo = comment.children('.comment-info'); + const num = commentInfo.children('b').children('.num').text(); + let author; + if (commentInfo.children('.author').length) author = '[link' + getNumber(commentInfo.children('.author').attr('href')) + ']'; + else author = '[b][code]' + commentInfo.children('span').first().text() + '[/code][/b]'; + let quote; + if (cite) { + let text; + if (selectionInfo.id === comment.data('id')) text = selectionInfo.text; + else text = bbencode(comment.children('.comment-text').children('.parsed').html()); + const date = findDate(commentInfo.html()); + quote = `[table][tr][td][size=10][i]Цитата:[/i] [b]#${num}[/b] ${date} @ ${author}[/size][/td][/tr][tr][td][table=0][tr][td]  [/td][td]${text}[/td][/tr][/table][/td][/tr][/table]`; + } + else { + quote = `${author} (#${num}), `; + } + const textarea = $('#comment'); + textarea.val(textarea.val() + quote); + textarea.focus(); + } + + function changeCreationPage() { + if (globals.creationAlert) addSaveAlert(); + if (isPage('blogs?creation', true) || isPage('sniff?creation', true)) { + const blogsTags = ` +

+ Добавить теги +

+ информация + новичкам + племенной блог +

+

+ поздравление + день рождения + годовщина + самопоздравление +

+

+ писательское творчество + стихотворения + рисунки + фотографии + рукоделие + журнал +

+

+ неграмотно + мало + скопировано + опасно для глаз +

+

сходка

+

конкурс

+
+ `; + const sniffTags = ` +
+ Добавить теги +

Основано на блоге Ликбез. Инструкция по выбору тегов там, а это кнопки для тех, кому лень писать их руками.

+

изображение

+ +

Поднюхано Замышеголовили

+ +

Флудильня

+ +

Общие теги:

+ + + Теги вселенных и фракций +

Мёртвые: + Звёздное племя + Сумрачный лес + Душевая +

+

Озёрная вселенная: + Грозовое племя + племя Ветра + Речное племя + племя Теней + клан Падающей Воды + Северный клан + Домашние + одиночки ОВ + Озёрная вселенная +

+

Морская вселенная: + Морское племя + племя Солнца + племя Луны + одиночки МВ + Морская вселенная +

+

Вселенная творцов: + племя Неразгаданных Тайн + Крылатое племя + Сплочённый Союз Свободных Республик + клан Ледяного Дождя + Эльфийские земли + Чернолесье + одиночки ВТ + Вселенная творцов +

+
+ + `; + const tagsInput = $('#creation-tags'); + if (!$('#add-tags').length) { + if (isPage('blogs')) tagsInput.parent().after(blogsTags); + else if (isPage('sniff')) tagsInput.parent().after(sniffTags); + $('.add-tag').click(function() { + let tags = tagsInput.val(); + if (tags) tags += ', '; + tags += $(this).text(); + tagsInput.val(tags); + tagsInput.focus(); + }); + } + const creationInput = $('#creation-text'); + if (creationInput.length) { + const key = isPage('blogs') ? 'cwm_saved_blog' : 'cwm_saved_sniff'; + const oldText = window.localStorage.getItem(key); + if (oldText && !creationInput.val()) creationInput.val(oldText); + creationInput.on('input', function() { + window.localStorage.setItem(key, creationInput.val()); + }); + } + } + } + + function searchByTag(tag) { + window.location.href = window.location.href.split('?')[0] + '?tag=' + tag; + } + + function changeCatPage() { + addCSS(`#info { color: black; } #age_icon, #age2_icon, #act_icon, img[src^="medal"] { cursor: pointer; }`); + moonCalc(); + if ($('[src="img/icon_kraft.png"]').length) { + if (globals.catAddFightLevel) { + const kraftArr = ['блоха', 'котёночек', 'задира', 'гроза детской', 'страх барсуков', 'победитель псов', 'защитник племени', 'великий воин', 'достоин Львиного племени', 'идеальная']; + const b = $('[src="img/icon_kraft.png"]').parent().siblings().children('b'); + b.append(' (' + kraftArr.indexOf(b.text()) + ')'); + } + } + if (globals.enableCatNotes) { + let p, catId; + if (isDesktop) { + p = $('#branch > p').first(); + catId = p.data('cat'); + $('#branch').prepend(``); + } + else { + p = $('#site_table > p').first(); + catId = p.data('cat'); + p.append(``); + } + const oldText = getNoteByCatId(catId); + const textarea = $('#note'); + if (oldText && !textarea.val()) textarea.val(oldText); + const savedNotes = JSON.parse(window.localStorage.getItem('cwmod_notes') || '{}'); + textarea.on('input', function() { + savedNotes[catId] = textarea.val(); + if (!savedNotes[catId]) delete savedNotes[catId]; + saveData('notes', savedNotes); + }); + } + const medals = $('img[src^="medal"]'); + if (medals.length) { + let lastpic = false; + medals.last().after(``); + const info = $('#infomedal'); + $.getJSON('https://porch.website/get?file=medals&type=json', function(data) { + let medalsList = data.data; + medals.click(function() { + const picURL = $(this).attr('src'); + const pic = getNumber(picURL); + if (pic === lastpic) { + info.hide(200); + lastpic = ''; + } + else { + if (info.css('display') === 'none') info.show(200); + lastpic = pic; + const medalInfo = medalsList[pic]; + if (medalInfo) { + let status = medalInfo[1]; + let transfer = medalInfo[2]; + let getting = medalInfo[3]; + let whose = medalInfo[4]; + let about = `
${$(this).attr('alt')}`; + if (!(status || transfer || getting || whose === 'Сайтовая')) about += '
Нет информации'; + else { + about += ''; + if (status) { + let color; + if (status === 'выдаётся') color = 'green'; + else if (status === 'не выдаётся') color = '#ba0000'; + else color = 'gray'; + about += `
Статус: ${status}`; + } + if (transfer === 'возможен') about += `
Перенос на другого персонажа возможен`; + else if (transfer === 'невозможен') about += `
Перенос на другого персонажа невозможен`; + about += '
'; + if (getting) about += `
${getting}`; + if (whose === 'Сайтовая') about += `
Это сайтовая медаль.`; + } + info.html(`Медаль № ${pic}${about}`); + } + else { + info.html(`Медаль № ${pic}
${$(this).attr('alt')}
Нет информации`); + } + } + }); + }); + } + } + + function changeChatPage() { + addCSS(`.tabName, #confirm_text, .mess_tr[style^="background: rgb(255, 204, 153)"] { color: black; } .mess_tr[style^="background: rgb(255, 204, 153)"] a { color: #003; }`); + addBBcode(1); + const key = 'cwmod_saved_chat'; + const oldText = window.localStorage.getItem(key); + if (oldText) $('#mess').html(oldText); + $('#mess').on('input', function() { + window.localStorage.setItem(key, $('#mess').html()); + }); + const observer = new MutationObserver(function(mutations) { + mutations.forEach(function() { + if (!$('#mess').html()) window.localStorage.removeItem(key); + }); + }); + observer.observe(document.querySelector('#mess'), { + childList: true + }); + } + + function changeCW3Page() { + const menu = $('.small').first(); + //const isMale = /Мой кот/.test(menu.text()); + const target = globals.newPageMenu ? 'target="_blank"' : ''; + const menuButtons = {}; + let smenuAbout = globals.menuAbout + let smenuIndex = globals.menuIndex + let smenuTop = globals.menuTop + let smenuChat = globals.menuChat + let smenuLS = globals.menuLS + let smenuLS0 = globals.menuLS0 + let smenuBlogs = globals.menuBlogs + let smenuSniff = globals.menuSniff + let smenuSett = globals.menuSett + let smenuMobile = globals.menuMobile + menuButtons[smenuAbout] = `Об игре`; + //menuButtons[smenuIndex] = `${isMale ? 'Мой кот' : 'Моя кошка'}`; + menuButtons[smenuTop] = `СИ`; + //menuButtons[smenuChat] = `Чат`; + //menuButtons[smenuLS] = `ЛС`; + menuButtons[smenuLS0] = `Памятка`; + menuButtons[smenuBlogs] = `Блоги`; + menuButtons[smenuSniff] = `Лента`; + menuButtons[smenuSett] = `Настройки`; + menuButtons[smenuMobile] = `Сменить версию`; + if (globals.menuAbout) { + $('.small').append('| Об игре '); + } + if (globals.menuTop) { + $('.small').append('| СИ '); + } + if (globals.menuLS0) { + $('.small').append('| Памятка '); + } + if (globals.menuBlogs) { + $('.small').append('| Блоги '); + } + if (globals.menuSniff) { + $('.small').append('| Лента '); + } + if (globals.menuSett) { + $('.small').append('| Настройки '); + } + if (globals.menuMobile) { + $('.small').append('| Сменить версию '); + } + Object.keys(menuButtons).forEach(function(key) { + if (globals.key) { + menu.append(' | ' + menuButtons[key]); + } + }); + let css = ''; + if (globals.quietLouder) { + css += `.vlm0, .vlm1, .vlm2, .vlm3, .vlm4 {font-size: 12px;}`; + } + if (globals.loudQuieter) { + css += `.vlm6, .vlm7, .vlm8, .vlm9, .vlm10 {font-size: 14px;}`; + } + if (globals.putCatsDown) { + css += `.d, .d div {background-position: left bottom;}`; + } + if (globals.fightPanelHeight) { + const height = globals.fightPanelHeight; + if (height !== 70) { + css += ` + #fightPanel { height: max-content; } + #fightLog { overflow-y: auto; min-height: 70px; height: unset !important; max-height: ${height}px; } + `; + } + } + if (globals.realism) { + css += `.d {background-image: url(https://porch.website/cwmod/cat.png) !important;}`; + } + if (globals.cw3CageGrid) { + css += `.cage {box-shadow: inset 1px 1px 1px rgba(0, 0, 0, 0.33), inset -1px -1px 1px rgba(255, 255, 255, 0.33);}`; + } + if (globals.deadNotTransperent) { + css += `.cat > div {opacity: 1 !important;}`; + } + if (globals.cw3HideSky) { + css += `#tr_sky {display: none;}`; + } + if (globals.alwaysDay) { + css += `#cages_div {opacity: 1 !important;}`; + } + if (globals.noHistoryUnderline) { + css += `#ist > a {text-decoration: none;}`; + } + if (globals.compact) { + css += ` + #app { width: 100%; height: 1000px; } + #main_table { width: 100%; max-width: unset; height: 100%; border-collapse: collapse; background: none !important; } + #main_table > tbody { display: grid; grid-row-gap: 5px; grid-template-columns: 1fr auto 1fr; } + #app > span.small { grid-area: links; position: fixed; z-index: 1; left: 5px; top: 5px; } + #tr_chat { grid-area: chat; } + #tr_actions { grid-area: actions; overflow: auto; background: none !important; } + #tr_tos { grid-area: tos; background: none !important; } + #tr_sky { display: none; } + #tr_field { grid-area: field; background: black; } + #tr_mouth { grid-area: mouth; overflow: auto; background: none !important; } + #tr_actions > td, #tr_mouth > td, #info_main > tbody > tr > td { background-color: #ffdead; } + #tr_info { grid-area: info; max-height: 1000px; overflow-x: hidden; overflow-y: auto; } + #info_main { background: none !important; } + #info_main > tbody > tr > td, #tr_mouth > td > *, #tr_actions > td > *, #tr_chat { padding: 5px; } + #block_mess { margin: 0; padding: 8px 0; } + .infos { width: 100%; max-width: max-content; } + #itemList { width: 400px; max-height: 75px; overflow-y: auto; } + #thdey > br { display: none; } + #chat_form { display: grid; grid-row-gap: 5px; margin: 10px 5px 5px 5px; } + .chat_text { width: unset !important; } + #chat_msg { width: auto !important; height: 350px; padding: 2px; } + #volume + b { display: block; font-size: 0.75em; } + #app > p:not(#error) { visibility: hidden; } + #black { visibility: visible; color: white; } + #black::before { content: 'ТБ: '; } + .small { padding: 0 5px; background-color: #ffdead; font-size: 15px; } + #history_block > div { visibility: hidden; } + #location { visibility: visible; position: fixed; right: 15px; top: 5px; z-index: 5; padding: 0 5px; font-weight: bold; font-size: 1.5em; background-color: #ffdead; } + h2 { font-size: 1.2em; } + `; + const splitInfo = globals.compactSplitInfo; + const sticky = globals.compactSplitInfoHeaders; + if (isDesktop) { + css += ` + #chat_form { grid-template-columns: auto auto; } + #info_main > tbody > tr { + display: grid; + max-height: 1000px; + grid-template-areas: 'parameter' 'history' 'family'; + grid-template-rows: ${splitInfo ? '252px 1fr 1fr' : 'auto auto auto'}; + grid-row-gap: 5px; + } + #family.infos, #history.infos, #parameter.infos { + overflow: auto; + } + #family.infos { grid-area: family; } + #history.infos { grid-area: history; } + #parameter.infos { grid-area: parameter; } + `; + } + else { + css += ` + #chat_form { grid-template-columns: auto auto auto; } + #info_main > tbody { + display: grid; + max-height: 1000px; + grid-template-areas: 'parameter' 'history' 'family'; + grid-template-rows: ${splitInfo ? '252px 1fr 1fr' : 'auto auto auto'}; + grid-row-gap: 5px; + } + #info_main > tbody > tr:nth-child(1) { + grid-area: parameter; + overflow: auto; + } + #info_main > tbody > tr:nth-child(2) { + grid-area: history; + overflow: auto; + } + #info_main > tbody > tr:nth-child(3) { + grid-area: family; + overflow: auto; + } + `; + } + if (splitInfo) { + css += ` + #info_main > tbody > tr { + grid-template-rows: 252px 1fr 1fr; + } + `; + } + else { + css += ` + #info_main > tbody { + grid-template-rows: auto auto auto; + } + `; + } + const hideHeaders = (globals.compactHideHeaders); + if (hideHeaders) { + css += ` + #info_main h2 { visibility: hidden; } + #parameters-alert { visibility: visible; } + `; + } + else if (splitInfo && sticky) { + css += `#info_main h2 { position: sticky; }`; + } + const swap = (globals.compactSwapSides); + const chatup = (globals.compactChatOnTop); + if (swap && chatup) { + css += `#main_table > tbody { grid-template-areas: 'info field tos' 'info field chat' 'info field actions' 'info field mouth'; grid-template-rows: 25px 425px 267.5px 267.5px; }`; + } + else if (swap && !chatup) { + css += `#main_table > tbody { grid-template-areas: 'info field tos' 'info field actions' 'info field mouth' 'info field chat'; grid-template-rows: 25px 267.5px 267.5px 425px; }`; + } + else if (!swap && chatup) { + css += `#main_table > tbody { grid-template-areas: 'tos field info' 'chat field info' 'actions field info' 'mouth field info'; grid-template-rows: 25px 425px 267.5px 267.5px; }`; + } + else { + css += `#main_table > tbody { grid-template-areas: 'tos field info' 'actions field info' 'mouth field info' 'chat field info'; grid-template-rows: 25px 267.5px 267.5px 425px; }`; + } + if (globals.compactRadiusEdges) { + css += `.small, #tos, #tr_chat, #tr_actions > td, #tr_mouth > td, #location, #tr_field, #parameter, #cages_div { border-radius: 15px; }`; + if ($('#app').data('mobile') === 1) css += `#info_main > tbody > tr { border-radius: 15px; }`; + else css += `#family, #history{ border-radius: 15px; }`; + } + } + const styleTemplate = ` + #error { background-color: var(--error-bg) !important; color: var(--error-color) !important; } + #main_table { background: var(--main-bg) } + #tr_field { background: black !important; } + hr { border: none; border-bottom: 1px solid var(--hr-color) !important; } + body { background-color: var(--body-bg) !important; color: var(--text-color) !important; } + a, a:hover { color: var(--a-color); } + #tr_chat, #tr_actions, #tr_mouth, #info_main { background: none !important; } + .small, #app > p:not(#error), #info_main > tbody > tr > td, #history_block > div, #tr_mouth > td, #tr_actions > td, #location, #black, #tr_chat { background-color: var(--table-bg) !important; color: var(--text-color) !important; border: none !important; } + .myname { background: var(--myname-bg) !important; color: var(--myname-color) !important; } + input, select { background-color: var(--input-bg) !important; color: var(--input-color) !important; border: 1px solid var(--input-border-color) !important; } + .ui-slider { background: var(--input-bg) !important; border: 1px solid var(--input-border-color) !important; } + .ui-slider .ui-slider-handle { background: var(--handle-bg) !important; border: 1px solid var(--input-border-color) !important; } + .hotkey { background: white !important; } + .move_name, #fightLog, #timer, .hotkey { color: #000 !important; } + `; + var theme = 0 + if (globals.cwmodTheme === 0) { + theme = "default" + } + else if (globals.cwmodTheme === 1) { + theme = "dark_grey" + } + else if (globals.cwmodTheme === 2) { + theme = "black_glass" + } + const themes = { + 'dark_grey': `:root { --table-bg: #222; --error-bg: #3c1e1e; --error-color: #ccc; --main-bg: #222; --hr-color: #282828; --body-bg: #191919; --text-color: #b2b2b2; --a-color: #b2b2b2; --myname-color: black; --myname-bg: #a73; --input-bg: #111; --handle-bg: #383838; --input-color: #aaa; --input-border-color: #282828; }` + , 'black_glass': `:root { --table-bg: #000d; --error-bg: #3c1e1e; --error-color: #ccc; --main-bg: none; --hr-color: #000; --body-bg: #4d4e4f; --text-color: #b2b2b2; --a-color: #b2b2b2; --myname-color: black; --myname-bg: #a73; --input-bg: #111; --handle-bg: #333; --input-color: #ccc; --input-border-color: #000; }` + }; + if (theme !== 'default') { + css += themes[theme] + styleTemplate; + } + addCSS(css); + if (globals.cw3Bkg !== 0) { + var bgSize = 0; + if (globals.cw3BkgSize === 0) { + bgSize = "auto" + } + else if (globals.cw3BkgSize === 1) { + bgSize = "cover" + } + var bgPos = 0; + if (globals.cw3BkgPos === 0) { + bgPos = "top left" + } + else if (globals.cw3BkgPos === 1) { + bgPos = "top center" + } + else if (globals.cw3BkgPos === 2) { + bgPos = "top right" + } + else if (globals.cw3BkgPos === 3) { + bgPos = "center left" + } + else if (globals.cw3BkgPos === 4) { + bgPos = "center" + } + else if (globals.cw3BkgPos === 5) { + bgPos = "center right" + } + else if (globals.cw3BkgPos === 6) { + bgPos = "bottom left" + } + else if (globals.cw3BkgPos === 7) { + bgPos = "bottom center" + } + else if (globals.cw3BkgPos === 8) { + bgPos = "bottom right" + } + addCSS(`body { background-size: ${bgSize}; background-position: ${bgPos}; }`); + if (globals.cw3Bkg === 1) { + body.css('background-image', $('#cages_div').css('background-image')); + const cagesDivObserver = new MutationObserver(function(mutations) { + mutations.forEach(function() { + body.css('background-image', $('#cages_div').css('background-image')); + }); + }); + cagesDivObserver.observe($('#cages_div')[0], { + attributes: true + }); + const pageObserver = new MutationObserver(function(mutations) { + mutations.forEach(function() { + if (body.text() === 'Вы открыли новую вкладку с Игровой, поэтому старая (эта) больше не работает.') { + body.css('background-image', 'none'); + cagesDivObserver.disconnect(); + pageObserver.disconnect(); + } + }); + }); + pageObserver.observe(document.body, { + childList: true + }); + } + else { + addCSS(`body { background-image: url(${globals.cw3BkgImg}); }`); + } + } + if (globals.cw3SnowWeather) { + const snowSVG = [ + ` + ` + , ` + ` + , ` + ` + ]; + let isSnow = false; + let sky = null; + + function snow() { + console.log("Создаем снежинку"); + const randomSnowflake = snowSVG[Math.floor(Math.random() * snowSVG.length)]; + const snowflakeDiv = $('
'); + snowflakeDiv.html(randomSnowflake); + let randomX = Math.random() * window.innerWidth; + let randomY = -20; + let angle = Math.random() * (25 - 15) + 15; + let angleRad = angle * Math.PI / 180; + let animationDuration = 8 + Math.random() * 4; + let rotationSpeed = Math.random() * 2; + snowflakeDiv.css({ + position: 'absolute' + , left: randomX + 'px' + , top: randomY + 'px' + , transform: `rotate(${Math.random() * 360}deg)` + , width: '20px' + , height: '20px' + , backgroundSize: 'cover' + , opacity: 1 + }); + snowflakeDiv.animate({ + top: window.innerHeight + 20 + , left: randomX + window.innerHeight * Math.tan(angleRad) + , transform: `rotate(${rotationSpeed * 360 * animationDuration}deg)` + , opacity: 0 + }, animationDuration * 1000, 'linear', function() { + snowflakeDiv.fadeOut(1000, function() { + snowflakeDiv.remove(); + }); + }); + $('body').append(snowflakeDiv); + } + + function runSnow() { + console.log("Запускаем runSnow"); + snow(); + setTimeout(runSnow, 250); + } + const skyObserver = new MutationObserver(function(mutations) { + sky = $('#sky').css('background-image').match(/\d+/g)[1]; + console.log("sky:", sky); + if (sky === '7' || sky === '8') { + if (!isSnow) { + console.log("Начинаем снегопад"); + isSnow = true; + setTimeout(runSnow, 250); + } + } + else { + console.log("Снегопад прекращается"); + isSnow = false; + } + }); + const mainTableObserver = new MutationObserver(function(mutations) { + mutations.forEach(function() { + if (!$('#snow').length) { + $('body').prepend('
'); + } + skyObserver.observe($('#sky')[0], { + attributes: true + }); + mainTableObserver.disconnect(); + }); + }); + mainTableObserver.observe($('#main_table > tbody')[0], { + childList: true + }); + let csssnow = `` + $('head').append(csssnow); + } + const cagesObserver = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + const node = mutation.addedNodes[0]; + if (!node) return; + if (node.nodeType !== Node.ELEMENT_NODE) return; + if (isDesktop && globals.compact) { + if (node.classList.contains('catWithArrow')) { + let padding = 0; + $('#cages').children('tbody').children('tr').last().children().each(function() { + const tooltip = $(this).find('.cat_tooltip'); + if (tooltip.length && tooltip.height() > padding) { + padding = tooltip.height(); + } + }); + padding += 50; + body.css('padding-bottom', padding + 'px') + } + } + if (globals.putCatsDown && globals.putArrowsDown) { + let arrow; + if (node.classList.contains('catWithArrow')) { + arrow = $(node).children('div').children('.arrow'); + } + else if (mutation.target.classList.contains('catWithArrow')) { + arrow = $(node).children('.arrow'); + } + else return; + if (!arrow.length) return; + const oldTop = Number(getNumber(arrow.css('top'))); + const catHeight = Number(getNumber(arrow.children('table').css('width'))); + const newTop = oldTop + 150 - catHeight * 1.5; + arrow.css('top', newTop + 'px'); + } + }); + }); + $('.cage_items').each(function() { + cagesObserver.observe(this, { + childList: true + , subtree: true + }); + }); + if (globals.actionTitle || globals.actionEndAlert) { + const changeTitle = globals.actionTitle; + const blurOnly = globals.actionEndAlertBlurOnly; + const audio = new Audio(); + audio.src = globals.actionEndAlertLink; + audio.volume = globals.actionEndAlertVol; + let isWindowActive = true; + window.addEventListener('focus', function(event) { + isWindowActive = true; + if (blurOnly) { + audio.pause(); + audio.currentTime = 0; + } + }); + window.addEventListener('blur', function(event) { + isWindowActive = false; + }); + const deysObserver = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + if (mutation.target.id === 'block_mess' && !$('#sek').length) { + if (changeTitle) document.title = 'Игровая / CatWar'; + } + else if (mutation.target.id === 'sek' && mutation.addedNodes.length) { + const timeLeft = $('#sek').text(); + if (changeTitle) document.title = timeLeft; + if (globals.actionEndAlert) { + const alertTime = new RegExp('^' + globals.actionEndAlertTime + ' .?с'); + if (alertTime.test(timeLeft) && (!isWindowActive || !blurOnly || $('#cwmod-popup-wrap').css('display') === 'flex')) { + audio.play(); + } + } + } + }); + }); + deysObserver.observe($('#block_mess')[0], { + childList: true + , subtree: true + }); + } + const DiseasesLevels = {}; + DiseasesLevels.dirt = ['грязные лапы', 'грязевые пятна', 'клещи', 'блохи']; + DiseasesLevels.wound = ['царапины', 'лёгкие раны', 'глубокие раны', 'смертельные раны']; + DiseasesLevels.drown = ['cсадины', 'лёгкие порезы', 'глубокие царапины', 'смертельные травмы']; + DiseasesLevels.trauma = ['ушибы', 'лёгкие переломы', 'сильные переломы', 'смертельные переломы']; + let catInfos = []; + body.on('mouseenter', '.cat', function() { + const cat = $(this); + const catEl = cat.find('.d'); + if (!catEl.length) return; + if (globals.catTooltipInfo) { + const html = cat.html(); + const link = cat.find('a').first(); + const catName = link.text(); + const catId = /\d+/.exec(link.attr('href'))[0]; + const sex = (/Его запах/.exec(html)); + const catElHtml = catEl.parent().html(); + let height = catEl.css('background-size'); + if (height === '101%') height += ' (надута)'; + const image = /composited\/([\da-f]{16})\.png/.exec(catElHtml)[1]; + let dirt = /dirt\/(\d)/.exec(catElHtml); + let wound = /wound\/(\d)/.exec(catElHtml); + let drown = /drown\/(\d)/.exec(catElHtml); + let trauma = /trauma\/(\d)/.exec(catElHtml); + wound = wound ? Number(wound[1]) : false; + dirt = dirt ? Number(dirt[1]) : false; + drown = drown ? Number(drown[1]) : false; + trauma = trauma ? Number(trauma[1]) : false; + const poisoning = (/poisoning/.exec(catElHtml)); + const disease = (/disease/.exec(catElHtml)); + const beddings = (/costume\/295\.png/.exec(catElHtml)); + let text = `
`; + text += `${catName} (ID ${catId})
Окрас`; + text += `
Рост: ${height}`; + text += dirt ? `
Грязь ${dirt} степени (${DiseasesLevels.dirt[dirt - 1]})` : ''; + text += beddings ? `
Убирает подстилки` : ''; + text += (wound || drown || trauma || poisoning || disease) ? `
Болезни:` : `
Здоров` + (sex ? '' : 'а'); + text += wound ? `
— Раны ${wound} степени (${DiseasesLevels.wound[wound - 1]})` : ''; + text += drown ? `
— Травмы от утопления ${drown} степени (${DiseasesLevels.drown[drown - 1]})` : ''; + text += trauma ? `
— Переломы ${trauma} степени (${DiseasesLevels.trauma[trauma - 1]})` : ''; + text += poisoning ? `
— Отравление` : ''; + text += disease ? `
— Насморк` : ''; + text += `
`; + catInfos[catId] = text; + if (!cat.find('.show-more').length) cat.find('.online').before(`Подробнее
`); + else cat.find('.show-more').data('id', catId); + } + if (globals.shortInventory) { + let things = {}; + let cats = []; + let mouth = cat.find('.mouth:not(.new-mouth)').first(); + if (mouth.length) { + let newMouth = mouth.siblings('.new-mouth'); + if (!newMouth.length) { + mouth.after('
    '); + newMouth = mouth.siblings('.new-mouth'); + } + else newMouth.show(); + let mouthThings = mouth.children('li'); + mouthThings.each(function() { + const li = $(this); + if (li.find('div').length) { + cats.push(li.html()); + } + else { + let thingId = /\d+/.exec(li.children('img').attr('src'))[0]; + if (li.text() !== '') { + things[thingId] = Number(li.text().slice(1)); + } + else if (things[thingId]) { + things[thingId]++; + } + else things[thingId] = 1; + } + }); + let newMouthHtml = ''; + Object.keys(things).forEach(function(key) { + let len = things[key] > 1 ? `×${things[key]}` : ''; + newMouthHtml += `
  1. ${len}
  2. `; + }); + cats.forEach(function(cat) { + newMouthHtml += `
  3. ${cat}
  4. `; + }); + mouth.hide(); + newMouth.html(newMouthHtml); + } + else cat.find('.new-mouth').hide(); + } + }); + if (globals.catTooltipInfo) { + body.on('click', '.show-more', function(e) { + e.preventDefault(); + showCwmodPopup('alert', catInfos[$(this).data('id')]); + }); + } + if (globals.paramInfo) { + $('#parameter').children('h2').first().append(' +'); + $('#parameters-alert').click(function() { + let params = ['Сонливость', 'Голод', 'Жажда', 'Нужда', 'Здоровье', 'Чистота']; + let text = '
    Параметры
    '; + ['dream', 'hunger', 'thirst', 'need', 'health', 'clean'].forEach(function(param, i) { + const isDream = (param === 'dream') + , isHunger = (param === 'hunger') + , isThirst = (param === 'thirst') + , isNeed = (param === 'need') + , isClean = (param === 'clean'); + text += `
    ${params[i]}
    `; + let red = parseInt($('#' + param).find("td").last()[0].style.width); + if (Number.isNaN(red)) text += 'Ошибка, попробуйте снова'; + else if (red === 0) { + if (isDream && $('.dey[data-id="1"]').length) text += `100 %
    10 c сна`; + else if (isThirst && $('.dey[data-id="5"]').length) text += `100 %
    До 30 c питья`; + else if (isNeed && $('.dey[data-id="4"]').length) text += `100 %
    10 c дел в грязном месте`; + else text += '100 %'; + } + else if (red === 150) { + text += '0 %'; + if (isDream) text += `
    ${secToTime(150 * 20)} сна или более`; + if (isThirst) text += `
    ${secToTime(150 * 60 - 30)} питья или более`; + if (isNeed) text += `
    ${secToTime(150 * 30 - 10)} дел в грязном месте или более`; + } + else { + const percent = isClean ? Math.floor((150 - red) / 1.5) : Math.round((150 - red) / 1.5 * 100) / 100; + text += `${percent}% (−${red}px)`; + if (isDream) { + const maxTime = red * 20 + 10; + text += `
    До ${secToTime(maxTime)} сна`; + } + else if (isHunger) { + const time = Math.ceil((100 - percent) * 9 / 100) * 15; + text += `
    ${secToTime(time)} поглощения пищи`; + } + else if (isThirst) { + const maxTime = red * 60 + 30; + text += `
    До ${secToTime(maxTime)} питья`; + } + else if (isNeed) { + const maxTime = red * 30 + 10; + text += `
    До ${secToTime(maxTime)} дел в грязном месте`; + } + else if (isClean && red <= 75) { + text += `
    Вылизываться ${secToTime((100 - percent) * 100)}`; + } + } + }); + showCwmodPopup('alert', text); + }); + } + } + + function snow() { + const id = Date.now() + , flake = 'https://porch.website/cwmod/snow/' + Math.ceil(Math.random() * 20) + '.png' + , pos_x = Math.ceil(Math.random() * 98) + , end_x = pos_x + Math.floor(Math.random() * 31) - 15 + , deg = Math.ceil(Math.random() * 358) + , width = Math.ceil(Math.random() * 45) + 5 + , img = ` + ` + , timefall = Math.ceil(Math.random() * 12000) + 5000; + $("#snow").append(img); + $(`#snow_${id}`).animate({ + top: '120%' + , left: end_x + '%' + }, timefall, function() { + $(`#snow_${id}`).empty().remove(); + }); + } + + function changeFaePage() { + if (globals.enableFaeNotes) { + const observer = new MutationObserver(function(mutations) { + mutations.forEach(function() { + $('.cat_span').each(function() { + const t = $(this); + const catId = getNumber(t.children().first().attr('href')); + const noteText = getNoteByCatId(catId); + if (noteText) { + t.append(` `); + $('#' + catId).text(noteText); + } + }); + }); + }); + observer.observe(document.querySelector('#friendList'), { + childList: true + }); + } + if (globals.enableCatNotes) { + $(isDesktop ? '#branch' : '#site_table').append(`Список заметок
    `); + let html = ''; + const notes = JSON.parse(window.localStorage.getItem('cwmod_notes') || '{}'); + Object.keys(notes).forEach(function(catId) { + html += `${catId}${notes[catId]}`;; + }); + if (html.length) { + $(isDesktop ? '#branch' : '#site_table').append(`${html}
    IDИмяЗаметка
    `); + Object.keys(notes).forEach(catId => setCatName(catId, '#note-' + catId)); + } + else { + $(isDesktop ? '#branch' : '#site_table').append(`Нет заметок об игроках`); + } + } + } + + function changeIdeasPage() { + addCSS(`.vote[style="color:#000"] { color: inherit !important; } .idea { color: black; } .idea a, .idea a:hover { color: #005 !important; }`); + } + + function changeIndexPage() { + let css = ` + #act_name b { color: black; } + #info { color: black; background: rgba(255, 255, 255, 0.5); } + #clan_icon, #age_icon, #age2_icon, #act_icon { cursor: pointer; } + #cwmod-grats { width: fit-content; padding: 5px; background: rgba(255, 255, 255, 0.5); border-radius: 10px; } + `; + if (globals.hideEducation) { + css += `#education, #education-show, #education-show + br {display: none !important}`; + } + addCSS(css); + addBBcode(); + const catId = $('[src="img/icon_id.png"]').parent().siblings().children('a').children('b').text(); + activityCalc(catId); + moonCalc(); + if (globals.indexSaveAlert) addSaveAlert(); + } + + function activityCalc(catId) { + const actStages = [{ + name: 'пустое место' + , fromZero: -5000 + } + , { + name: 'подлежащий удалению' + , fromZero: -5000 + } + , { + name: 'покинувший игру' + , fromZero: -2000 + } + , { + name: 'забывший про игру' + , fromZero: -1000 + } + , { + name: 'забытый кот' + , fromZero: -750 + } + , { + name: 'ужаснейшая' + , fromZero: -500 + } + , { + name: 'ужасная' + , fromZero: -300 + } + , { + name: 'ухудшающаяся' + , fromZero: -150 + } + , { + name: 'отрицательная' + , fromZero: -50 + } + , { + name: 'переходная' + , fromZero: -5 + } + , { + name: 'положительная' + , fromZero: 5 + } + , { + name: 'улучшающаяся' + , fromZero: 50 + } + , { + name: 'замечательная' + , fromZero: 150 + } + , { + name: 'переход 2 мин 15 с' + , fromZero: 225 + } + , { + name: 'замечательнейшая' + , fromZero: 300 + } + , { + name: 'переход 2 мин' + , fromZero: 450 + } + , { + name: 'любимый кот' + , fromZero: 500 + } + , { + name: 'переход 1 мин 45 с' + , fromZero: 675 + } + , { + name: 'легенда сайта' + , fromZero: 750 + } + , { + name: 'переход 1 мин 30 с' + , fromZero: 900 + } + , { + name: 'ходячий миф' + , fromZero: 1000 + } + , { + name: 'переход 1 мин 15 с' + , fromZero: 1125 + } + , { + name: 'переход 1 мин' + , fromZero: 1350 + } + , { + name: 'переход 45 c' + , fromZero: 1575 + } + , { + name: 'император Игровой' + , fromZero: 2000 + } + , { + name: 'частичка Игровой' + , fromZero: 5000 + } + , { + name: 'хранитель Игровой' + , fromZero: 20000 + } + , { + name: 'идеальная' + , fromZero: 75000 + } + , { + name: 'сверхидеальная' + , fromZero: 150000 + } + ]; + const sets = JSON.parse(window.localStorage.getItem('cwmod_act') || '{}'); + if (!sets[catId]) { + sets[catId] = {}; + if (window.localStorage.getItem('cwm_hours') !== null) { + sets[catId].hours = Number(window.localStorage.getItem('cwm_hours')); + window.localStorage.removeItem('cwm_hours'); + } + else sets[catId].hours = 24; + sets[catId].opened = true; + } + /// до 2.2 + if (sets[catId].actgoal) { + actStages.forEach(function(stage, i) { + if (i && Number(sets[catId].actgoal) === stage.fromZero) { + sets[catId].goal = i; + delete sets[catId].actgoal; + } + }); + } + + function updateHourWord() { + const hours = sets[catId].hours; + $('#hour-word').text(declOfNum(hours, ['час', 'часа', 'часов'])); + } + + function actLength(d) { + const minus = sets[catId].minus || 0; + if (d <= 14) return 150 - minus; + else if (d >= 1575) return 45 - minus; + else return Math.ceil(150 - d / 15) - minus; + } + + function left(currentActivity, goal, hoursPerDay) { + const secsPerDay = convertTime('h s', hoursPerDay); + if (actLength(currentActivity) * 4 + 1 > secsPerDay) { + return { + actions: '∞' + , time: '∞' + , date: 'никогда' + }; + } + const actionsWithoutDecr = goal - currentActivity; + let days = 0; + let secsToday; + while (currentActivity < goal) { + secsToday = 0; + while (secsToday < secsPerDay) { + currentActivity++; + secsToday += actLength(currentActivity); + if (currentActivity >= goal) break; + } + if (currentActivity >= goal) break; + days++; + currentActivity -= 4.8; + } + const actionsDecr = Math.floor(days * 4.8 + convertTime('s h', secsToday) / 5); + const time = secsPerDay * days + secsToday; + const now = new Date(); + const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); + const secsToTomorrow = convertTime('ms s', tomorrow - now); + if (days === 0 && secsToday > secsToTomorrow) days++; + const date = new Date(Date.now() + convertTime('d ms', days)); + return { + actions: actionsWithoutDecr + actionsDecr + , time: secToTime(time) + , date: date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + }; + } + + function updateToact() { + if (progress.stage === actStages.length - 1) { + $('#toact').hide(); + return; + } + const goal = Number($('#act-list').val()); + const result = left(progress.doneFromZero, actStages[goal].fromZero, sets[catId].hours); + $('#toact > ul').html(` +
  5. ${result.actions} ${declOfNum(result.actions, ['переход', 'перехода', 'переходов'])} (${result.time})
  6. +
  7. будет достигнута ${result.date}
  8. + `); + } + const act = $('#act_name b').text().split(' ('); + const progress = {}; + actStages.forEach(function(stage, i) { + if (act[0] === stage.name) { + progress.doneFromZero = stage.fromZero + Number(act[1].split('/')[0]); + } + if ( + (!actStages[i + 1] || actStages[i + 1].fromZero > progress.doneFromZero) && + actStages[i].fromZero <= progress.doneFromZero + ) { + progress.stage = i; + } + }); + const actInfoHTML = ` +
    + Калькулятор активности + +
    Переход: ${secToTime(actLength(progress.doneFromZero))}
    +
    Предметы во рту уменьшают мой переход на + +
    +
    Я качаю активность в сутки
    +
    + Цель: : + +
    +
    Переход начнёт падать
    +
    + `; + $('#info').after(actInfoHTML); + for (let i = progress.stage + 1; i < actStages.length; i++) { + $('#act-list').append(``); + } + if (sets[catId].goal > progress.stage || sets[catId].noGrats) { + $(`#act-list > [value="${sets[catId].goal}"]`).prop('selected', true); + } + else if (sets[catId].goal) { + $(`#cwmod-grats`).html(` + Цель «${actStages[sets[catId].goal].name}» достигнута! +
    + +
    Больше не поздравлять на этом персонаже + `).show(); + $('#cwmod-grats-hooray').click(function() { + $(`#cwmod-grats`).hide(200); + $(`#cwmod-grats`).hide(200); + sets[catId].goal = Number($('#act-list').val()); + sets[catId].noGrats = $('#cwmod-grats-never-show').is(':checked'); + saveData('act', sets); + }); + } + if (sets[catId].minus) { + $(`#minus > [value="${sets[catId].minus}"]`).prop('selected', true); + } + updateHourWord(); + updateToact(); + if (actLength(progress.doneFromZero) !== 45) { + $('#tofall').parent().hide(); + } + else { + const timeFall = new Date(Date.now() + (progress.doneFromZero - 1575) * 5 * 3600000); + $('#tofall').html( + timeFall.getDate() + ' ' + + months[timeFall.getMonth()] + + ' ' + timeFall.getFullYear() + ); + } + $('#minus').change(function() { + sets[catId].minus = $(this).val(); + saveData('act', sets); + updateToact(); + $('#actlength').html(`Переход: ${secToTime(actLength(progress.doneFromZero))}`); + }); + $('#act-list').change(function() { + sets[catId].goal = Number($('#act-list').val()); + saveData('act', sets); + updateToact(); + }); + $('#hours-per-day').on('input', function() { + const hours = Number($('#hours-per-day').val()); + if (hours < 0 || hours > 24 || !Number.isInteger(hours * 1000)) { + $('#hours-per-day').val(sets[catId].hours); + return; + } + sets[catId].hours = hours; + saveData('act', sets); + updateHourWord(); + updateToact(); + }); + $('#open-calc').click(function() { + sets[catId].opened = !$('#calc-act').is('[open]'); + saveData('act', sets); + }); + } + + function changeKnsPage() { + if (globals.knsAlert) addSaveAlert(); + } + + function changeLsPage() { + addCSS(` + .msg_header { font-size: 1.2rem; text-align: center; } + #search, #saved { display: none; } + label { cursor: pointer; } + .msg_deleted { color: darkred; } + .messList { background-color: ${$('#messList').css('background-color')}; color: ${$('#messList').css('color')}; } + .messList a { color: #0000cd; } + `); + const enableSaving = globals.enableSavingLS; + if (enableSaving) $('#links').append(` | Сохранённые (?)`); + $('#links').append(` | Поиск`); + let html = ` + + `; + if (enableSaving) html += '
    '; + $(isDesktop ? '#branch' : '#site_table').append(html); + addSearchFunc(enableSaving); + if (enableSaving) { + updateSavedLsList(); + $(window).on('storage', function(e) { + if (e.originalEvent.key === 'cwmod_ls') updateSavedLsList(); + }); + if (isPage('ls?3')) showSavedLsList(); + if (isPage(/^https:\/\/catwar.net\/ls\?id=\d+/)) changeMessagePage(); + body.on('click', '.del-saved', function() { + const lsId = $(this).data('id'); + const subject = $(this).parent().siblings().first().text(); + const catName = $(this).parent().siblings('.cat_name').text(); + if (confirm(`Удалить ЛС «${subject}» от игрока ${catName} из сохранённых?`)) { + deleteSavedLs(lsId); + $(this).parent().parent().remove(); + } + }); + } + if (isPage('ls?search')) showSearch(); + if (isPage('ls?new')) addBBcode(); + $('a').click(function(e) { + if ($(this).attr('id') === 'f3') { + if (e.ctrlKey) return; + e.preventDefault(); + history.pushState(null, null, 'https://catwar.net/ls?3'); + showSavedLsList(); + } + else if ($(this).attr('id') === 's') { + if (e.ctrlKey) return; + e.preventDefault(); + history.pushState(null, null, 'https://catwar.net/ls?search'); + showSearch(); + } + else { + hideSavedLsList(); + hideSearch(); + } + }); + const observer = new MutationObserver(function(mutations) { + mutations.forEach(function() { + if (enableSaving && isPage('ls?3')) { + history.pushState(null, null, 'https://catwar.net/ls?3'); + showSavedLsList(); + } + else if (isPage('ls?search')) { + history.pushState(null, null, 'https://catwar.net/ls?search'); + showSearch(); + } + else { + if (enableSaving) hideSavedLsList(); + hideSearch(); + } + if (isPage('ls?new')) addBBcode(); + if (enableSaving && isPage(/^https:\/\/catwar.net\/ls\?id=\d+/)) changeMessagePage(); + }); + }); + observer.observe($('#main')[0], { + childList: true + }); + body.on('click', '#preview', function() { + if (isDesktop) { + $('#preview_div').after(` + + + + + + + + +
    + Отправитель: +
    Сегодня в +
    Переписка: + … +
    + `); + } + else { + $('#preview_div').after(` + + + + + + + + +
    + Отправитель: +
    Сегодня в +
    Переписка: + … +
    + `); + } + let subject = $('#subject').val().replaceAll('<', '<'); + if (!subject) subject = '( = )'; + $('#preview-subject').html(subject); + getCurrentUser(function(catId, catName) { + $('#preview-sender').html(`${catName}`); + }); + const currentDate = new Date(); + $('#preview-date').html(`${leadingZero(currentDate.getHours())}:${leadingZero(currentDate.getMinutes())}`); + $('#preview-text').html($('#preview_div')); + }); + } + + function addSearchFunc(enableSaving) { + const lastSearch = globals.lsLastSearch; + const lastFolder = lastSearch.folder; + const lastType = enableSaving ? lastSearch.type : 1; + $(`[name="search-folder"][value="${lastFolder}"]`).prop('checked', true); + switch (lastType) { + case 1: + $('#search-all').prop('checked', true); + break; + case 2: + $('#search-saved').prop('checked', true); + break; + case 3: + $('[name="search-type"]').prop('checked', true); + break; + default: + $('[name="search-type"]').prop('checked', false); + } + $('#search-ok').click(searchLs); + $('[name="search-folder"]').change(function() { + const folder = parseInt($('[name="search-folder"]:checked').val(), 10); + lastSearch.folder = folder; + setSettings(lsLastSearch, lastSearch); + }); + $('[name="search-type"]').change(function() { + const searchAll = $('#search-all').is(':checked'); + const searchSaved = $('#search-saved').is(':checked'); + if (searchAll && !searchSaved) lastSearch.type = 1; + else if (!searchAll && searchSaved) lastSearch.type = 2; + else if (searchAll && searchSaved) lastSearch.type = 3; + else lastSearch.type = 0; + setSettings(lsLastSearch, lastSearch); + }); + $('#search-cat').keypress(function(e) { + if (e.which == 13) { + $('#search-text').focus(); + return false; + } + }); + $('#search-text').keypress(function(e) { + if (e.which == 13) { + searchLs(); + return false; + } + }); + } + + function showSearch() { + $('.active').removeClass('active'); + $('#s').addClass('active'); + $('#main, #saved').hide(); + $('#search').show(); + } + + function hideSearch() { + $('#main').show(); + $('#search').hide(); + } + + function showSavedLsList() { + $('.active').removeClass('active'); + $('#f3').addClass('active'); + $('#main, #search').hide(); + $('#saved').show(); + } + + function hideSavedLsList() { + $('#main').show(); + $('#saved').hide(); + } + + function changeMessagePage() { + // if ($('#delete-saved-ls').length) return; + // if ($('.bbcode').length) addBBcode(); + // ↑ у меня есть некоторые вопросы к себе + const main = $('#main'); + const lsId = parseInt(window.location.href.split('=')[1], 10); + const savedLs = getSavedLsById(lsId); + const btnDelete = ``; + const isLsOnSever = !(main.html() === 'ЛС не найдено.'); + if ($('#msg_subject').length && lsId) { + const btnSave = ``; + const subjectTd = $('#msg_subject'); + subjectTd.html(`${subjectTd.html()}${btnSave}`); + subjectTd.removeAttr('id'); + $('#savels').click(saveLs); + if (savedLs) { + const td = $('#msg_table > tbody > tr:last-child > td'); + td.html(td.html() + `Сохранено ${savedLs.savedate} ${btnDelete}`); + } + } + else if (!isLsOnSever && savedLs) { + insertSavedLs(main, lsId, savedLs, btnDelete); + } + body.on('click', '#delete-saved-ls', function() { + if (isLsOnSever) { + deleteSavedLs(lsId); + $('#savedate').remove(); + $('#delete-saved-ls').remove(); + } + else if (confirm('Удалить это ЛС из сохранённых?')) { + deleteSavedLs(lsId); + main.html('ЛС не найдено.'); + } + }); + if ($('#msg_login').length) { + let myId; + if (savedLs) myId = Number(savedLs.myId); + else myId = Number(main.data('id')); + const catId = Number(getNumber($('#msg_login').attr('href'))); + const history = JSON.parse(window.localStorage.getItem('cwmod_ls_history') || '{}'); + if (!history[myId]) { + history[myId] = {}; + } + if (!history[myId][catId]) { + history[myId][catId] = {}; + } + $('#msg_info > .msg_open').each(function() { + const id = $(this).data('id'); + const isMy = ($(this).text() === '-'); + history[myId][catId][id] = isMy; + }); + saveData('ls_history', history); + } + } + + function insertSavedLs(main, lsId, ls, btnDelete) { + const info = ` + ${ls.type ? 'Получатель' : 'Отправитель'}: ${ls.catName} +
    ${ls.date} +
    Переписка: + `; + if (isDesktop) { + main.html(` + + + + + + +
    ${escapeHTML(ls.subject)}
    ${info}${ls.text}
    ${ls.type ? 'Отправитель' : 'Получатель'}: ${ls.myName} [${ls.myId}]
    Сохранено ${ls.savedate} ${btnDelete}
    + `); + } + else { + main.html(` + + + + + + + +
    ${escapeHTML(ls.subject)}
    ${info}
    ${ls.text}
    ${ls.type ? 'Отправитель' : 'Получатель'}: ${ls.myName} [${ls.myId}]
    Сохранено ${ls.savedate} ${btnDelete}
    + `); + } + setCatName(ls.catId, `#msg_login`, ls.catName); + const history = JSON.parse(window.localStorage.getItem('cwmod_ls_history'))[ls.myId][ls.catId]; + const historyArray = {}; + Object.keys(history).forEach(function(key) { + const isMy = history[key]; + $('#msg-history').prepend(`${isMy ? '-' : '+'} `); + }); + Object.keys(history).forEach(function(key) { + const isMy = history[key]; + $.post('/ajax/mess_show', { + id: key + }, function(data) { + const isSaved = getSavedLsById(key); + if (isSaved || !data.fail) { + let lsLink = `` + if (Number(key) === lsId) lsLink += `` + lsLink += isMy ? '-' : '+'; + if (Number(key) === lsId) lsLink += `` + if (Number(key) === lsId) lsLink += `` + lsLink += `` + historyArray[key] = lsLink; + } + else { + historyArray[key] = `${isMy ? '-' : '+'}`; + } + if (Object.keys(historyArray).length === Object.keys(history).length) { + $('#msg-history').empty(); + Object.keys(historyArray).forEach(function(k) { + $('#msg-history').prepend(historyArray[k] + ' '); + }); + } + }, 'json'); + }); + } + + function searchLs() { + const folder = parseInt($('[name="search-folder"]:checked').val(), 10); + const searchAll = $('#search-all').is(':checked'); + const searchSaved = $('#search-saved').is(':checked'); + if (!searchAll && searchSaved && folder === 2) { + $('#search-list').html(''); + } + else { + $('#search-list').html(` +

    Результаты поиска

    +

    Найдено: 0

    + + + + +
    Тема${folder === 1 ? 'Получатель' : 'Отправитель'}Дата
    + `); + const cat = $('#search-cat').val(); + let text = $('#search-text').val(); + if (text) { + text = text.match(/['_\-а-яёa-z0-9$]+/gi); + text = new RegExp(text.join('|'), 'gi'); + } + if (searchAll || !searchSaved) searchAllLs(folder, cat, text); + if (searchSaved || !searchAll) searchSavedLs(folder, cat, text); + } + } + + function searchAllLs(type, cat, text) { + getCatIdByName(cat, function(catId) { + $.post('/ajax/mess_folder', { + folder: type + , page: 1 + , del: 0 + }, function(data) { + const column = (type ? 'poluch' : 'otpr'); + for (let i = 1; i <= data.page; i++) { + $.post('/ajax/mess_folder', { + folder: type + , page: i + , del: 0 + }, function(data) { + for (let j = 0; j < data.msg.length; j++) { + const msg = data.msg[j]; + const id = msg.id; + const html = ` + + ${msg.subject} + ${msg.login} + ${msg.time} + + `; + $.post('/ajax/mess_show', { + id: id + }, function(data) { + if (cat) { + if (catId !== msg[column] && cat !== msg[column] && cat.toLowerCase() !== msg.login.toLowerCase()) return; + } + if (text) { + if (!data.msg.subject.match(text) && !data.msg.text.replace(/<[^>]+>/g, '').match(text)) return; + } + $('#search-results').append(html); + $('#search-number').html($('#search-results').children().length - 1); + }, 'json'); + } + }, 'json'); + } + }, 'json'); + }); + } + + function searchSavedLs(type, cat, text) { + const savedLs = JSON.parse(window.localStorage.getItem('cwmod_ls')); + if (savedLs) { + getCatIdByName(cat, function(catId) { + for (let key in savedLs) { + const ls = savedLs[key]; + if (ls.type !== type) continue; + if (cat) { + if ( + catId !== ls.catId && + cat !== ls.catId && + cat.toLowerCase() !== ls.catName.toLowerCase() + ) { + continue; + } + } + if (text) { + if ( + !ls.subject.match(text) && + !ls.text.replace(/<[^>]+>/g, '').match(text) + ) { + continue; + } + } + $.post('/ajax/mess_show', { + id: key + }, function(data) { + if (data.fail) { + const html = ` + + ${escapeHTML(ls.subject)} + ${ls.catName} + ${ls.savedate} + + `; + $('#search-results').append(html); + $('#search-number').html($('#search-results').children().length - 1); + setCatName(ls.catId, `.search-cat-name[data-id="${key}"]`, ls.catName); + } + }, 'json'); + } + }); + } + else { + $('#search-results').html('Нет сохранённых сообщений'); + } + } + + function updateSavedLsList() { + const savedLs = JSON.parse(window.localStorage.getItem('cwmod_ls')); + if (savedLs) { + $('#saved-list').html(` +

    Входящие

    + + + + +
    ТемаОтправительДата сохраненияX
    +

    Отправленные

    + + + + +
    ТемаПолучательДата сохраненияX
    + `); + const inbox = $('#inboxLsList'); + const outbox = $('#outboxLsList'); + for (let key in savedLs) { + const ls = savedLs[key]; + const html = ` + + ${escapeHTML(ls.subject)} + ${ls.catName} + ${ls.savedate} + + + `; + if (ls.type) outbox.append(html); + else inbox.append(html); + setCatName(ls.catId, `.cat_name[data-id="${key}"]`, ls.catName); + } + $('#saved-number').text(Object.keys(savedLs).length); + } + else { + $('#saved-number').text(0); + $('#saved-list').html(`Сообщений нет.`); + } + } + + function saveLs() { + try { + const savedLs = JSON.parse(window.localStorage.getItem('cwmod_ls') || '{}'); + const main = $('#main'); + const lsId = parseInt(window.location.href.split('=')[1], 10); + const lsInfo = $('#msg_info').html(); + const ls = {}; + ls.subject = $('#msg_subject').text(); + ls.text = $('#msg_table').find('.parsed').html(); + ls.date = findDate(lsInfo); + ls.catId = parseInt(getNumber($('#msg_login').attr('href')), 10); + ls.catName = $('#msg_login').html(); + ls.myId = main.data('id'); + ls.myName = main.data('login'); + ls.type = lsInfo.match(/Получатель/) ? 1 : 0; + const now = new Date(); + const saveDate = {}; + saveDate.day = leadingZero(now.getDate()); + saveDate.month = leadingZero(now.getMonth() + 1); + saveDate.year = now.getFullYear(); + saveDate.hour = leadingZero(now.getHours()); + saveDate.minute = leadingZero(now.getMinutes()); + saveDate.second = leadingZero(now.getSeconds()); + ls.savedate = `${saveDate.year}-${saveDate.month}-${saveDate.day} ${saveDate.hour}:${saveDate.minute}:${saveDate.second}`; + savedLs[lsId] = ls; + saveData('ls', savedLs); + if ($('#savedate').length) $('#savedate').text(`Сохранено ${ls.savedate}`); + else { + const td = $('#msg_table > tbody > tr:last-child > td'); + td.append(`Сохранено ${ls.savedate} `); + $('#saved-number').text(Number($('#saved-number').text()) + 1); + } + updateSavedLsList(); + } + catch (err) { + window.console.error('Варомод:', err); + } + } + + function deleteSavedLs(lsId) { + try { + const savedLs = JSON.parse(window.localStorage.getItem('cwmod_ls')); + if (!savedLs) return; + delete savedLs[lsId]; + saveData('ls', savedLs); + } + catch (err) { + window.console.error('Варомод:', err); + } + } + + function getSavedLsById(lsId) { + try { + const savedLs = JSON.parse(window.localStorage.getItem('cwmod_ls')); + if (!savedLs) return; + const ls = savedLs[lsId]; + return ls || false; + } + catch (err) { + window.console.error('Варомод:', err); + } + } + /* + function changeTimePage() { + const catTimeNow = timestampToCatTime(Date.now()); + $(isDesctop ? '#branch' : '#site_table').append(` +
    +

    Настоящее кошачье время

    +

    ${catTimeNow.day} ${months[catTimeNow.month]} ${catTimeNow.year} года, ${leadingZero(catTimeNow.hour)}:${leadingZero(catTimeNow.minute)}:${leadingZero(catTimeNow.second)}

    +

    Калькулятор времени

    +

    Кошачье время:

    +

    Время двуногих:

    +
    + `); + } + */ + function changeSettingsPage() { + let css = ` + .copy { cursor: pointer; } + #cwmod-settings h2 { text-indent: 1.5em; } + #cwmod-settings h3 { margin: 1em 0 0.5em 1em; } + #cwmod-settings h4 { margin: 0; } + #cwmod-settings ul { margin: 0; padding: 0 0 0 30px; list-style-type: kannada; } + #cwmod-settings ul ul { padding: 0 0 0 10px; list-style-type: none; } + #cwmod-settings li { padding: 0.2em 0; } + .cwmod-settings[type="checkbox"] { margin-left: 0; cursor: pointer; } + .cwmod-data-result { margin-bottom: 1em; max-height: 300px; overflow-y: auto; white-space: pre-line;} + .cwmod-error { font-weight: bold; color: darkred; } + .cwmod-done { font-weight: bold; color: darkgreen; } + + select#cwmodTheme, div#cwmod-settings input.cwmod-settings[type="text"]:not(input#cw3BkgImg), input.cwmod-data-export, input.cwmod-data-import { + border-radius: 3px !important; + margin: 5px 0px; + padding: 1px 5px; } + + div#cwmod-settings input.cwmod-settings[type="number"] { + border-radius: 3px; + text-align: center; + margin: 2px; + height: 22px !important; + width: 55px !important; } + + input.cwmod-data-merge { + border-radius: 3px; + margin: 2px; + height: 22px !important; + width: 50% !important; } + + input#clear-ym-storage { + border-radius: 3px; + margin: 0px 10px; + height: 22px !important; + width: 90% !important; } + + p#cwmodSaveButton { + margin: 0px 15px; } + + select#cw3Bkg, input#cw3BkgImg, select#cw3BkgSize, select#cw3BkgPos { + border-radius: 3px !important; + margin: 3px 0px; + padding: 1px 5px; + width: 80% !important; } + + div#cwmodMenuList, div#cwmodCustSet { + margin: 10px 0px 10px; } + + div.setHead>p { + margin: 25px 0px; + font-weight: 600; + font-size: 16px; + margin-bottom: 5px; } + + div.setHead { + border-bottom: 4px solid #0F0F0F45; + width: 25%; + height: 24px !important; + margin-bottom: 4px; } + `; + addCSS(css); + if (globals.hideMail) { + const inputColor = $('input[name="mail"]').css('background-color'); + addCSS(`input[name="mail"]:not(:focus) { color: ${inputColor} !important; }`, hideMail); + } + const html = `
    +

    Настройки Варомода v${VERSION}

    + + + +
    +
    +

    Сайт

    +
    + + +
    + + +
    + + +
    + + +
    + + +
    + + +
    + + +
    + +
    + + px
    + +
    + + +
    + + +
    + +
    + + px +
    + + px +
    + 0 — значение по умолчанию (не уменьшать) +
    + + +
    + +
    + + +
    + + +
    +
    +
    + +
    +
    +

    Окружающий мир

    +
    + + +
    +
    + + +
    +
    +
    +

    Локация

    +
    + + +
    +
    + + +
    +
    +
    + +
    +
    +

    Меню

    +
    + + +
    +
    + +
    + + +
    + + +
    + + +
    + + +
    + + +
    + + +
    + + +
    +
    + + +
    +
    +
    + +
    +
    +

    Чат

    +
    + + +
    +
    + + +
    +
    + +
    +

    Конструктор окрасов

    +
    + + +
    +
    +
    + +
    +
    +

    Оформление

    +
    + +
    Больше тем в Вароредизайне. Не используйте темы Вароредизайна и Варомода одновременно! +
    +
    + +
    + +
    + +
    + +
    +
    + + +
    + + +
    + + + + + + +
    + +
    +
    +

    Игроки

    +
    + + +
    + + +
    + + +
    + + +
    То, что можно увидеть в кодах: рост, ссылка на окрас, степени грязи и болезней +
    + + +
    Вместо повторения предметов одного типа писать их количество +
    + + +
    +
    +
    + +
    +
    +

    Импорт и экспорт данных

    + +
    Как пользоваться +
      +
    1. Скопируйте нужные данные в браузере, откуда вы их хотите перенести.
    2. +
    3. Вставьте их в поле «Импорт» того же раздела в браузере, куда вы их хотите перенести.
    4. +
    5. Нажмите на кнопку «Объединить» («Обновить» в случае настроек).
    6. +
    +
    + + + + +

    Заметки об игроках

    Экспорт:

    Скопировать

    Импорт:

    +
    + + + + + +

    Личные сообщения

    Экспорт:

    Скопировать

    Импорт:

    +
    + + + + + +

    Настройки

    Экспорт:

    Скопировать

    Импорт:

    +
    + +

    Для тех, у кого ничего не сохраняется

    +
    +
    +
    +
    + `; + $(isDesktop ? '#branch' : '#site_table').append(html); + try { + $('.cwmod-data-export').each(function() { + const key = $(this).data('export'); + $(this).val(window.localStorage.getItem('cwmod_' + key)) + }); + $(window).on('storage', function(e) { + if (e.originalEvent.key === 'cwmod_settings') { + $('[data-export="notes"]').val(e.originalEvent.newValue); + } + if (e.originalEvent.key === 'cwmod_ls') { + $('[data-export="ls"]').val(e.originalEvent.newValue); + } + }); + } + catch (err) { + window.console.error('Варомод:', err); + } + $('#about-split-info').click(function(e) { + e.preventDefault(); + showCwmodPopup('alert', ''); + }); + $('.cwmod-data-import').click(function() { + $(this).select(); + }); + $('.cwmod-data-merge').click(function() { + const key = $(this).data('merge'); + mergeData(key); + }); + $('.copy').click(function() { + const key = $(this).data('copy'); + $(`input[data-export="${key}"]`).select(); + document.execCommand('copy'); + alert('Скопировано!'); + }); + $(`[data-conf="${hideMail}"]`).change(function() { + if ($(this).is(':checked')) { + addCSS(`input[name="mail"]:not(:focus) { color: #333; }`, hideMail); + } + else removeCSS(hideMail); + }); + $('#clear-ym-storage').click(function() { + try { + window.localStorage.setItem('storage-test', Math.pow(2, 1023).toString(2)); + window.localStorage.removeItem('storage-test'); + const ymSize = window.localStorage.getItem('_ym_alt_retryReqs').length; + if (ymSize) { + window.localStorage.removeItem('_ym_alt_retryReqs'); + $('#clear-ym-storage-result').html(`

    Возможно, чистка ${ymSize} байт данных Яндекс.Метрики могла помочь.

    `); + } + } + catch (err) {} + }); + } + $('.cwmod-settings').on('change', function() { + let key = this.id; + let val = this.type === 'checkbox' ? this.checked : this.value; + if (this.tagName === 'SELECT') { + val = $(this).prop('selectedIndex'); + } + setSettings(key, val); + console.log(key, ': ', val, '.'); + }); + $('#div2').on('change', '.cwmod-settings', function() { + let key = this.id; + let val = this.type === 'checkbox' ? this.checked : this.value; + if (this.tagName === 'SELECT') { + val = $(this).prop('selectedIndex'); + } + setSettings(key, val); + console.log(key, ': ', val, '.'); + }); + $(document).ready(function() { + $('#blogAvatarsSize').val(globals.blogAvatarsSize); + $('#blogImgMaxWid').val(globals.blogImgMaxWid); + $('#sniffImgMaxWid').val(globals.sniffImgMaxWid); + $('#cwmodTheme').val(globals.cwmodTheme); + $('#cw3Bkg').val(globals.cw3Bkg); + $('#cw3BkgImg').val(globals.cw3BkgImg); + $('#cw3BkgSize').val(globals.cw3BkgSize); + $('#cw3BkgPos').val(globals.cw3BkgPos); + }); + + function mergeData(dataKey) { + $(`[data-result]`).empty(); + let exp = $(`[data-export="${dataKey}"]`).val(); + let imp = $(`[data-import="${dataKey}"]`).val(); + if (!imp) { + mergeDataError(dataKey, null, ['С чем объединять-то?', '']); + return; + } + try { + if (exp) exp = JSON.parse(exp); + } + catch (err) { + window.console.error(err); + mergeDataError(dataKey, 'export', ['Ошибка парсинга JSON']); + return; + } + try { + imp = JSON.parse(imp); + } + catch (err) { + window.console.error(err); + mergeDataError(dataKey, 'import', ['Ошибка парсинга JSON']); + return; + } + const validExp = mergeDataValidate(dataKey, exp); + if (validExp.error) { + mergeDataError(dataKey, 'export', validExp.text); + return; + } + const validImp = mergeDataValidate(dataKey, imp); + if (validImp.error) { + mergeDataError(dataKey, 'import', validImp.text); + return; + } + let text = []; + const merged = Object.assign({}, exp, imp); + Object.keys(merged).forEach(function(key) { + if (dataKey === 'settings') { + if (DEFAULTS[key] === undefined) { + delete merged[key]; + return; + } + } + if (exp[key] && imp[key]) { + if (dataKey === 'ls') { + if (exp[key].catName === imp[key].catName && exp[key].savedate > imp[key].savedate) { + merged[key] = exp[key]; + } + } + else if (dataKey === 'notes') { + if (exp[key] === imp[key]) return; + else if (exp[key].indexOf(imp[key]) !== -1) { + merged[key] = exp[key]; + text.push(`Заметки об игроке с ID ${key}: "${exp[key]}" и "${imp[key]}" — объединены`); + } + else if (imp[key].indexOf(exp[key]) === -1) { + merged[key] = exp[key] + '\n' + imp[key]; + text.push(`Заметки об игроке с ID ${key}: "${exp[key]}" и "${imp[key]}" — объединены в "${merged[key]}"`); + } + } + } + }); + console.log(merged); + saveData(dataKey, merged); + $('[data-export="${dataKey}"]').val(JSON.stringify(merged)); + mergeDataDone(dataKey, text); + } + + function mergeDataValidate(dataKey, data) { + let error = false + , text = []; + Object.keys(data).forEach(function(k) { + if (dataKey === 'notes') { + if (!/^\d+$/.test(k)) { + error = true; + text.push(`Ключ _${k}_ не ID игрока`); + } + if (typeof data[k] !== 'string') { + error = true; + text.push(`Элемент _${k}_ не заметка`); + } + } + else if (dataKey === 'ls') { + if (!/^\d+$/.test(k)) { + error = true; + text.push(`Ключ _${k}_ не ID сообщения`); + } + if (typeof data[k] !== 'object') { + error = true; + text.push(`Элемент _${k}_ не сообщение`); + } + else { + const lsKeys = ['subject', 'text', 'type', 'savedate', 'catId', 'catName', 'date', 'myId', 'myName']; + const thisKeys = Object.keys(data[k]); + if (thisKeys.length !== lsKeys.length) { + error = true; + text.push(`Элемент ${k} не сообщение`); + } + else { + let keysError = false; + lsKeys.forEach(function(key) { + if (thisKeys.indexOf(key) === -1) { + keysError = true; + } + }); + if (keysError) { + error = true; + text.push(`Элемент ${k} не сообщение`); + } + } + } + } + }); + return { + error: error + , text: text + } + } + + function mergeDataError(dataKey, type, text = []) { + let errorText = 'Ошибка: '; + const errors = { + 'export': 'неправильный формат исходных данных (в порядке всё с ними было, зачем трогать???)' + , 'import': 'неправильный формат входных данных' + }; + errorText += errors[type] || 'Неизвестная ошибка'; + $(`[data-result="${dataKey}"]`).append(`

    ${errorText}

    ${text.join('
    ')}`); + } + + function mergeDataDone(dataKey, text = []) { + let resultText = 'Данные успешно объединены'; + if (dataKey === 'settings') resultText = 'Настройки успешно обновлены'; + $(`[data-result="${dataKey}"]`).append(`

    ${resultText}!

    ${text.join('
    ')}`); + } + + function addCSS(css, key) { + const styleId = key ? 'cwmod-style-' + key : 'cwmod-style'; + const style = $('#' + styleId); + if (style.length) { + style.append(css); + } + else { + $('head').append(``); + } + } + + function removeCSS(key) { + $('#cwmod-style-' + key).remove(); + } + + function loadSettings() { + const key = 'cwmod_settings'; + try { + SETTINGS = JSON.parse(window.localStorage.getItem(key) || '{}'); + if (SETTINGS['cw3_location_bg'] != null) { + if (SETTINGS['cw3_location_bg']) SETTINGS[cw3Bkg] = 'location'; + delete SETTINGS['cw3_location_bg']; + } + if (SETTINGS['cw3_location_bg_size'] != null) { + if (SETTINGS['cw3_location_bg_size'] === 'cover') SETTINGS[CW3_BACKGROUND_SIZE] = 'cover'; + delete SETTINGS['cw3_location_bg_size']; + } + } + catch (err) { + alert(err); + window.localStorage.removeItem(key); + SETTINGS = {}; + } + } + + function saveData(key, data) { + try { + window.localStorage.setItem('cwmod_' + key, JSON.stringify(data)); + } + catch (err) { + window.console.error('Варомод:', err); + } + } + + function addSaveAlert() { + window.addEventListener('beforeunload', beforeunload); + $('input[type=submit]').click(function() { + window.removeEventListener('beforeunload', beforeunload); + }); + } + + function beforeunload(event) { + event.preventDefault(); + event.returnValue = ''; + return ''; + } + + function isPage(page, match) { + if (page instanceof RegExp) return page.test(window.location.href); + const re = new RegExp('catwar\.su/' + page.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + (match ? '(#.*)?$' : '')); + return re.test(window.location.href); + } + + function secToTime(sec) { + if (!sec) return '0 c'; + const d = Math.floor(convertTime('s d', sec)); + sec -= convertTime('d s', d); + const h = Math.floor(convertTime('s h', sec)); + sec -= convertTime('h s', h); + const m = Math.floor(convertTime('s m', sec)); + sec -= convertTime('m s', m); + const s = Math.round(sec); + let result = []; + if (d) result.push(`${d} д`); + if (h) result.push(`${h} ч`); + if (m) result.push(`${m} мин`); + if (s) result.push(`${s} с`); + return result.join(' '); + } + + function leadingZero(num) { + return num < 10 ? '0' + num.toString() : num; + } + + function escapeHTML(str) { + return str.replace('<', '$lt;').replace('>', '$gt;'); + } + + function decodeHTML(str) { + const doc = new DOMParser().parseFromString(str, "text/html"); + return doc.documentElement.textContent; + } + + function getNoteByCatId(catId) { + try { + const savedNotes = JSON.parse(window.localStorage.getItem('cwmod_notes') || '{}'); + const text = savedNotes[catId]; + return text || false; + } + catch (err) { + window.console.error('Варомод:', err); + } + } + + function addBBcode(type) { + const bb = $('.bbcode').parent(); + if (!bb.length) return; + if ($('.bbcode[data-code="ol"]').length) return; + if (type) { + bb.append(` + + + + + + + + `); + } + else { + $('[data-code="block"]').after(` + + `); + bb.append(` + + + + + + + + + `); + } + } + + function setAvatar(catId, selector) { + $.get('/cat' + catId.toString() + , function(data) { + const temp = $('
    ', { + html: data + }); + let avatar = temp.find('[src*=avatar]').attr('src'); + if (!avatar) avatar = '//e.catwar.net/avatar/0.jpg'; + try { + window.sessionStorage.setItem('avatar' + catId, avatar); + } + catch (err) {} + $(selector).css('background-image', `url(${avatar})`); + } + ); + } + + function setCatName(catId, selector, oldName) { + $.post('/preview', { + text: `[link${catId}]` + }, function(data) { + data = data.replace(/<\/?div( class="parsed")?>/, ''); + $(selector).html(data); + if (oldName && $(selector).text() !== oldName) { + $(selector).html(data + ' (' + oldName + ')'); + } + }); + } + + function getCatIdByName(name, callback) { + $.post('/ajax/top_cat', { + name: name + }, function(data) { + const catId = parseInt(data, 10); + callback(catId); + }); + } + + function getCurrentUser(callback) { + $.get('/' + , function(data) { + const temp = $('
    ', { + html: data + }); + const catId = temp.find('a[href^="cat"]').first().text(); + const catName = temp.find('big').first().text(); + callback(catId, catName) + } + ); + } + + function dateToString(date) { + if (typeof date === 'number') date = new Date(date); + const dateString = date.toISOStringLocal(); + return dateString.slice(0, 16); + } + + function declOfNum(n, titles) { + n = Math.abs(n); + if (isNaN(n)) return titles[2]; + if (!Number.isInteger(n)) return titles[1]; + n %= 100; + if (n > 10 && n < 20) return titles[2]; + n %= 10; + if (n === 1) return titles[0]; + if (n > 1 && n < 5) return titles[1]; + return titles[2]; + } + + function convertTime(units, val) { + const allUnits = ['ms', 's', 'm', 'h', 'd']; + units = units.split(' '); + let valUnit = allUnits.indexOf(units[0]); + const resultUnit = allUnits.indexOf(units[1]); + const multipliers = [1000, 60, 60, 24]; + if (valUnit > resultUnit) + while (valUnit !== resultUnit) { + val *= multipliers[valUnit - 1]; + valUnit--; + } + else + while (valUnit !== resultUnit) { + val /= multipliers[valUnit]; + valUnit++; + } + return val; + } + + function findDate(text) { + return text.match(/(\d?\d )?[а-я]+ (\d{4} )?в \d?\d:\d\d/i)[0]; + } + + function catTimeToMs(y, m, d, h, min, s) { + // отсчёт месяцев с 0, дней с 1 + const result = (((((((y * 12 + m) * 28 + --d) * 24 + h) * 60) + min) * 60) + s) * 1000 / 7; + return Math.round(result); + } + + function timestampToCatTime(timestamp) { + const secInYear = 12 * 28 * 24 * 60 * 60; + const secInMonth = 28 * 24 * 60 * 60; + const ms = timestamp - catTimeStart; + let time = Math.round(ms / 1000 * 7); + const year = Math.floor(time / secInYear); + time -= year * secInYear; + const month = Math.floor(time / secInMonth); + time -= month * secInMonth; + const day = Math.floor(convertTime('s d', time)); + time -= convertTime('d s', day); + const hour = Math.floor(convertTime('s h', time)); + time -= convertTime('h s', hour); + const minute = Math.floor(convertTime('s m', time)); + time -= convertTime('m s', minute); + const second = time; + return { + year: year + , month: month + , day: day + 1 + , hour: hour + , minute: minute + , second: second + }; + } + + function getNumber(s) { + return Number(s.match(/\d+/)[0]); + } + + function bbencode(html) { + html = html.replace(/
    /g, '[br]'); + html = html.replace(/<(\/?)b>/gm, '[$1b]'); + html = html.replace(/<(\/?)i>/gm, '[$1i]'); + html = html.replace(/<(\/?)s>/gm, '[$1s]'); + html = html.replace(/<(\/?)u>/gm, '[$1u]'); + html = html.replace(/<\/?tbody>/gm, ''); + html = html.replace(/<(\/?)table>/gm, '[$1table=0]'); + html = html.replace(/<(\/?)table border="1">/gm, '[$1table]'); + html = html.replace(/<(\/?)tr>/gm, '[$1tr]'); + html = html.replace(/(.(?![/b]<\/td>)+)<\/td>/gm, '[td][center]$1[/center][/td]'); + html = html.replace(/<(\/?)td>/gm, '[$1td]'); + html = html.replace(/[td][i]Цитата:[/i](.(?![/td])+)[/td]/gm, '[td][size=10][i]Цитата:[/i]$1[/size][/td]'); + html = html.replace(//gm, '[url=$1]'); + html = html.replace(/<\/a>/gm, '[/url]'); + html = html.replace(/([^/gm, '[img]$1[/img]'); + html = html.replace(/