diff --git a/web/CW-Shed-1.54.user.js b/web/CW-Shed-1.54.user.js
deleted file mode 100644
index 31b4edb..0000000
--- a/web/CW-Shed-1.54.user.js
+++ /dev/null
@@ -1,4212 +0,0 @@
-// ==UserScript==
-// @name CW: Shed
-// @version 1.54
-// @description Сборник небольших дополнений к игре CatWar
-// @author ReiReiRei
-// @copyright 2020-2025, Тис (https://catwar.net/cat406811)
-// @license MIT; https://opensource.org/licenses/MIT
-// @updateURL https://reireirei72.github.io/zero-t-18883/shed/CW_Shed.meta.js
-// @match *://catwar.net/*
-// @match *://catwar.su/*
-// @grant GM_xmlhttpRequest
-// @grant GM.xmlHttpRequest
-// @require https://reireirei72.github.io/zero-t-18883/shed/jquery-3.4.1.min.js
-// @require https://raw.githubusercontent.com/litera/jquery-scrollintoview/master/jquery.scrollintoview.min.js
-// @require https://reireirei72.github.io/zero-t-18883/shed/jquery-ui.js
-// ==/UserScript==
-(function (window, document, $) {
- 'use strict';
- if (typeof $ === 'undefined') return;
- const version = '1.54';
- const domain = location.host.split('.').pop();
- const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
- const isDesktop = !$('meta[name=viewport]').length;
- const defaults = {
-'on_customChat' : false // Кастомный чат
-,'on_chatReverse' : false // "Перевернуть" чат
-,'on_actNotif' : false // Уведомления на действия
-, 'on_newDM' : false // уведомления на новые лс
-, 'on_newChat' : false // уведомления на новое соо в чате (не игровой)
-, 'on_chatMention' : false // уведомления на упоминание имени в чате
-, 'on_blockNotif' : false // уведомления при нажатии/отжатии блока
-, 'on_smellTimerNotif' : true // уведомление при окончании таймера нюха
-, 'on_paramInfo' : true // Информация о параметрах при нажатии
-, 'on_idDM' : true // Включены по умолчанию: ID в личных сообщениях
-, 'on_idCatMouth' : true // ID котов во рту при выборе
-, 'on_idItemMouth' : true // ID предметов (и уникальные, и обычные) + инфо
-, 'on_idChat' : false // ID в чате Игровой
-, 'on_teamFights' : false // Команды в боережиме
-, 'on_huntText' : true // Охота с текстом движения дичи
-, 'on_huntMobileBtns' : true // Стиль, добавляющий кнопки охоте на телефонах
-, 'on_huntMobileFix' : false // Стиль, фиксящий охоту на телефонах
-, 'on_cleanerHistory' : false // лог чистки
-, 'on_charInline' : true // душевые в одну строчку
-, 'on_charHide' : false // скрыть душевых в игровой
-, 'on_catsDown' : false // коты внизу клетки
-, 'on_nickHighlight' : false // подсвечивание (кастомных) имен в чате
-, 'on_moveFightLog' : false // кнопка (и возможность) перемещения лога бр
-, 'on_shortFightLog' : false // сокращение лога бр
-, 'on_reports' : true // отчеты в блогах
-, 'on_oldDialogue' : false // старый вид диалогов (1 колонка в выборе)
-, 'on_smellTimer' : false // таймер нюха
-, 'on_cuMovesNote' : true // Окно заметок для ВТ
-, 'on_settLink' : true // Ссылка на настройки в игровой
-, 'on_extraInfo' : false // Доп. инфо о котиках
-, 'on_deletionWarning' : false // Предупреждение об удалении
-, 'on_historyCleanWarning' : false // Предупреждение о чистке истории TODO
-, 'on_localTimer' : 0 // Отображение системного времени в игровой (0 - выключен, 1 - локальное, 2 - московское)
- //Громкость звуков
-, 'sound_notifEaten' : 0.2 // Звук, когда тебя подняли
-, 'sound_notifBeaten' : 0.2 // Звук, когда тебя атакуют
-, 'sound_notifEndAct' : 0.1 // Звук, когда заканчивается действие
-, 'sound_newDM' : 0.1 // Звук при получении ЛС
-, 'sound_newChat' : 0.1 // Звук при получении соо в Чате
-, 'sound_chatMention' : 0.3 // Звук при упоминании имени игрока в чате (жёлтым)
-, 'sound_blockStart' : 0.1 // Звук при нажатии блока
-, 'sound_blockEnd' : 0.1 // Звук при отжатии блока
-, 'sound_ttRefresh' : 0.2 // Звук при смене карты
-, 'sound_smellTimer' : 0.1 // Звук при окончании таймера нюха
- //Настройки лога чистки
-, 'clean_id' : true // Писать в логе ID поднятого
-, 'clean_underscore' : false // Подчеркивать "поднял/опустил"
-, 'clean_title' : true // Писать в логе должность поднятого
-, 'clean_status' : false // Писать в логе должность поднятого
-, 'clean_location' : true // Писать в логе локацию, где подняли и где отпустили
-, 'clean_action' : false // Писать в логе проверку на действие
- //Массивы
-, 'cm_blocked' : [] //Список игроков, от которых не получать уведомления на упоминание в чате
-, 'nickListArray' : [] //Список ников игрока
- //Настройки команд в БР
-, 'tf_max_height' : 100 // макс высота блока с командами
-, 'fight_log_max_height' : 70 // высота лога бр
-, 'tf_color_g_team1' : "#41cd70" // зелёный цвет команды 1 (основная) в командах бр
-, 'tf_color_g_team2' : "#429dde" // зелёный цвет команды 2 в командах бр
-, 'tf_color_g_team3' : "#f6c739" // зелёный цвет команды 3 в командах бр
-, 'tf_color_g_team4' : "#ee91d7" // зелёный цвет команды 4 в командах бр
-, 'tf_color_r_team1' : "#cd4141" // красный цвет команды 1 (основная) в командах бр
-, 'tf_color_r_team2' : "#cd4141" // красный цвет команды 2 в командах бр
-, 'tf_color_r_team3' : "#cd4141" // красный цвет команды 3 в командах бр
-, 'tf_color_r_team4' : "#cd4141" // красный цвет команды 4 в командах бр
- //Умолчания действий (УВЕДОМЛЕНИЯ)
-, 'notif_eaten' : true // Уведомлять, когда тебя съели
-, 'notif_attack' : false // Уведомлять, когда тебя ввели в БР через Т2/Т3
- //Умолчания действий - ЗВУК
-, 'snd_act_move' : true // Переход
-, 'snd_act_eat' : false // Еда
-, 'snd_act_need' : true // Нужда
-, 'snd_act_drink' : true // Жажда
-, 'snd_act_dig' : true // Копать
-, 'snd_act_sleep' : true // Спать
-, 'snd_act_sniff' : true // Нюхать
-, 'snd_act_digin' : true // Закапывать
-, 'snd_act_clean' : true // Вылизывать(ся)
-, 'snd_act_swim' : true // Поплавать
-, 'snd_act_fill_moss' : true // Наполнить водой мох
-, 'snd_act_dive' : true // Нырять
-, 'snd_act_murr' : true // Помурлыкать
-, 'snd_act_tails' : false // Переплести хвосты
-, 'snd_act_cheek' : false // Потереться щекой о щёку
-, 'snd_act_ground' : false // Повалять по земле
-, 'snd_act_rub' : false // Потереться носом о нос
-, 'snd_act_calm' : false // Выход из бр
-, 'snd_act_watch' : true // Осматривать окрестности
-, 'snd_act_marking' : false // Метить территорию
-, 'snd_act_clawscratch' : false // Точить когти
-, 'snd_act_rug' : false // Чистить ковёр
-, 'snd_act_attention' : false // Привлекать внимание
-, 'snd_act_domestsleep' : false // Сон в лежанке
-, 'snd_act_domesthunt' : false // Грандиозная охота
-, 'snd_act_checkup' : false // Осмотреть кота
-, 'snd_act_loottr' : true // осмотреть дупло
-, 'snd_act_lootcr' : true // осмотреть расщелину
- //Умолчания действий - ТЕКСТ
-, 'txt_act_move' : true // Переход
-, 'txt_act_eat' : true // Еда
-, 'txt_act_need' : true // Нужда
-, 'txt_act_drink' : true // Жажда
-, 'txt_act_dig' : true // Копать
-, 'txt_act_sleep' : true // Спать
-, 'txt_act_sniff' : true // Нюхать
-, 'txt_act_digin' : true // Закапывать
-, 'txt_act_clean' : true // Вылизывать(ся)
-, 'txt_act_swim' : true // Поплавать
-, 'txt_act_fill_moss' : true // Наполнить водой мох
-, 'txt_act_dive' : true // Нырять
-, 'txt_act_murr' : true // Помурлыкать
-, 'txt_act_tails' : true // Переплести хвосты
-, 'txt_act_cheek' : true // Потереться щекой о щёку
-, 'txt_act_ground' : true // Повалять по земле
-, 'txt_act_rub' : true // Потереться носом о нос
-, 'txt_act_calm' : true // Выход из бр
-, 'txt_act_watch' : true // Осматривать окрестности
-, 'txt_act_marking' : true // Метить территорию
-, 'txt_act_clawscratch' : true // Точить когти
-, 'txt_act_rug' : true // Чистить ковёр
-, 'txt_act_attention' : true // Привлекать внимание
-, 'txt_act_domestsleep' : true // Сон в лежанке
-, 'txt_act_domesthunt' : true // Грандиозная охота
-, 'txt_act_checkup' : true // Осмотреть кота
-, 'txt_act_loottr' : true // осмотреть дупло
-, 'txt_act_lootcr' : true // осмотреть расщелину
-, 'my_id' : '' // Айди для отчетов
- //Минное поле
-, 'on_treeTechies' : false // минное поле
-, 'tt_folded' : false // сворачивать минное поле
-, 'tt_dark_theme' : false // темная тема
-, 'tt_show_volume' : true // показывать громкость веток в чате
-, 'tt_clean_confirm' : true // подтверждение очистки
-, 'tt_notif_refresh' : false // звук при обновлении локи
-, 'tt_window_top' : 20 // положение окна относительно верхней части
-, 'tt_window_left' : 20 // положение окна относительно левой части
-, 'tt_pagenamesArray' : ['1А', '2А', '3А', '4А', '5А', '6А', '1Б', '2Б', '3Б', '4Б', '5Б', '6Б', '1В', '2В', '3В', '4В', '5В', '6В', '1Г', '2Г', '3Г', '4Г', '5Г', '6Г'] //Список названий
-, 'tt_pageenabledArray' : [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true] //Список включенных , страниц
-, 'tt_foldersnamesArray' : ['А', 'Б', 'В', 'Г'] //имена вкладок
-, 'tt_foldersenabledArray' : [true, true, true, true] //включение вкладок
- //CSS
-, 'on_css_quicksettings' : false // быстрые настройки
-, 'on_csslocation' : false // замена фона на определенный
-, 'on_css_defects' : false // светить дефекты (но не грязь)
-, 'on_css_defects_dirt' : false // светить дефекты (грязь)
-, 'on_css_removesky' : false // убрать небо
-, 'on_css_oldicons' : false // старые иконки
-, 'on_css_coloredparam' : false // цветные параметры и навыки
-, 'on_css_cellshade' : false // сетка
-, 'on_css_bgpic' : false // картинка на заднем фоне
-, 'on_css_bghuntpic' : false // картинка на заднем фоне охоты
-, 'on_css_highlightmove' : false // подсветка переходов при наведении
-, 'on_css_maxopacity' : false // непрозрачные мертвецы
-, 'on_css_hideTooltip' : false // скрыть табличку (для кача лу)
-, 'on_css_daylight' : false // всегда день
-, 'on_css_alternativeDivideGUI' : false // Альтернативный интерфейс разделения травы
-, 'on_css_itemHighlight' : false // Альтернативный интерфейс разделения травы
-
-, 'css_itemHighlightArray' : ['13','15','17','19','20','21','22','23','25','26','78','106','108','109','110','111','112','115','116','119','126','565','566','655','3993','4010','4011'] // предметы, которые нужно подсвечивать в Игровой
-, 'css_itemHighlightColor' : '#eeeeee' // предметы, которые нужно подсвечивать в Игровой
-, 'css_bgpicURL' : 'https://catwar.' + domain + '/cw3/spacoj/0.jpg' // картинка на заднем плане игровой
-, 'css_huntbgpicURL' : 'https://catwar.' + domain + '/cw3/jagd_img/bg1.png' // картинка на заднем плане игровой
-, 'css_locURL' : 'https://catwar.' + domain + '/cw3/spacoj/170.jpg' // на какой фон заменять
-, 'css_cellshadeColor' : '#ffffff' // сетка цвет
-, 'css_cellshadeOpacity' : 0.1 // сетка прозрачность
-, 'css_theme' : 'theme_classic' // тема
-, 'css_cp_pattern' : true // узор в навыках и параметрах
-, 'css_cp_colors' : ['#ac23bf', '#d860ea', '#5e1268', '#6f2f79', '#dfab04', '#f0d142', '#845406', '#886921', '#28afd0', '#2bedee', '#165f75', '#157a7d', '#51d74c', '#89df4b', '#327327', '#54842d', '#d22c28', '#ee8761', '#841921', '#913733', '#a65b32', '#f09662', '#62351c', '#804c2d', '#379034', '#51bb39', '#1b4d1b', '#336b24'] // цвета
-, 'on_css_hideChat' : false // скрыть чат
- };
- const globals = {}; //Настройки
- for (var key in defaults) {
- let settings = getSettings(key);
- if (settings === null) {
- globals[key] = defaults[key];
- }
- else {
- if (Array.isArray(defaults[key])) {
- try {
- globals[key] = JSON.parse(settings);
- } catch(e) {
- console.log('CWShed: Ошибка при загрузке настройки ' + key)
- console.log(settings)
- console.error(e)
- }
- }
- else {
- globals[key] = settings;
- }
- }
- }
- const sounds = {};
- sounds.new_message = '/new_message.mp3';
- sounds.action_notif = 'https://reireirei72.github.io/zero-t-18883/shed/action_end.mp3';
- sounds.chat_mention = 'https://reireirei72.github.io/zero-t-18883/shed/chat_mention.mp3';
- sounds.alert_attacked = 'https://d.zaix.ru/ihrv.mp3';
- sounds.tt_refresh = 'https://reireirei72.github.io/zero-t-18883/shed/refresh.wav'; //изменить потом
- sounds.block_start = 'https://reireirei72.github.io/zero-t-18883/shed/lock.mp3';
- sounds.block_end = 'https://reireirei72.github.io/zero-t-18883/shed/unlock.mp3';
- const audioGlobal = new Audio();
- audioGlobal.autoplay = false;
- audioGlobal.loop = false;
-
- function playAudio(src, vlm) {
- let audio = audioGlobal;
- audio.src = src;
- audio.volume = vlm;
- audio.play();
- }
-
- function getSettings(key) { //Получение настроек
- let setting = 'cws_sett_' + key;
- let val = window.localStorage.getItem(setting);
- switch (val) {
- case null:
- return null;
- case 'true':
- return true;
- case 'false':
- return false;
- default:
- return val;
- }
- }
- var error_tm;
-
- function error(t) {
- $("#error").text(t).show();
- clearTimeout(error_tm);
- error_tm = setTimeout(function () {
- hideError()
- }, 10000);
- }
-
- function hideError() {
- clearTimeout(error_tm);
- $("#error").fadeOut(500);
- }
-
- function setSettings(key, val) {
- let setting = 'cws_sett_' + key;
- window.localStorage.setItem(setting, val);
- }
-
- function removeSettings(key) {
- let setting = 'cws_sett_' + key;
- window.localStorage.removeItem(setting);
- }
-
- function addCSS(css) {
- $('head').append(``);
- }
-
- function leadZero(num) {
- return (num < 10) ? '0' + num : num;
- }
- const pageurl = window.location.href;
- const isCW3 = (/^https:\/\/\w?\.?catwar.(su|net)\/cw3(?!(\/kns|\/jagd))/.test(pageurl));
- const isSite = !(/^https:\/\/\w?\.?catwar.(su|net)\/cw3(\/kns|\/jagd)?.*/.test(pageurl));
- const isDM = (/^https:\/\/\w?\.?catwar.(su|net)\/ls/.test(pageurl));
- const isHunt = (/^https:\/\/\w?\.?catwar.(su|net)\/cw3\/jagd/.test(pageurl));
- const isSett = (/^https:\/\/\w?\.?catwar.(su|net)\/settings/.test(pageurl));
- const isMyCat = (/^https:\/\/\w?\.?catwar.(su|net)\/$/.test(pageurl));
- const isBlog = (/^https:\/\/\w?\.?catwar.(su|net)\/blog\d+/.test(pageurl));
- const isCUMoves = (/^https:\/\/\w?\.?catwar.(su|net)\/moves$/.test(pageurl));
- const isProfile = (/^https:\/\/\w?\.?catwar.(su|net)\/cat(\d+|\/)/.test(pageurl));
-
- try {
- if (isCW3) cw3();
- if (isSite) site();
- if (isDM) dm();
- if (isSett) sett();
- if (isHunt) hunt();
- if (isMyCat) myCat();
- if (isBlog) blog();
- if (isProfile) profile();
- if (isCUMoves) cumoves();
- }
- catch (err) {
- window.console.error('CW:Shed error: ', err);
- }
-
- if (!isDesktop) { // фиксы дизайнов
- addCSS(`.tag_edit, .tag_save {
- font-size: 130%;
- }
- .tag_remove, .tag_cancel {
- font-size: 120%
- }
- #tag_quest {
- padding: 7px
- }
- #tag_add {
- padding: 9px;
- }`);
- }
-
- function site() { // Весь сайт, кроме Игровой и её разделов
- if (globals.on_deletionWarning) {
- const el = $('.other_cats_list').first();
- if (el.length) {
- el.children().each(function (e) {
- const href = $(this).attr('href');
- const data = /login2\?id=(\d+)/.exec(href);
- let response = '[???]';
- if (data && data[1]) {
- response = '';
- const id = +data[1];
- let cat_data = getSettings(`reg_${id}`);
- if (cat_data) {
- cat_data = JSON.parse(cat_data);
- let date = new Date();
- date.setTime(date.getTime() + (date.getTimezoneOffset() + 180) * 60 * 1000);
- let diff = Math.floor(date.getTime() / 1000) - cat_data.regTime;
- diff = Math.floor(diff / 86400); // days alive
- let count = 45; // Время жизни
- if (diff > 365) {
- count = 120;
- }
- let lastOnline = new Date();
- lastOnline.setTime(cat_data.lastOnline * 1000);
- let inactive = Math.ceil((date - lastOnline) / (86400 * 1000));
- let ttl = count - inactive;
- if (ttl < 7) {
- response = `[!!!] `;
- }
- }
- }
- const text = $(this).text();
- $(this).html(`${text} ${response}`);
- });
- }
- }
- }
- function cw3() { //Игровая
- if (globals.on_settLink) {
- $('.small').first().append(` | Настройки модов `); //Настройки мода
- }
- if (no(globals.on_links)) {
- return;
- }
- if (globals.on_historyCleanWarning) {
- $(document).ready(function () {
- const istElem = $('#ist');
- addCSS(`#history_clean { display: none; }`);
- $('Очистить историю ').insertAfter('#history_block > #ist + br');
- if (istElem.text() == 'История очищена.') {
- $('#cws_history_clean').css('display', 'none');
- }
- $('body').on('click', '#cws_history_clean', function(e) {
- e.preventDefault();
- if (confirm('Точно очистить историю?')) {
- $('#history_clean')[0].click();
- }
- });
- var observer = new MutationObserver(function(mutationsList, observer) {
- const ist = $('#ist').text();
- $('#cws_history_clean').css('display', (istElem.text() == 'История очищена.' ? 'none' : 'inline'));
- });
- observer.observe(window.document.getElementById('ist'), {characterData: false, childList: true, attributes: false});
-
- });
- }
- if (globals.on_css_alternativeDivideGUI) {
- $("body").on('click', '#reveal_info li:has(.select_teil)', function () {
- $(this).find('.select_teil')[0].click();
- });
- addCSS(`#reveal_info > ul:has(.select_teil) { display: flex; flex-flow: row wrap; margin: 0; padding: 0; }
-#reveal_info > ul:has(.select_teil) > li { display: block; width: 70px; height: calc(70px + 1.25em); position: relative; background-repeat: no-repeat; margin: 0 0 .2em .5em; cursor: pointer; }
-#reveal_info > ul:has(.select_teil) > li > a { display: block; position: absolute; text-decoration: none; width: 70px; bottom: 0; text-align: center; }
-#reveal_info > ul:has(.select_teil) > li:nth-child(1) { background-image: url(/cw3/things/120.png); }
-#reveal_info > ul:has(.select_teil) > li:nth-child(2) { background-image: url(/cw3/things/121.png); }
-#reveal_info > ul:has(.select_teil) > li:nth-child(3) { background-image: url(/cw3/things/122.png); }
-#reveal_info > ul:has(.select_teil) > li:nth-child(4) { background-image: url(/cw3/things/123.png); }
-#reveal_info > ul:has(.select_teil) > li:nth-child(5) { background-image: url(/cw3/things/124.png); }
-#reveal_info > ul:has(.select_teil) > li:nth-child(6) { background-image: url(/cw3/things/125.png); }`);
- }
- if (globals.on_extraInfo) {
- $.fn.reveal=function(options){var defaults={animation:'fadeAndPop',animationspeed:300,closeonbackgroundclick:true,dismissmodalclass:'close-reveal-modal'};
- var options=$.extend({},defaults,options);return this.each(function(){var modal=$(this),topMeasure=parseInt(modal.css('top')),topOffset=modal.height()
- +topMeasure,locked=false,modalBG=$('.reveal-modal-bg');if(modalBG.length==0){modalBG=$('
').insertAfter(modal)} modal.bind(
- 'reveal:open',function(){modalBG.unbind('click.modalEvent');$('.'+options.dismissmodalclass).unbind('click.modalEvent');if(!locked){lockModal();if
- (options.animation=="fadeAndPop"){modal.css({'top':$(document).scrollTop()-topOffset,'opacity':0,'visibility':'visible'});modalBG.fadeIn(options.
- animationspeed/2);modal.delay(options.animationspeed/2).animate({"top":$(document).scrollTop()+topMeasure+'px',"opacity":1},options.animationspeed,
- unlockModal())}if(options.animation=="fade"){modal.css({'opacity':0,'visibility':'visible','top':$(document).scrollTop()+topMeasure});modalBG.fadeIn(
- options.animationspeed/2);modal.delay(options.animationspeed/2).animate({"opacity":1},options.animationspeed,unlockModal())}if(options.animation=="none")
- {modal.css({'visibility':'visible','top':$(document).scrollTop()+topMeasure});modalBG.css({"display":"block"});unlockModal()}}modal.unbind('reveal:open')}
- );modal.bind('reveal:close',function(){if(!locked){lockModal();if(options.animation=="fadeAndPop"){modalBG.delay(options.animationspeed).fadeOut(options.
- animationspeed);modal.animate({"top":$(document).scrollTop()-topOffset+'px',"opacity":0},options.animationspeed/2,function(){modal.remove();unlockModal()}
- )}if(options.animation=="fade"){modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);modal.animate({"opacity":0},options.animationspeed,
- function(){modal.remove();unlockModal()})}if(options.animation=="none"){modal.remove();modalBG.css({'display':'none'})}}modal.unbind('reveal:close')});
- modal.trigger('reveal:open');var closeButton=$('.'+options.dismissmodalclass).bind('click.modalEvent',function(){modal.trigger('reveal:close')});
- if(options.closeonbackgroundclick){modalBG.css({"cursor":"pointer"});modalBG.bind('click.modalEvent',function(){modal.trigger('reveal:close')})}$('body')
- .keyup(function(e){if(e.which===27){modal.trigger('reveal:close')}});function unlockModal(){locked=false}function lockModal(){locked=true}})}
- const cws_showModal = function(t, e) {
- $("#app").append('');
- $("#reveal").reveal();
- }
- const cws_catsInfo = {};
- $('body').on('mouseenter', '.cat', function () {
- const cat = $(this);
- let el = cat.find('.d');
- const link = cat.find('a').first();
- const catName = link.text();
- const cat_id = /\d+/.exec(link.attr('href'))[0];
- const defects = {};
- let el_composited, el_costume, size;
- el.children().each(function (e) {
- const bgImg = $(this).css('background-image');
- size = $(this).css('background-size');
- const isDefects = bgImg.indexOf('defects') > -1;
- if (bgImg.indexOf('defects') > -1) {
- const data = /cats\/-?\d+\/defects\/([a-z]+).*(\d+)\.png/.exec(bgImg)
- if (data) {
- const name = data[1], val = +(data[2]);
- defects[name] = val;
- }
- } else if (bgImg.indexOf('composited') > -1) {
- el_composited = $(this);
- } else if (bgImg.indexOf('costume') > -1 && el_costume === undefined) {
- el_costume = $(this);
- }
- });
- let image = "none";
- const hasGenerated = (el_composited !== undefined);
- if (hasGenerated) { // take composited
- image = /(composited\/[\da-f]{16})\.png/.exec(el_composited.css('background-image'))[1];
- } else if (el_costume !== undefined) { // take FIRST COSTUME
- image = /(cats\/-?\d+\/costume\/\d+)\.png/.exec(el_costume.css('background-image'))[1];
- }
- const pol = !!(/Его запах/.exec(cat.html()));
- cws_catsInfo[cat_id] = {
- "name" : catName,
- hasGenerated,
- image,
- defects,
- size,
- pol,
- };
- if (!cat.find('.cws-show-more').length) {
- cat.find('.online').before(`Подробнее `);
- } else {
- cat.find('.cws-show-more').data('id', cat_id);
- }
- });
- $('body').on('click', '.cws-show-more', function (e) {
- e.preventDefault();
- let text = "Ничего не нашли грустно...";
- let title = "Информация";
- const id = $(this).data('id');
- const info = cws_catsInfo[id];
- if (info) {
- title = `${info.name} `;
- text = ``;
- text += ``;
- text += ` `;
- text += ``;
- text += `Пол: ${info.pol ? "кот" : "кошка"} `;
- text += `Рост: ${info.size}${+(info.size.replace('%', '')) == 101 ? " (надута)" : ""}
`;
- if (Object.keys(info.defects).length > 0) {
- const defects_list = {
- "poisoning" : {
- name : "Отравления",
- states : { "1" : "недомогание", "2" : "лёгкое отравление", "3" : "сильное отравление", "4" : "смертельное отравление", }
- },
- "wound" : {
- name : "Раны",
- states : { "1" : "царапины", "2" : "лёгкие раны", "3" : "глубокие раны", "4" : "смертельные раны", }
- },
- "drown" : {
- name : "Травмы от утопления",
- states : { "1" : "cсадины", "2" : "небольшие кровоподтёки", "3" : "сильные травмы", "4" : "смертельные травмы", }
- },
- "disease" : {
- name : "Болезнь",
- states : { "1" : "кашель", "2" : "", "3" : "", "4" : "", }
- },
- "trauma" : {
- name : "Переломы",
- states : { "1" : "синяки", "2" : "лёгкие ушибы", "3" : "сильные ушибы", "4" : "смертельные ушибы", }
- },
- "dirt" : {
- name : "Грязь",
- states : { "1" : "грязные лапы", "2" : "грязевые пятна", "3" : "клещи", "4" : "блохи", }
- },
- };
- const defects = [];
- for (const defect in info.defects) {
- const value = info.defects[defect];
- const name = defects_list[defect] && defects_list[defect].name || defect;
- const flavor = defects_list[defect] && defects_list[defect].states[value] || "неизвестно";
- defects.push(`${name} : ${value} стадия (${flavor})`);
- }
- text += defects.join(" ");
- } else {
- text += `Здоров${info.pol ? "" : "а"}`;
- }
- text += ` `;
- text += ` `;
- text += `
`;
- }
- cws_showModal(title, text);
- });
- }
- if (globals.on_smellTimer) {
- $(document).ready(function () {
- $('.small').first().append(` | Нюх через: 0 с `);
- let smellActive = 0;
- let smellOtherActive = 0;
- let firstNote = "";
- let rang = true;
-
- function smellTimerTick() {
- let val = parseInt($('#cws_smell_timer').attr('value'));
- if (val) {
- rang = false;
- val--;
- $('#cws_smell_timer').attr('value', val);
- let str = '';
- let hr = parseInt(val / 3600);
- let mi = parseInt((val - hr * 3600) / 60);
- let se = parseInt(val - (hr * 3600 + mi * 60));
- str += (hr) ? hr + ' ч ' : '';
- str += (mi || hr) ? mi + ' мин ' : '';
- str += se + ' с';
- $('#cws_smell_timer').html(str);
- }
- else if (globals.on_smellTimerNotif && !rang) {
- playAudio(sounds.action_notif, globals.sound_smellTimer);
- rang = true;
- }
- }
- setInterval(smellTimerTick, 1000);
- //TODO: сделать так, чтоб таймер не запускался вообще, пока есть действие нюха, т.е. value != 0
- let firstClick = setInterval(function () { //господи я ненавижу варовскую привычку сначала создавать элемент а потом вставлять в него данные
- if ($('#smell_icon').length) {
- firstNote = $('#error').html();
- $('#smell_icon').click();
- clearInterval(firstClick);
- }
- }, 500);
-
- $("body").on('DOMNodeInserted', '#dein', 'a[data-id=14]', function () {
- let isActive = $('#dein a[data-id=14]').length;
- if (!smellOtherActive && isActive) { //Отменено действие нюха
- $('#cws_smell_timer').attr('value', 0);
- $('#cws_smell_timer').html('0 с');
- }
- smellOtherActive = isActive;
- });
- const smell_timer = {"0": 3600,"1": 3600,"2": 3600,"3": 3600,"4": 1800,"5": 1200,"6": 900,"7": 720,"8": 600,"9": 0};
- $("body").on('DOMNodeRemoved', '#dein', 'a[data-id=14]', function () {
- let isActive = $('#dein a[data-id=14]').length;
- if (smellOtherActive && !isActive) { //Нажато действие нюха
- let smell_lv = $('#smell b').text(),
- smell_time = smell_timer[smell_lv],
- str = '',
- mi = smell_time / 60,
- se = smell_time - mi * 60;
- str += (mi) ? mi + ' мин ' : '';
- str += se + ' с';
- $('#cws_smell_timer').attr('value', smell_time);
- $('#cws_smell_timer').html(str);
- }
- smellOtherActive = isActive;
- });
-
- $("body").on('DOMSubtreeModified', '#error', function () {
- let html = $(this).html();
- if (html && html.indexOf('Следующее обнюхивание') !== -1) {
- let text = html.replace('Следующее обнюхивание будет доступно через ', '');
- let smellMin = (text.match(/(\d+) мин/g) == null) ? 0 : parseInt(text.match(/(\d+) мин/g)[0].replace(/\D/g, ''));
- let smellSec = parseInt(text.match(/(\d+) с/g)[0].replace(/\D/g, ''));
- let totalSec = smellMin * 60 + smellSec;
- $('#cws_smell_timer').attr('value', totalSec);
- $('#cws_smell_timer').html(smellMin + ' мин ' + smellSec + ' с');
- if (firstNote !== "") { //Чтоб не перекрывало уведомления о ранах, голоде и т.д.
- $('#error').html(firstNote);
- firstNote = "";
- }
- }
- else if (html.indexOf('Час уже прошёл') !== -1 && firstNote !== "") {
- $('#error').html(firstNote);
- firstNote = "";
- }
- });
- });
- }
- if (globals.on_oldDialogue) {
- $(document).ready(function () {
- $("body").on('DOMNodeInserted', '#text', function () {
- $(this).attr('size', 1);
- });
- });
- }
- if (globals.on_catsDown) { //опускаем котов вниз вместе со стрелами
- $(document).ready(function () {
- $('head').append(``);
- $("body").on('DOMSubtreeModified DOMNodeInserted', '.catWithArrow', function (e) {
- let $arrow = $(this).find('.arrow');
- let topval = $arrow.css('top');
- if (topval) {
- let int_topval = parseInt(topval.replace('px', ''));
- if (int_topval > 0) {
- $arrow.css('bottom', topval);
- $arrow.css('top', '');
- }
- }
- });
- });
- }
- if (globals.on_charInline) {
- addCSS(`.other_cats_list + br {display: none;}.other_cats_list::after {content: " ||";}.other_cats_list {border: none;}`);
- }
- if (+globals.on_localTimer) {
- const getTimeStr = function() {
- const date = new Date();
- if (+globals.on_localTimer == 2) {
- date.setTime(date.getTime() + (date.getTimezoneOffset() + 180) * 60 * 1000);
- }
- return date.toLocaleTimeString() + " "
- + ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'][date.getDay()] + ', '
- + date.getDate() + ' ' + ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'][date.getMonth()];
- }
- if (isDesktop) {
- addCSS(`#cws_localTimer {color: #d7d7d7;background-color: #00000096;padding: 0 1em;font-size: 12px;line-height:2.2}#tr_tos > td {display: flex;justify-content: space-between;}`);
- } else {
- addCSS(`#cws_localTimer {color: #d7d7d7;background-color: #00000096;padding: 0 1em 0.3em 1em;font-size: 12px}`);
- }
- $('#tr_tos > td').append('' + getTimeStr() + '
');
- setInterval(function () {
- $('#cws_localTimer').html(getTimeStr());
- }, 1000);
- }
- if (globals.on_charHide) {
- addCSS(`.other_cats_list {display: none;}.other_cats_list + br {display: none;}`);
- }
- if (globals.on_newDM) {
- let newDM = 0;
- const dm_observer = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutationRecord) {
- if (mutationRecord.type === "characterData") {
- let newDMtmp = $("#newls").text();
- if (newDMtmp !== undefined) {
- newDMtmp = (newDMtmp === '') ? 0 : +(newDMtmp.replace(/\D/gi, ''));
- if (newDMtmp > newDM) {
- playAudio(sounds.new_message, globals.sound_newDM);
- }
- newDM = newDMtmp;
- }
- }
- });
- });
- dm_observer.observe(document.getElementById('newls'), { subtree: true, characterData: true });
- }
- if (globals.on_newChat) {
- let newChat = 0;
- $('body').on('DOMSubtreeModified', '#newchat', function () { // deprecated, todo: remove/update
- let newChattmp = $(this).html();
- if (newChattmp !== undefined) {
- newChattmp = (newChattmp === '') ? 0 : parseInt(newChattmp.replace(/\D/gi, ''));
- if (newChattmp > newChat) {
- playAudio(sounds.new_message, globals.sound_newChat);
- }
- newChat = newChattmp;
- }
- });
- }
- if (globals.on_customChat) {
- let messages = 1;
- if (isDesktop) {
- addCSS('#cws_chat_msg {width: 1000px;} .chat_text {width: 935px;}');
- }
- else {
- addCSS('#cws_chat_msg {width: 100% !important;} .chat_text {line-break: anywhere;}');
- }
- addCSS(`#chat_msg {display: none;}#cws_chat_msg {overflow: auto;height: 275px;}.cws_chat_wrapper{display: -webkit-flex;padding: 0 .25em;display: flex;}
- .cws_chat_msg {-webkit-flex: auto;flex: auto;-webkit-flex-direction: row;flex-direction: row;}.cws_chat_report {width: 42px;}.cws_chat_report {-webkit-touch-callout: none;
- -webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}`);
- // варомод (почему вы просите добавить совместимость меня, когда совместимость проще добавить тому кто сделал эту компактную игровую?)
- const hvo_settings = JSON.parse(window.localStorage.getItem('cwmod_settings') || '{}');
- if (hvo_settings.cw3_compact) {
- addCSS(`#cws_chat_msg { width: auto !important; height: 350px; padding: 2px; }`);
- }
- if (globals.on_chatReverse) {
- $('
').insertBefore('#chat_form');
- }
- else {
- $('
').insertAfter('#chat_form');
- }
- let scroll = false; // была прокрутка до предыдущих сообщений
- const chatTarget = document.getElementById('chat_msg');
- const chatObserver = new MutationObserver(function (mutationsList, observer) {
- let name_heard = false;
- let last_mutation = mutationsList[mutationsList.length - 1].target;
- let msg_new = last_mutation.children.length;
- let msg_blocks = last_mutation.children;
- for (let i = messages + 1; i <= msg_new; i++) { // Добавление во временный чат новых сообщений
- let block = msg_blocks[msg_new - i];
- if (block.nodeName == "SPAN") {
- let msg = block.getElementsByClassName('chat_text')[0],
- classList = msg.classList.value,
- text = msg.querySelectorAll('span')[0].innerHTML,
- nick = msg.getElementsByClassName('nick')[0].outerHTML,
- bot_resp = msg.querySelectorAll('b + span')[0],
- bot_msg = (bot_resp === undefined) ? '' : bot_resp.outerHTML,
- report = block.querySelectorAll('td[style="width: 42px;"]')[0],
- cat_id = report.querySelectorAll('a[href^="/cat"]')[0].getAttribute('href'),
- silent_bot = msg.querySelectorAll('.nick[style*="italic"]').length,
- cat_title = '';
- cat_id = parseInt(cat_id.replace(/\D/g, ''));
- let cat_id_format = (globals.on_idChat && !silent_bot) ? ` [${cat_id}] ` : '';
- let has_nickname = false;
- if (globals.on_nickHighlight) { // Покрасить ники в myname
- $.each(globals.nickListArray, function (index, key) {
- let expr = new RegExp('^(' + key + ')[^А-ЯЁёA-Za-z0-9]|[^А-ЯЁёA-Za-z0-9>](' + key + ')[^А-ЯЁёA-Za-z0-9<]|[^А-ЯЁёA-Za-z0-9](' + key + ')$|^(' + key + ')$', "ig");
- if (text.match(expr)) { //есть имя и оно ещё не внутри тега
- let matchAll = text.matchAll(expr);
- matchAll = Array.from(matchAll); // теперь массив
- $.each(matchAll, function (index, value) {
- let replacer = value[1] || value[2] || value[3] || value[4]; //То, что было найдено (4 местоположения key, 4 варианта регулярки)
- text = text.replace(value[0], value[0].replace(replacer, '' + replacer + ' '));
- has_nickname = true;
- });
- }
- });
- }
- if (globals.on_chatMention && !name_heard) { // Если в текущем сообщении есть myname и !name_heard - проиграть звук и выставить name_heard = true
- let has_myname = msg.getElementsByClassName('myname').length;
- if (has_myname || has_nickname) {
- let is_bot = msg.getElementsByTagName('i').length;
- if (jQuery.inArray(cat_id, globals.cm_blocked) == -1 && !is_bot) { //ЕСЛИ НЕ В МАССИВЕ ИГНОРИРУЕМЫХ и не бот
- playAudio(sounds.chat_mention, globals.sound_chatMention);
- name_heard = true; // чтоб не спамило звуки, когда загружаешь страницу а там чел твое имя 228 раз написал
- }
- }
- }
- // Если надо свапнуть (и ID включены, иначе будет жирный пробел перед должностью)
- let result = `
-
- ${text} - ${nick}${cat_title} ${cat_id_format}
- ${bot_msg}
-
-
-
${report.outerHTML}
-
`;
- if (globals.on_chatReverse) {
- $('#cws_chat_msg').append(result);
- $('#cws_chat_msg').append(' ');
- if (!scroll) {
- $('#cws_chat_msg')[0].scrollTop = $('#cws_chat_msg')[0].scrollHeight;
- }
- }
- else {
- $('#cws_chat_msg').prepend(result);
- $('#cws_chat_msg').prepend(' ');
- }
- }
- }
- messages = mutationsList[mutationsList.length - 1].target.children.length;
- });
- chatObserver.observe(chatTarget, {
- childList: true
- });
-
- $('#cws_chat_msg').on('click', '.nick', function () { // потому что клик на ник с ориг чата работает только на ориг чат фу бе
- let $text = $('#text');
- $text.val($text.val() + $(this).text() + ', ');
- $text.focus();
- });
- $('#cws_chat_msg').on('click', '.msg_report', function () { // потому что клик на жалобу с ориг чата тоже работает только на ориг чат
- let id = $(this).data('id');
- $('#chat_msg .msg_report[data-id="' + id + '"]')[0].click(); // почему вообще нельзя одновременно кликнуть на несколько элементов массива это глупо jq
- });
- if (globals.on_chatReverse) {
- $('#cws_chat_msg').on('scroll', function () { // потому что клик на жалобу с ориг чата тоже работает только на ориг чат
- let $e = $('#cws_chat_msg');
- if ($e.scrollTop() + $e.height() >= $e[0].scrollHeight - 45) { // прокручено до конца
- scroll = false;
- }
- else {
- scroll = true;
- }
- });
- }
-
- }
- if (globals.on_idItemMouth) {
- let item_names_json = {};
- $(document).ready(function () {
- $.getJSON("https://reireirei72.github.io/zero-t-18883/shed/item_names.json?" + Date.now(), function (response) { //Подгрузка имен предметов из json файла
- item_names_json = response;
- $("#thdey > ul").append('Название предмета: [ Неизвестно ] [? ] ');
- $("body").on('click', "#itemList .itemInMouth", function () {
- if ($(this).hasClass("active_thing")) {
- let item_id = $(this).find("img").attr("src").replace(/\D/g, "");
- let name = item_names_json[item_id] || "[ Неизвестно ]";
- $("#item_name_ide").html(name);
- $("#item_id_ide").html(item_id);
- }
- });
- });
- });
- }
- if (globals.on_idCatMouth) {
- $(document).ready(function () {
- $("#ctdey > ul").append('ID кота: [ Не определено ] ');
- $("body").on('click', "#itemList .catrot", function () {
- if ($(this).hasClass("active_thing")) {
- $("#cat_id_ide").html($(this).attr('id'));
- }
- });
- });
- }
- if (globals.on_actNotif) {
- function which_action(text) {
- const act_detect = {
- "move": "Переход",
- "eat": [" дичь", "Перекусывать"],
- "need": "Делаем свои дела",
- "drink": "Пьём ещё",
- "dig": "Копать",
- "sleep": "Сон",
- "sniff": "нюх",
- "digin": "Закапывать",
- "clean": "Вылизывать",
- "swim": "Плавать",
- "fill_moss": "Наполнять мох",
- "dive": "Нырять",
- "murr": "Мурлыкать",
- "tails": "Переплетаем хвосты",
- "cheek": "Трёмся щекой",
- "ground": "Валяем по земле",
- "rub": "Тереться носом о нос",
- "calm": "Успокаиваться",
- "watch": "Осматривать окрестности",
- "marking": "Помечать территорию",
- "clawscratch": "Точить когти",
- "rug": "Чистить ковёр",
- "attention": "Привлекать внимание",
- "domestsleep": "Спать ",
- "domesthunt": "Грандиозно охотиться ",
- "checkup": "Осматривать к",
- "loottr": "Осматривать дупло",
- "lootcr": "Осматривать расщелину"
- };
- const act_flav_text = {
- "move": "Переход",
- "eat": "Поедание дичи",
- "need": "Справление нужды",
- "drink": "Питьё",
- "dig": "Копание",
- "sleep": "Сон",
- "sniff": "Нюх",
- "digin": "Закапывание",
- "clean": "Вылизывание",
- "swim": "Плавание",
- "fill_moss": "Наполнение мха",
- "dive": "Ныряние",
- "murr": "Мурлыкаем",
- "tails": "Переплетаем хвосты",
- "cheek": "Трёмся щекой",
- "ground": "Валяем по земле",
- "rub": "Трёмся носом о нос",
- "calm": "Выход из боевой стойки",
- "watch": "Осмотр окрестностей",
- "marking": "Пометка территории",
- "clawscratch": "Затачивание когтей",
- "rug": "Чистка ковра",
- "attention": "Привлечение внимания",
- "domestsleep": "Сон в лежанке",
- "domesthunt": "Грандиозная охота",
- "checkup": "Осмотр целителем",
- "loottr": "Осмотр дупла",
- "lootcr": "Осмотр расщелины"
- };
- let wh_act = {
- txt: null,
- snd: false
- };
- $.each(act_detect, function (actid, acttext) {
- if (!(acttext instanceof Array)) {acttext = [acttext];}
- for (let textinstance in acttext) {
- if (text.indexOf(acttext[textinstance]) !== -1) {
- if (globals["txt_act_" + actid]) wh_act.txt = act_flav_text[actid];
- if (globals["snd_act_" + actid]) wh_act.snd = true;
- return wh_act;
- }
- }
-
- });
- return wh_act;
- }
- let rang = false;
- let move_ok = false; // можно проигрывать звук
- let action = which_action($("#block_mess").text() || "");
- var actionNotificationObserver = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutationRecord) {
- if (mutationRecord.type === "characterData") {
- let match = $('#block_mess').text().match(/(\d+\sч\s)?(\d+\sмин\s)?(\d+\sс)/u);
- if (match) {
- let time = match[0].trim();
- action = which_action($("#block_mess").text() || "");
- if (time == '7 с' || time == '6 с') move_ok = true; //Действие длится хотя бы 7 секунд -С МОМЕНТА ОТКРЫТИЯ ИГРОВОЙ-
- if (action.txt !== null) $('title').text(time + " / " + action.txt); //Сменить титульник, если текст на это действие включен
- let datenow = new Date();
- if (!action.snd) rang = true; //Реагировать только на нужные навыки ("звук был" = да)
- if ((time === '3 с' || time === '2 с' || time === '1 с') && !rang && move_ok) { //Свернутая вкладка обновляется каждые 2-3 секунды, F // До конца действия 1-3 сек, звука ещё не было/звук включен, звук можно проигрывать
- playAudio(sounds.action_notif, globals.sound_notifEndAct);
- rang = true;
- move_ok = false;
- }
- } else {
- $('title').text('Игровая / CatWar');
- rang = false;
- move_ok = false;
- }
- }
- });
- });
- const actParentNode = document.getElementById('tr_actions').children[0];
- actionNotificationObserver.observe(actParentNode, { subtree: true, childList: true, characterData: true, characterDataOldValue: true, });
- }
- if (globals.notif_eaten) { //Уведомления, когда вас поднимают
- var pickNotificationObserver = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutationRecord) {
- if (mutationRecord.type === "characterData") {
- if ($("#block_mess").html().indexOf("Вы не сможете выбраться") !== -1) {
- $('title').text("Во рту");
- playAudio(sounds.action_notif, globals.sound_notifEaten);
- }
- if ($("#block_mess").html() === "" && !globals.on_actNotif) { //Если пуст, действий нет (нужно, если нет уведомлений на действия)
- $('title').text('Игровая / CatWar');
- }
- }
- });
- });
- const actParentNode = document.getElementById('tr_actions').children[0];
- pickNotificationObserver.observe(actParentNode, { subtree: true, childList: true, characterData: true, characterDataOldValue: true, });
- }
- if (globals.notif_attack) {
- const attackObserver = new MutationObserver(function(mutations) {
- let last_note = $($("#ist").html().split('.')).get(-2);
- if (last_note !== undefined) {
- if (last_note.indexOf("в боевую стойку, поскольку на меня напал") !== -1) {
- playAudio(sounds.alert_attacked, globals.sound_notifBeaten);
- }
- }
- });
- attackObserver.observe(document.getElementById('ist'), { characterData: false, childList: true, attributes: false });
- }
- if (globals.on_moveFightLog) {
- $('#app').ready(function () { //Возможность перетаскивать панель лога боя
- $('head').append(``);
- $("#fightPanel").prepend(` `);
- $("#fightPanel").draggable({
- handle: "#fightPanelHandle"
- });
- });
- }
- if (globals.on_blockNotif) {
- let block = false;
- $('#app').ready(function () {
- $('#block').on('load', function () {
- if ($(this).attr('src') == 'symbole/lock.png') { //locked
- block = true;
- playAudio(sounds.block_start, globals.sound_blockStart);
- }
- else if (block) { //unlocked
- block = false;
- playAudio(sounds.block_end, globals.sound_blockEnd);
- }
- });
- });
- }
- if (globals.fight_log_max_height != 70) {
- $('#fightLog').css('height', globals.fight_log_max_height);
- }
- if (globals.on_shortFightLog) {
- $(document).ready(function () {
- let prev_log = '';
- let prev_class = '';
- var shortLogObserver = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutationRecord) {
- if (mutationRecord.type === "childList") {
- mutationRecord.addedNodes.forEach((node) => {
- if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === "SPAN" && !node.classList.contains("cws-hit-count")) {
- let this_log = node.textContent, this_class = node.getAttribute("class");
- if (this_log == prev_log && prev_class == this_class) {
- node.remove();
- $('#fightLog > br:first-child').remove();
- let $to_change = $('.cws-hit-count').first();
- let count = +($to_change.attr('count'));
- count++;
- $to_change.attr('count', count);
- $to_change.html(' (х' + count + ')');
- } else {
- $(' ').insertAfter(node);
- }
- prev_log = this_log;
- prev_class = this_class;
- }
- });
- }
- });
- });
- shortLogObserver.observe(document.getElementById('fightLog'), { subtree: true, childList: true });
- });
- }
- if (globals.on_teamFights) {
- $('head').append(``); //Определение цветов команд
- $('head').append(``); //Заготовка раскраски команд
- $("#app").ready(function () {
- let ids = {}; //Список айди
- $("#fightPanel").append(``); //Добавление списка в панель бр
- $("#refresh-team").on("click", function () { //Кнопка "Обновить"
- $('#fightColors > tr').each(function () { //Удалить старое
- let id = $(this).attr('id').match(/\d+/)[0];
- if (!$("#arrow" + id).length) { //если не существует кота из списка в боережиме
- $("#team_member_" + id).remove();
- delete ids[id];
- }
- });
- $('.arrow').each(function () {
- let id = $(this).attr('id').match(/\d+/)[0];
- if (!ids[id]) { //Добавить новое
- ids[id] = 1; //team 1
- let name = $(".cat_tooltip a[href='/cat" + id + "']").html();
- $("#fightColors").append(`${name}
- *
- *
- *
- *
- `);
- }
- });
- });
- $(document).on('change', '.cws-team-chk', function () { //Изменение команды при клике
- let id = $(this).attr('id').match(/\d+/)[0];
- ids[id] = parseInt($(this).val());
- let style = '\n'; //Формирование нового стиля
- $.each(ids, function (id, team) {
- style += `#arrow${id} .arrow_green {background: var(--team${team}g);}\n#arrow${id} .arrow_red {background: var(--team${team}r);}\n`;
- });
- $('#cws_team_fights').html(style);
- });
- });
- }
- if (globals.on_cleanerHistory) {
- let titles = {};
- let statuses = {};
- const convert = {
- "Котёнок": "котёнка",
- "Оруженосец": "оруженосца",
- "Старший оруженосец": "старшего оруженосца",
- "Ученица целителя": "ученицу целителя",
- "Ученик целителя": "ученика целителя",
- "Целительница": "целительницу",
- "Целитель": "целителя",
- "Воительница": "воительницу",
- "Воитель": "воителя",
- "Старшая воительница": "старшую воительницу",
- "Старший воитель": "старшего воителя",
- "Старейшина": "старейшину",
- "Глашатая": "глашатую",
- "Глашатай": "глашатая",
- "Предводительница": "предводительницу",
- "Предводитель": "предводителя",
- "Будущая стражница": "будущую стражницу",
- "Будущий страж": "будущего стража",
- "Будущая охотница": "будущую охотницу",
- "Будущий охотник": "будущего охотника",
- "Стражница": "стражницу",
- "Страж": "стража",
- "Охотница": "охотницу",
- "Охотник": "охотника",
- "Врачеватель": "врачевателя",
- "Ученица врачевателя": "ученицу врачевателя",
- "Ученик врачевателя": "ученика врачевателя",
- "Ученица": "ученицу",
- "Ученик": "ученика",
- "Молодой воин": "молодого воина",
- "Воин": "воина",
- "Старший воин": "старшего воина",
- "Учитель": "учителя",
- "Воин света": "воина света",
- "Слышащая": "слышащую",
- "Слышащий": "слышащего",
- "Ученица слышащего": "ученицу слышащего",
- "Ученик слышащего": "ученика слышащего",
- "Доверенная": "доверенную",
- "Доверенный": "доверенного",
- "Наследница": "наследницу",
- "Наследник": "наследника",
- "Хранитель моря": "хранителя моря",
- "Верховная хранительница покоя": "верховную хранительницу покоя",
- "Верховный хранитель покоя": "верховного хранителя покоя",
- "Верховная добытчица": "верховную добытчицу",
- "Верховный добытчик": "верховного добытчика",
- "Верховная жрица": "верховную жрицу",
- "Верховный жрец": "верховного жреца",
- "Глава Верховного Совета": "главу Верховного Совета",
- "Советница верховного жреца": "советницу верховного жреца",
- "Советник верховного жреца": "советника верховного жреца",
- "Советница верховного хранителя покоя": "советницу верховного хранителя покоя",
- "Советник верховного хранителя покоя": "советника верховного хранителя покоя",
- "Советница верховного добытчика": "советницу верховного добытчика",
- "Советник верховного добытчика": "советника верховного добытчика",
- "Лунная жрица": "лунную жрицу",
- "Лунный жрец": "лунного жреца",
- "Добытчица": "добытчицу",
- "Добытчик": "добытчика",
- "Хранительница покоя": "хранительницу покоя",
- "Хранитель покоя": "хранителя покоя",
- "Ученица хранителей покоя": "ученицу хранителей покоя",
- "Ученик хранителей покоя": "ученика хранителей покоя",
- "Ученица добытчиков": "ученицу добытчиков",
- "Ученик добытчиков": "ученика добытчиков",
- "Старец": "старца",
- "Королева": "королеву",
- "Наследник хранителя": "наследника хранителя",
- "Хранительница солнца": "хранительницу солнца",
- "Хранитель солнца": "хранителя солнца",
- "Заместительница глашатая": "заместительницу глашатая",
- "Заместитель глашатая": "заместителя глашатая",
- "Восходящая": "восходящую",
- "Восходящий": "восходящего",
- "Командор серых стражей": "командора серых стражей",
- "Ведущая": "ведущую",
- "Ведущий": "ведущего",
- "Ученица Луны": "ученицу Луны",
- "Ученик Луны": "ученика Луны",
- "Королева": "королеву",
- "Заботливый отец": "заботливого отца",
- "Ведущая воительница": "ведущую воительницу",
- "Ведущий воитель": "ведущего воителя",
- "Молодая воительница": "молодую воительницу",
- "Молодой воин": "молодого воина",
- "Помощница ученика врачевателя": "помощницу ученика врачевателя",
- "Помощник ученика врачевателя": "помощника ученика врачевателя",
- "Старший оруженосец": "старшего оруженосца",
- "Переходящая": "переходящую",
- "Переходящий": "переходящего",
- "Советница": "советницу",
- "Советник": "советника",
- "Воспитанник": "воспитанника",
- "Воспитанница": "воспитанницу",
- "Старший воспитанник": "старшего воспитанника",
- "Старший воспитанница": "старшую воспитанницу",
- "Вождь": "вождя",
- "Мудрец": "мудреца",
- "Искусник": "искусника",
- "Наместник": "наместника",
- "Пилигрим": "пилигрима",
- "Ловец": "ловца",
- "Шаман": "шамана",
- "Кормилица": "кормилицу",
- "Воевода": "воеводу"
- };
-
- function title_convert(title) {
- return convert[title] || title;
- }
- if (globals.clean_title || globals.clean_status) {
- $(document).ready(function () {
- const catsCagesObserver = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutationRecord) {
- if (mutationRecord.type === "childList") {
- mutationRecord.removedNodes.forEach((node) => {
- if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains("catWithArrow")) {
- const linkNode = node.querySelector('.cat_tooltip > u > a');
- if (linkNode) {
- let href = linkNode.getAttribute('href');
- if (href !== undefined) {
- let cat_id = href.replace(/\D/g, '');
- if (titles[cat_id] === undefined) {
- let titleElem = node.innerHTML.match(/([^<]+)<\/i><\/small><\/div>/ui);
- if (titleElem !== null && titleElem[1]) {
- titles[cat_id] = titleElem[1];
- }
- }
- let status = node.querySelector('.online').textContent; // [ На удалении ]
- let is_punished = node.querySelector('div[style*="costume/295."]'); // Подстилки?
- if (is_punished) {
- status = "[ В подстилках ]";
- }
- statuses[cat_id] = status;
- }
- }
- }
- });
- }
- });
- });
- catsCagesObserver.observe(document.getElementById('cages'), { subtree: true, childList: true, attributes: false });
- });
- }
- let first_load = true;
- let cl_history = (window.localStorage.getItem('cws_cleaner_history_log') !== null) ? window.localStorage.getItem('cws_cleaner_history_log') : 'История очищена.';
- cl_history = ((globals.clean_underscore) ? cl_history.replace(/ (Подняла?|Опустила?) /ig, ' $1 ') : cl_history.replace(/ (Подняла?|Опустила?)<\/u> /ig, ' $1 '));
- $("#ist").ready(function () {
- // ДОБАВЛЕНИЕ ЛОГА ЧИСТИЛЬЩИКОВ
- $('' + cl_history + ' Очистить историю чистки ').insertAfter("#history_clean");
- let prev_ist, prev_prev_ist;
-
- const cleanHistObserver = new MutationObserver(function(mutations) {
- if (first_load) {
- first_load = false;
- } else {
- const testDate = new Date();
- console.log('cleanHistObserver triggered at', testDate.getTime());
- let last_ist = $("#ist").html().split('.');
- last_ist = last_ist[last_ist.length - 2];
- if (last_ist !== undefined) {
- console.log('Последняя запись в истории:', last_ist);
- let clean_id = last_ist.match(/cat(\d+)/);
- if (clean_id) {
- clean_id = clean_id[1];
- }
- last_ist = last_ist.trim().replace(/(<([^>]+)>)/ig, '');
- if (((last_ist.indexOf("Поднял") !== -1) || (last_ist.indexOf("Опустил") !== -1)) && ((last_ist.indexOf("кота") !== -1) || (last_ist.indexOf("кошку") !== -1))) { //Если есть "поднял(а)/опустил(а) кота/кошку"
- console.log('В последней записи найдено "Поднял/опустил", ID жертвы:', clean_id);
- let hist_str = ' ' + ((globals.clean_underscore) ? last_ist.replace(/(Подняла*|Опустила*)/, '$1 ') : last_ist);
- if (globals.clean_id) {
- hist_str += ' (' + clean_id + ')';
- } //Записать ID
- if (globals.clean_status && (last_ist.indexOf("Поднял") !== -1) && statuses[clean_id] !== undefined) {
- hist_str += ' ' + statuses[clean_id];
- }
- if (globals.clean_location) {
- hist_str += ' в локации «' + $("#location").html() + '»';
- } //Записать локацию
- hist_str += '.';
- if ((globals.clean_action) && // следить за проверками
- (last_ist.indexOf("Поднял") !== -1) &&
- (prev_prev_ist !== undefined) && // поза-позапрошлая запись есть
- (prev_ist.indexOf("Отменил") !== -1) && //Отменил действие
- (prev_prev_ist.indexOf("по имени") !== -1) && //Перед этим взаимодействуя с кем-то
- (prev_prev_ist.indexOf("Поднял") === -1) && //Не поднял и не опустил
- (prev_prev_ist.indexOf("Опустил") === -1)) {
- let clean_curr_name = last_ist.match(/ по имени ([А-Яа-яЁё ]+)/u) || ['', ''];
- let clean_check_name = prev_prev_ist.match(/ по имени ([А-Яа-яЁё ]+)/u) || ['', ''];
- if (clean_check_name[1] !== '' && clean_check_name[1] == clean_curr_name[1]) { //Имя проверенного и имя поднятого одинаковые
- let their_pol = (last_ist.indexOf("кошку") !== -1) ? 'кошку' : 'кота';
- let ur_pol = (last_ist.indexOf("Подняла") !== -1) ? 'Проверила' : 'Проверил';
- hist_str = ' ' + ur_pol + ' ' + their_pol + ' по имени ' + clean_check_name[1] + '.' + hist_str;
- }
- }
- if (globals.clean_title && titles[clean_id]) { //Поменять на должность
- hist_str = hist_str.replace(/(кота|кошку)/g, title_convert(titles[clean_id]));
- }
- console.log('Добавляем к истории чистки запись:', hist_str);
- if ($("#location").html() != '[ Загружается… ]' && hist_str !== undefined) { //ок?
- $('#cleaner_block').append(hist_str);
- window.localStorage.setItem('cws_cleaner_history_log', $('#cleaner_block').html());
- }
- }
- prev_prev_ist = prev_ist;
- prev_ist = last_ist;
- }
- }
- });
- cleanHistObserver.observe(document.getElementById('ist'), { characterData: false, childList: true, attributes: false });
- $('#erase_cleaner').on('click', function () {
- $('#cleaner_block').html("История очищена.");
- window.localStorage.setItem('cws_cleaner_history_log', 'История очищена.');
- });
- });
- }
- if (globals.on_treeTechies) {
- if (globals.tt_notif_refresh) {
- $("#ist").ready(function () {
- let last_note, note_first = true;
- const treeRefreshObserver = new MutationObserver(function(mutations) {
- last_note = $($("#ist").html().split('.')).get(-2); //Последняя запись в истории
- if (last_note !== undefined) {
- if (/Услышала? оглушительн/.test(last_note) && !note_first) {
- playAudio(sounds.tt_refresh, globals.sound_ttRefresh);
- }
- note_first = false; //История была уже прочитана 1 раз, и страница не только что загрузилась
- }
- });
- treeRefreshObserver.observe(document.getElementById('ist'), { characterData: false, childList: true, attributes: false });
- });
- }
- $('#app').ready(function () {
- $('head').append(``);
- if (globals.tt_dark_theme) {
- $('head').append(``);
- }
- if (globals.tt_show_volume) {
- $('head').append(``);
- }
- const tt_field_def = `
-
-
-
-
- `;
- let tt_fields = getSettings('tt_fields') === null ? [tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def,
- tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def, tt_field_def,
- tt_field_def, tt_field_def, tt_field_def, tt_field_def
- ] : JSON.parse(getSettings('tt_fields'));
- let mines_html = `
-
-
`;
- for (let i = 1; i <= 23; i++) {
- if (globals.tt_pageenabledArray[i]) {
- mines_html += `
`;
- }
- }
- mines_html += `
Очистить всё поле `;
- $('#app').append(mines_html);
- let proj = false; //свитч переноса
- let page = 0; //страница
- let text = '0';
- let mark = 'cws-tt-safe';
- $("#cws_treeTechies").draggable({
- containment: "document",
- handle: "#cws_treeTechiesHandle",
- drag: function () {
- let offset = $(this).offset();
- let xPos = offset.left;
- let yPos = offset.top;
- setSettings('tt_window_left', offset.left);
- setSettings('tt_window_top', offset.top);
- }
-
- });
-
- let selFolder = getSettings('tt_selected_folder');
- if (selFolder !== null) {
- if (!$('#cws_tt_folder' + selFolder).length) {
- selFolder = '0';
- }
- $('#cws_tt_folder' + selFolder).click();
- $('.cws-tt-page-lbl').hide();
- $('.cws-tt-page-lbl[folder=' + selFolder + ']').show();
- $('.cws-tt-page-lbl[folder=' + selFolder + ']')[0].click();
- let pageid = $('.cws-tt-page-lbl[folder=' + selFolder + ']').attr('for');
- let $pageinp = $('#' + pageid + '');
- $('.cws-tt-table[page=' + page + ']').hide();
- page = $pageinp.val();
- $('.cws-tt-table[page=' + page + ']').show();
- }
-
- function tt_setStyle($elem, style) {
- $elem.removeClass('cws-tt-safe cws-tt-unsafe cws-tt-move').addClass(style);
- if (proj) {
- let col = $elem.index();
- let row = $elem.parent().index();
- $('#cages > tbody > tr').eq(row).children().eq(col).removeClass('cws-tt-safe cws-tt-unsafe cws-tt-move').addClass(style);
- }
- }
-
- function tt_draw() {
- $('.cws-tt-table[page=' + page + '] td.cws-tt-safe, .cws-tt-table[page=' + page + '] td.cws-tt-unsafe, .cws-tt-table[page=' + page + '] td.cws-tt-move').each(function () {
- let col = $(this).index();
- let row = $(this).parent().index();
- $('#cages > tbody > tr').eq(row).children().eq(col).addClass($(this)[0].classList.value);
- /*if ($(this).hasClass('cws-tt-safe') || $(this).hasClass('cws-tt-safe-def')) {
- $('#cages > tbody > tr').eq(row).children().eq(col).addClass('cws-tt-safe');
- }
- else if ($(this).hasClass('cws-tt-unsafe')) {
- $('#cages > tbody > tr').eq(row).children().eq(col).addClass('cws-tt-unsafe');
- }
- else if ($(this).hasClass('cws-tt-move')) {
- $('#cages > tbody > tr').eq(row).children().eq(col).addClass('cws-tt-move');
- }*/
- })
- }
- $('body').on('change', 'input[name="cws_tt_page"]', function () {
- $('.cws-tt-table[page=' + page + ']').hide();
- page = $(this).val();
- $('.cws-tt-table[page=' + page + ']').show();
- if (proj) {
- $('#cages > tbody > tr > td.cws-tt-safe').each(function () {
- $(this).removeClass('cws-tt-safe')
- });
- $('#cages > tbody > tr > td.cws-tt-unsafe').each(function () {
- $(this).removeClass('cws-tt-unsafe')
- });
- $('#cages > tbody > tr > td.cws-tt-move').each(function () {
- $(this).removeClass('cws-tt-move')
- });
- tt_draw();
- }
- });
- $('body').on('change', 'input[name="cws_tt_folder"]', function () {
- let folder = $(this).val();
- setSettings('tt_selected_folder', folder);
- $('.cws-tt-page-lbl').hide();
- $('.cws-tt-page-lbl[folder=' + folder + ']').show();
- $('.cws-tt-page-lbl[folder=' + folder + ']')[0].click();
- });
- $('body').on('change', 'input[name="cws_tt_cell"]', function () {
- text = $(this).val();
- mark = $(this).attr('mark');
- });
- $('body').on('click', '.cws-tt-table td', function () {
- $(this).html(text).removeClass('cws-tt-safe cws-tt-unsafe cws-tt-move').addClass(mark);
- if (proj) {
- let col = $(this).index();
- let row = $(this).parent().index();
- $('#cages > tbody > tr').eq(row).children().eq(col).removeClass('cws-tt-safe cws-tt-unsafe cws-tt-move').addClass(mark);
- }
- tt_fields[page] = $('.cws-tt-table[page=' + page + ']').html();
- setSettings('tt_fields', JSON.stringify(tt_fields));
- });
- $('body').on('click', '#cws_tt_clear_btn', function () {
- let ok = true;
- if (globals.tt_clean_confirm) {
- ok = confirm('Очистить поле?');
- }
- if (ok) {
- $('.cws-tt-table .cws-tt-safe-def').removeClass('cws-tt-safe-def'); // remove later
- $('.cws-tt-table[page=' + page + '] td:not(.cws-tt-move)').each(function () {
- $(this).html('');
- tt_setStyle($(this), '');
- });
- tt_fields[page] = $('.cws-tt-table[page=' + page + ']').html();
- setSettings('tt_fields', JSON.stringify(tt_fields));
- }
- });
- $('body').on('click', '#cws_treeTechiesFold', function () {
- $('#cws_treeTechies').toggleClass('folded');
- $('.cws-tt-fold-minus').toggleClass('cws-tt-fold-hidden');
- $('.cws-tt-fold-plus').toggleClass('cws-tt-fold-hidden');
- });
- $('body').on('change', '#cws_tt_show', function () {
- if ($(this).prop('checked')) {
- proj = true; //вкл свитч переноса
- tt_draw();
- }
- else {
- proj = false;
- $('#cages > tbody > tr > td.cws-tt-safe').removeClass('cws-tt-safe');
- $('#cages > tbody > tr > td.cws-tt-unsafe').removeClass('cws-tt-unsafe');
- $('#cages > tbody > tr > td.cws-tt-move').removeClass('cws-tt-move');
- }
- });
- });
- }
- if (globals.on_paramInfo) {
- function timeConv(sec) {
- let str = "";
- let hr = parseInt(sec / 3600);
- let mi = parseInt((sec - hr * 3600) / 60);
- let se = parseInt(sec - (hr * 3600 + mi * 60));
- str += ((hr) ? hr + " ч " : "");
- str += ((mi) ? mi + " мин " : "");
- str += ((se) ? se + " с" : "");
- return str.trim();
- }
- $('body').on('click', '#dream_table .symbole', function () {
- let green = $('#dream td:first-child').attr('style').replace(/[^\d\.]/g, '');
- let moving = ($('#dream td:first-child').attr('style').indexOf('overflow') !== -1);
- if (!moving) {
- let perc = Math.round(green / 150 * 10000) / 100;
- error(`Сонливость: ${perc}% (${green}px).${(green<150)?` Спать${(green != '0')?` примерно ${timeConv((150-green)*20)}`:` 50 мин или более`}.`:''}`);
- }
- });
- $('body').on('click', '#hunger_table .symbole', function () {
- let green = $('#hunger td:first-child').attr('style').replace(/[^\d\.]/g, '');
- let moving = ($('#hunger td:first-child').attr('style').indexOf('overflow') !== -1);
- if (!moving) {
- let perc = Math.round(green / 150 * 10000) / 100;
- error("Голод: " + perc + "% (" + green + "px).");
- }
- });
- $('body').on('click', '#thirst_table .symbole', function () {
- let green = $('#thirst td:first-child').attr('style').replace(/[^\d\.]/g, '');
- let moving = ($('#thirst td:first-child').attr('style').indexOf('overflow') !== -1);
- if (!moving) {
- let perc = Math.round(green / 150 * 10000) / 100;
- error(`Жажда: ${perc}% (${green}px).${(green<150)?` Пить примерно ${timeConv((150-green)*60)}.`:''}`);
- }
- });
- $('body').on('click', '#need_table .symbole', function () {
- let green = $('#need td:first-child').attr('style').replace(/[^\d\.]/g, '');
- let moving = ($('#need td:first-child').attr('style').indexOf('overflow') !== -1);
- if (!moving) {
- let min = (150 - green) / 2;
- let perc = Math.round(green / 150 * 10000) / 100;
- error(`Нужда: ${perc}% (${green}px).${(green<150)?` Справлять нужду${(green != '0')?` примерно ${timeConv(Math.trunc(min)*60)}${(Number.isInteger(min))?'':' 30 с'}`:` 1 ч 15 мин или более`}.`:''}`);
- }
- });
- $('body').on('click', '#clean_table .symbole', function () {
- let green = $('#clean td:first-child').attr('style').replace(/[^\d\.]/g, '');
- let moving = ($('#clean td:first-child').attr('style').indexOf('overflow') !== -1);
- if (!moving) {
- let fleas = (green < 75) ? true : false;
- let perc = Math.round(green / 150 * 10000) / 100;
- let red = 150 - green;
- red = (red % 3) ? red : red - 0.5;
- let time = (red - 1) / 1.5 * 100 + 100;
- error(`Чистота: ${perc}% (${green}px).${(green<150)?` Вылизываться ${(fleas)?'уже поздно':timeConv(time)}.`:''}`);
- }
- });
- }
- for (let i = 0; i < globals.css_itemHighlightArray.length; i++) {
- globals.css_itemHighlightArray[i] = globals.css_itemHighlightArray[i].trim();
- }
- var checkItemHighlightCage = function(style_value) {
- let style = (style_value || '').split(';');
- const styleBody = `content: '';position: absolute;width: 100%;height: 100%;-webkit-filter: drop-shadow(3px 3px 0px ${globals.css_itemHighlightColor});
- -moz-filter: drop-shadow(3px 3px 0px ${globals.css_itemHighlightColor});-ms-filter: drop-shadow(3px 3px 0px ${globals.css_itemHighlightColor});
- -o-filter: drop-shadow(3px 3px 0px ${globals.css_itemHighlightColor});filter: drop-shadow(3px 3px 0px ${globals.css_itemHighlightColor});`;
- for (let i = 0; i < style.length; i++) {
- let now = style[i].split(':');
- if (now.length == 2 && now[0] == 'background') {
- let nowItems = now[1].split(',');
- let nowItemsGenerated = [];
- let nowUniqueKey = 'cws_itemHighlight';
- for (let j = 0; j < nowItems.length; j++) {
- let nowItem = nowItems[j];
- let nowItemType = ((nowItem.match(/things\/(\d+)\.png/u) || ['', 0])[1]) + '';
- nowUniqueKey += '_' + nowItemType;
- if (globals.css_itemHighlightArray.includes(nowItemType)) {
- nowItemsGenerated.push(nowItem);
- }
- }
- if (nowItemsGenerated.length) {
- if (!$('#' + nowUniqueKey).length) {
- if (globals.on_css_itemHighlight_data == undefined) {
- globals.on_css_itemHighlight_data = '';
- }
- const data = ``;
- globals.on_css_itemHighlight_data += data;
- $('head').append(data);
- }
- }
- }
- }
- }
- var itemHighlightObserver = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutationRecord) {
- checkItemHighlightCage(mutationRecord.target.attributes.style.value);
- });
- });
- if (globals.on_css_itemHighlight) {
- for (let target of document.getElementsByClassName('cage_items')) {
- itemHighlightObserver.observe(target, { attributes : true, attributeFilter : ['style'] });
- }
- }
- const css_texts = {
- 'on_csslocation': ``,
- 'on_css_cellshade': ``,
- 'on_css_removesky': ``,
- 'on_css_oldicons': ``,
- 'on_css_coloredparam': ``,
- 'on_css_highlightmove': ``,
- 'on_css_maxopacity': ``,
- 'on_css_hideTooltip': ``,
- 'on_css_daylight': ``,
- 'on_css_defects': ``,
- 'on_css_defects_dirt': ``,
- 'on_css_hideChat': ``,
- 'on_css_itemHighlight' : ``,
- };
- $.each(css_texts, function (index, value) {
- if (globals[index]) {
- $('head').append(css_texts[index]);
- if (globals[index + '_data']) {
- $('head').append(globals[index + '_data']);
- }
- }
- });
-
- if (globals.on_css_quicksettings) {
- addCSS(`#cws_quick_settings_block {user-select:none;}`);
- $('#family').append(`
-`);
- $('body').on('change', '#on_treeTechies', function () {
- $('#cws_treeTechies').toggleClass('hidden');
- });
- $('body').on('change', '.cwa-chk', function () {
- let id = $(this).attr('id');
- let ischkd = $(this).prop('checked');
- if (ischkd) {
- $('head').append(css_texts[id]);
- if (globals[id + '_data']) {
- $('head').append(globals[id + '_data']);
- }
- if (id == 'on_css_itemHighlight') {
- itemHighlightObserver.disconnect();
- for (let target of document.getElementsByClassName('cage_items')) {
- itemHighlightObserver.observe(target, { attributes : true, attributeFilter : ['style'] });
- }
- $('.cage_items').each(function() {
- checkItemHighlightCage($(this).attr('style'));
- });
- }
- } else {
- $('#cwsstyle_' + id + ', .' + id).remove();
- if (id == 'on_css_itemHighlight') {
- itemHighlightObserver.disconnect();
- }
- }
- setSettings(id, ischkd);
- });
- }
- }
-
- function myCat() {
- $(document).ready(function () {
- let id = $('#pr table tr:first-child td:last-child a').attr('href').replace('cat', '');
- setSettings('thine', id);
- });
- if (globals.on_deletionWarning) {
- const id = +($('#id_icon').parent().parent().children().last().text());
- const moons = +($('#age_icon').parent().parent().children().last().text().replace(/[^\d\.]/ig, ''));
- const age = Math.floor(moons * 4 * 86400 * 1000);
- let date = new Date();
- date.setTime(date.getTime() + (date.getTimezoneOffset() + 180) * 60 * 1000 - age - 86400 * 1000);
- // Текущая дата по московскому времени минус возраст и минус дополнительные сутки из-за того, что регистрация в ночное время
- // может калькулировать возраст по лунам на день позже
- const dateNow = new Date();
- dateNow.setTime(dateNow.getTime() + (dateNow.getTimezoneOffset() + 180) * 60 * 1000);
- const obj = {};
- setSettings(`reg_${id}`, JSON.stringify({
- regTime: Math.floor(date.getTime() / 1000),
- lastOnline: Math.floor(dateNow.getTime() / 1000)
- }));
- }
- if (!globals.charListArray || !globals.charListArray.length) { //Если массив ни разу не заполнялся
- $(document).ready(function () {
- let autoCCArr = [];
- $('a[href*="/login2?"]').each(function () {
- let id = $(this).attr('href').split('=')[1];
- let name = $(this).html();
- if (id && name) {
- autoCCArr.push({
- 'id': id,
- 'name': name
- });
- }
- });
- let id = $('#pr a[href*="cat"] > b').html();
- let name = $('#pr > big').html();
- if (id && name) {
- autoCCArr.push({
- 'id': id,
- 'name': name
- });
- }
- window.localStorage.setItem('cws_sett_charListArray', JSON.stringify(autoCCArr));
- });
- }
- }
-
- function profile() {
- $.getJSON("https://reireirei72.github.io/zero-t-18883/shed/river_achievements.json?" + Date.now(), function (data) {
- const achievements = data,
- elem = `
`,
- inner = `Ачивка "{name}"
- Тип: {type}
-{condition} `;
- const top_el_id = isDesktop ? '#branch' : '#site_table';
- let $achievement = $(`${top_el_id} > .parsed:first tbody > tr img[src*="i.yapx.cc"], `
- + `${top_el_id} > .parsed:first > img[src*="i.yapx.cc"], `
- + `${top_el_id} > .parsed:first tbody > tr img[src*="i.ibb.co"], `
- + `${top_el_id} > .parsed:first > img[src*="i.ibb.co"]`),
- $body = $('body'),
- old_code = "";
- const linkRegex = /(i\.yapx\.cc\/([\w\d]+)\.png|i\.ibb\.co\/([\d\w]+\/[\d\w_-]+)\.png)/;
- $(document).ready(function () {
- $achievement.last().after(elem);
- $achievement.each(function (index) { // Добавить титул к каждой ачивке
- let code = $(this).attr('src').match(linkRegex);
- if (code !== null) {
- code = code[2] || code[3];
- let name = (achievements[code] === undefined) ? "" : achievements[code].name;
- $(this).prop('title', name);
- }
- });
- $achievement.on('click', function () { // инфоблок
- let code = $(this).attr('src').match(linkRegex);
- if (code !== null) {
- code = code[2] || code[3];
- if (code == old_code && $('#cws_achievement').css('display') != 'none') {
- $('#cws_achievement').hide(200);
- }
- else if (achievements[code] !== undefined) {
- let this_achievement = achievements[code];
- let info = inner
- .replace("{name}", this_achievement.name)
- .replace("{type}", this_achievement.type)
- .replace("{condition}", this_achievement.condition);
- $('#cws_achievement').html(info).show(200);
- old_code = code;
- }
- }
- });
- });
- });
- }
-
- function dm() { //ЛС игрока
- if (globals.on_idDM) {
- function add_id() {
- let id = $('#msg_login').attr('href');
- if (id !== undefined) {
- id = id.replace(/\D/ig, '');
- $(' [' + id + '] ').insertAfter($('#msg_login'));
- }
- }
- $(document).ready(function () {
- add_id(); // on load
- $('#main').bind("DOMSubtreeModified", function () {
- if (!$('#cws_msg_id').length) {
- add_id(); // on click
- }
- });
- });
- }
- }
-
- function hunt() {
- if (globals.on_css_bghuntpic) {
- $('head').append(``);
- }
- if (!isDesktop) {
- if (globals.on_huntMobileBtns) {
- addCSS(`#select_type:after {
- content: " (переверните телефон на бок)";
- font-style: italic;
-}
-#select_type {
- width: 80%;
- margin-left: 10%;
- margin-top: 5%;
- text-align: center;
-}
-input {
- left: 5%;
- width: 90%;
-}
-#cws_buttons {
- position: absolute;
- top: 10px;
- left: 0px;
-}
-.mod_btn {
- position: absolute;
- z-index: 9999;
- font-family: Verdana;
- font-size: 2.5em;
- height: 1.5em;
- width: 1.5em;
- border-radius: 5em;
- background-size: 75% !important;
- background: #333 center no-repeat;
- color: white;
- opacity: .8;
- bottom:0;right:0;
- user-select: none;
- text-align: center;
- -webkit-user-select: none;
- -moz-user-select: none;
- -ms-user-select: none;
-}
-#w_btn {
- top: 0em;
- left: 2.25em;
- background-image: url('https://i.imgur.com/y0e39Ai.png');
-}
-#d_btn {
- top: 2.3em;
- left: 4.25em;
- background-image: url('https://i.imgur.com/g6WcMvn.png');
-}
-#a_btn {
- top: 2.3em;
- left: .25em;
- background-image: url('https://i.imgur.com/JgywWPS.png');
-}
-#s_btn {
- top: 4.6em;
- left: 2.25em;
- background-image: url('https://i.imgur.com/BPRewfC.png');
-}
-#q_btn {
- top: .7em;
- left: .75em;
- background-image: url('https://i.imgur.com/JgywWPS.png');
-}
-#e_btn {
- top: .7em;
- left: 3.75em;
- background-image: url('https://i.imgur.com/y0e39Ai.png');
-}
-#z_btn {
- top: 3.9em;
- left: .75em;
- background-image: url('https://i.imgur.com/BPRewfC.png');
-}
-#x_btn {
- top: 3.9em;
- left: 3.75em;
- background-image: url('https://i.imgur.com/g6WcMvn.png');
-}
-#q_btn, #e_btn, #x_btn, #z_btn {transform: rotate(45deg);}
-#oben, #links, #rechts, #unten {display: none;}`);
- $("#main").ready(function () {
- $("#main").append(`
-
-
-
-
-
-
-
`);
- $('.mod_btn').on("mousedown touchstart", function (e) {
- e.preventDefault();
- let code = $(this).data('code');
- $('#main').trigger(
- jQuery.Event('keydown', {
- keyCode: code,
- which: code
- })
- );
- });
- $('.mod_btn').on("mouseup touchend", function (e) {
- e.preventDefault();
- let code = $(this).data('code');
- $('#main').trigger(
- jQuery.Event('keyup', {
- keyCode: code,
- which: code
- })
- );
- });
- });
- }
- if (globals.on_huntMobileFix) {
- addCSS(`body {
- position: fixed;
- height: 100%;
- width: 100%;
- transform: scale(.8);
-}
-html {
- height: 100%;
- width: 100%;
-}
-#smell {
- position: absolute;
- bottom: calc(10px - 10%);
- left: -10%;
-}
-#cws_buttons {
- position: absolute;
- top: calc(10px - 12.5%);
- left: -12.5%;
- transform: scale(.9);
-}`);
- }
- }
-
- if (globals.on_huntText) {
- addCSS(`#smell {
- text-align: center;
- display:flex;
- flex-direction: column;
- align-items:center;
- justify-content:center;
- }
- #cws_hunt_txt {
- background-color: white;
-height: 2.3em;
- }
-#cws_timer, #cws_hunt_txt {width: 100%;}`);
-
- let color_old = -1;
- setInterval(function () {
- if ($('#smell').attr('style')) {
- if (!$('#cws_hunt_txt').length) {
- $('#smell').append('00:00
')
- }
- let color_new = parseInt($('#smell').css('background-color').split('(').pop().split(',')[0]);
- let a = color_new - color_old
- if (color_old != -1) {
- let text = (a < 0) ? "Дальше" : "Ближе";
- if (color_new === 0) text = "Слишком далеко";
- if ((a !== 0) || (color_new === 0 && !$('#cws_hunt_txt').html())) $('#cws_hunt_txt').html(text);
- }
- color_old = color_new;
- }
- }, 100);
- setInterval(function () {
- if ($('#cws_timer').length) {
- let sec = parseInt($('#cws_timer').data('sec')),
- min;
- $('#cws_timer').data('sec', ++sec);
- min = parseInt(sec / 60);
- sec = sec - min * 60;
- $('#cws_timer').text(leadZero(min) + ':' + leadZero(sec));
- }
- }, 1000);
- }
- }
-
- function blog() {
- if (globals.on_reports) {
- $(document).ready(function () {
- addCSS(`.inp-button {background-color: #333;color: #fff;border: 1px solid #000;font-family: Verdana;font-size: .9em;}`);
- const blogID = +(pageurl.replace(/\D/g, ''));
- let date;
- date = new Date();
- date.setTime(date.getTime() + (date.getTimezoneOffset() + 180) * 60 * 1000);
- const date_str = date.getFullYear() + '-' + leadZero(date.getMonth() + 1) + '-' + leadZero(date.getDate());
- let my_id_div = `Ваш ID: Запомнить
`;
-
- function rememberMyID(my_id) {
- if ($('#remember_id').prop('checked') && !isNaN(my_id) && my_id) { // запомнить
- setSettings('my_id', my_id);
- }
- }
- addCSS(`/*.cws_tabs_content { display: none; } .cws_tabs_content.active { display: block; }*/
-.cws_tabs_caption {
- display: -webkit-flex;
- display: -ms-flexbox;
- display: flex;
- -webkit-flex-wrap: wrap;
- -ms-flex-wrap: wrap;
- flex-wrap: wrap;
- list-style: none;
- position: relative;
- margin: 0;
- padding-inline-start:0px;
-}
-.cws_tabs_caption li {
- padding: 1px 12px;
- margin: 0 2px 0 0;
- background: #333;
- color: #FFF;
- position: relative;
- border: solid #000;
- border-width: 1px;
- text-align: center;
-}
-.cws_tabs_caption li:not(.active) {
- cursor: pointer;
-}
-.cws_tabs_caption li:not(.active):hover {
- background: #444;
- border-color: #666;
-}
-.cws_tabs_caption .active {
- background: #444;
- color: #fff;
- border-color: #666;
-}`);
- /*РЕКА*/
- if (blogID == 13664) { // Охрана границ
- let patr_time = 21,
- doz_time = leadZero(date.getHours()),
- patr_date = new Date(date),
- doz_date = new Date(date);
- let hour = date.getHours(),
- minute = date.getMinutes();
- if (hour < 12) {
- patr_date.setDate(patr_date.getDate() - 1);
- } // yesterday
- if (hour >= 12) {
- patr_time = 12;
- }
- if (hour >= 15) {
- patr_time = 15;
- }
- if (hour >= 18) {
- patr_time = 18;
- }
- if (hour >= 21) {
- patr_time = 21;
- }
- const patr_date_str = patr_date.getFullYear() + '-' + leadZero(patr_date.getMonth() + 1) + '-' + leadZero(patr_date.getDate());
- $('#send_comment').append(`
-
-Автоматическое заполнение отчётов
-
-${my_id_div}
-
-
-
-
-
-
-
Дозор
-
-
-
Заполнить отчет
-
-
-
-
Исключения из дозора
-
-
Заполнить отчет
-
-
-
- ×
-
-
- +
-
-
-
-
-
-
- ×
-
-
-
-офф в дозоре
-отсутствие на месте дозора
-перепутано место дозора
-пропуск нарушителя
-долгое невыполнение переходов в активном дозоре
-уход с места дозора раньше времени
-тренировка во время дозора
-выполнение посторонних действий в активном дозоре
-
- +
-
-
-
-
-
-
-
-
Патруль
- Маршрут:
-
1
-
2
-
-
- Список участников, исключая вас, разделяя запятой:
-
-
-
Заполнить отчет
-
-
`);
- $('#r03_patr').on('click', function (e) {
- let myid = parseInt($('#cws_blog_myid').val()); // id пишущего отчет
- rememberMyID(myid);
- myid = (isNaN(myid)) ? 'Некорректный ID ведущего' : masking(myid, '[cat%ID%] [%ID%]');
- let mar = $('.cws-input[name=r03_patr_mar]:checked').val();
- if (mar === undefined) {
- mar = 'Не выбран маршрут';
- }
- let arr_members = strToArr($('#cws_patr_members').val());
- let id_arr = [];
- let name_error = false; // ошибка в имени участника
- arr_members.forEach((element) => {
- let name = element.trim();
- let tmp = nameToID(name);
- if (parseInt(tmp)) {
- id_arr.push(name + ' [' + tmp + ']');
- }
- else {
- name_error = true;
- }
- })
- let date = splitDateStr($("#r03_patr_date").val()); // дата
- let hr = parseInt($("#r03_patr_time").val().split(":")[0]);
- let txt = `[u][b]Патруль[/b][/u]
-[b]Дата и время:[/b] ${date.day}.${date.month}, ${leadZero(hr)}:00;
-[b]Маршрут:[/b] ${mar};
-[b]Ведущий:[/b] ${myid};
-[b]Участники:[/b] ${id_arr.join(', ')};`;
- if (name_error) {
- txt += `\n! ! ! В отчёте какая-то ошибка с именем (минимум одно из имён не было найдено). Проверьте его перед тем, как отправить.`
- }
- let val = $('#comment').val();
- if (val) {
- val += "\n\n";
- }
- $('#comment').val(val + txt).scrollintoview();
- });
- $('#r03_doz').on('click', function (e) {
- let date = splitDateStr($("#r03_doz_date").val()),
- txt = '[u][b]Дозор[/b][/u]\n[b]Дата:[/b] ' + date.day + '.' + date.month + ';\n[b]Время:[/b] ',
- my_id = parseInt($('#cws_blog_myid').val()),
- som_text = $('#r03_doz_text').val().trim(),
- name_error = false,
- locations = [],
- time,
- nextTime,
- sign,
- found,
- pattern,
- places = {
- "КЗ": "Камышовые заросли",
- "ТБ": "Травянистый берег",
- "РЛ": "Редколесье",
- "РО": "Разрушенная ограда",
- "РД": "Расколотое дерево",
- "ЛР": "Лесной ручеёк",
- "ВЛ": "Валежник",
- "ИТ": "Илистая тропа",
- "ОС": "Одинокий склон",
- "НК": "Нагретые камни",
- "ДБ": "Дубрава",
- "МЗ": "Мшистые земли",
- "ГТ": "Главный туннель",
- "01": "Активный 1",
- "02": "Активный 2",
- "03": "Активный 3",
- "04": "Активный 4"
- };
- rememberMyID(my_id);
- time = som_text.match(/^(\d{2}) *([\+-])/i);
- if (time === null) {
- let val = $('#comment').val();
- if (val) {
- val += "\n\n";
- }
- $('#comment').val(val + '! ! ! Отчёт обязательно должен начинаться с двух цифр (час сбора) и знака (+ или -).');
- return;
- }
- sign = time[2];
- time = parseInt(time[1]);
- nextTime = (time == 23) ? 0 : time + 1;
- txt += leadZero(time) + ':00-' + leadZero(nextTime) + ':00;\n';
- my_id = (isNaN(my_id)) ? 'Некорректный ID собирающего' : masking(my_id, '[cat%ID%] [%ID%]');
- txt += '[b]Собирающий:[/b] ' + my_id + '.\n[b][u]Участники[/u][/b]\n';
- if (sign == '+') {
- som_text = som_text.replace(/^(\d{2}) *([\+-])[^\n]*\n|\. *$|; *$|, *$/ig, '');
- som_text = som_text.replace(/\. *\n|, *\n|; *\n/ig, '\n');
- som_text = som_text.replace(/\n(\d):/ig, '\n0$1:');
- som_text = som_text.replace(/^(\d):/ig, '0$1:');
- $.each(places, function (short_name, full_name) {
- pattern = new RegExp('\n*' + short_name + ': *([^\n]+)', "i");
- if (found = som_text.match(pattern)) {
- let name_arr = found[1].split(','),
- id_arr = [],
- tmp_arr = [];
- $.each(name_arr, function (index, name) {
- let tmp = nameToID(name.trim());
- if (parseInt(tmp)) {
- //id_arr.push(masking(tmp, '[cat%ID%] [%ID%]'));
- id_arr.push(name + ' [' + tmp + ']');
- }
- else {
- id_arr.push(name_arr[index] + ' [?]');
- name_error = true;
- }
- });
- locations.push('[b]' + full_name + ':[/b] ' + id_arr.join(', '));
- }
- });
- txt += locations.join(';\n') + '.';
- }
- else {
- txt += 'Нет.'
- }
- if (name_error) {
- txt += `\n! ! ! В отчёте какая-то ошибка с именем (одно из имён не было найдено). Проверьте его перед тем, как отправить.`
- }
- let val = $('#comment').val();
- if (val) {
- val += "\n\n";
- }
- $('#comment').val(val + txt).scrollintoview();
- });
- $('#r03_doz_nar').on('click', function (e) {
- let date = splitDateStr($("#r03_doz_nar_date").val()),
- hr = parseInt($("#r03_doz_nar_time").val().split(":")[0]),
- next_hr = (hr == 23) ? 0 : hr + 1,
- txt = '[u][b]Дозор[/b][/u]\n[b]Дата:[/b] ' + date.day + '.' + date.month + ';\n[b]Время:[/b] ' + leadZero(hr) + ':00-' + leadZero(next_hr) + ':00';
- let free_arr = [],
- nar_arr = [];
- $('.r03-doz-nar-free-wrap').each(function () {
- let free = $(this).find($('input.r03-doz-nar-free')).val();
- if (free) {
- if (isNaN(parseInt(free))) {
- free = nameToID(free.trim());
- }
- free = masking(free, '[cat%ID%] [%ID%]');
- free_arr.push(free);
- }
- });
- $('.r03-doz-nar-wrap').each(function () {
- let name = $(this).find($('input.r03-doz-nar-narname')).val(),
- reason = $(this).find($('select.r03-doz-nar-narreas')).val();
- if (name) {
- if (isNaN(parseInt(name))) {
- name = nameToID(name.trim());
- }
- name = masking(name, '[cat%ID%] [%ID%]');
- nar_arr.push(name + ' (' + reason + ')');
- }
- });
- if (free_arr.length) {
- txt += ';\n[b]Освобождены:[/b] ' + free_arr.join(', ');
- }
- if (nar_arr.length) {
- txt += ';\n[b]Нарушения:[/b] ' + nar_arr.join(', ');
- }
- txt += '.';
- let val = $('#comment').val();
- if (val) {
- val += "\n\n";
- }
- $('#comment').val(val + txt).scrollintoview();
- // $("#comment").scrollintoview();
- });
- $('#r03_doz_nar_block').on('click', '.add-field', function (e) {
- let max_children = 5;
- let data_id = $(this).data('id'),
- template = $('#' + data_id)[0];
- let $fields = $('.' + data_id);
- let last_e = $fields[$fields.length - 1];
- if ($fields.length < max_children) {
- let clone = document.importNode(template.content, true);
- let add = $(clone).insertAfter(last_e);
- $(last_e).find($('.add-field')).css('display', 'none');
- }
- });
- $('#r03_doz_nar_block').on('click', '.del-field', function (e) {
- let data_id = $(this).data('id');
- $(this).closest($('.' + data_id)).remove();
-
- let $fields = $('.' + data_id);
- let last_e = $fields[$fields.length - 1];
- $(last_e).find($('.add-field')).css('display', 'inline-block');
- });
- }
-
- if (blogID == 13219) { // чистильщики
- $('#send_comment').append(`
-
-Автоматическое заполнение отчётов
-
-${my_id_div}
-
-
-
- I группа
- II группа
- III группа
-
-
-
-
- Автоматическое составление отчёта через историю, сгенерированную модом.
ВСЯ история должна придерживаться одного вида, включая такие опции, как:
-
- ID поднятого/опущенного;
- должность поднятого/опущенного;
- статус поднятого;
- локацию, в которой кот был поднят/опущен.
-
-
-
-
-
-
-
-Заполнить отчет
-`);
- $('#r03_clean1').on('click', function () {
- let expr_pickup = new RegExp('(Подняла? ([А-яЁё ]+) по имени [А-яЁё ]+ \\((\\d+)\\) (\\[[А-яЁё ]+\\]) в локации «([А-яЁё ]+)»\\.|Опустила? на землю ([А-яЁё ]+) по имени [А-яЁё ]+ \\((\\d+)\\) в локации «([А-яЁё ]+)»\\.)', "ig");
- let text = $('#r03_clean_text').val();
- let group = $('#cws_clean_grp').val();
- let match_pickup = Array.from(text.matchAll(expr_pickup));
- let good_cats = {};
- let current_cats = [];
- const titles = {
- "котёнка": "Котята",
- "оруженосца": "ОВ",
- "воителя": "ОВ",
- "воительницу": "ОВ",
- "королеву": "ОВ",
- "старшего воителя": "ОВ",
- "старшую воительницу": "ОВ",
- };
- const places_from = {
- "Камышовая поляна": "Лагерь",
- "Мшистая полянка": "Лагерь",
- "Поляна для сна": "Лагерь",
-
- "Тенистая поляна": "Подлагерь",
- "Дальний уголок": "Подлагерь",
- "Грязное место": "Подлагерь",
- "Куча с добычей": "Подлагерь",
- "Старый вяз": "Подлагерь",
- "Полянка для игр": "Подлагерь",
- "Лужайка для игр": "Подлагерь",
- "Окутанный тайнами лужок": "Подлагерь",
-
- "Неглубокий ручей": "Номерные",
- "Детская": "Номерные",
- "Палатка оруженосцев": "Номерные",
- "Палатка воителей": "Номерные",
-
- "Поляна для тренировок": "Поляна для Тренировок [ПДТ]",
- "Юркая ложбинка": "Поляна для Тренировок [ПДТ]",
- "Лужайка, скрытая листвой": "Поляна для Тренировок [ПДТ]",
- "Боевая поляна": "Поляна для Тренировок [ПДТ]",
- "Местечко для тренировок": "Поляна для Тренировок [ПДТ]",
- "Пещера острых клыков": "Поляна для Тренировок [ПДТ]",
- "Пещера танцующих когтей": "Поляна для Тренировок [ПДТ]",
- "Расцарапанные камушки": "Поляна для Тренировок [ПДТ]",
- "Покинутая вороном лужайка": "Поляна для Тренировок [ПДТ]",
- "Просторное местечко": "Поляна для Тренировок [ПДТ]",
- "Тренировочный овраг": "Поляна для Тренировок [ПДТ]",
-
- "Камышовые заросли": "КЗ",
-
- "Галечный берег": "Лес",
- "Плакучая ива": "Лес",
- "Шелестящий тростник": "Лес",
- "Торфяник": "Лес",
- "Междуречье": "Лес",
- "Скользкие камни": "Лес",
- "Травянистый берег": "Лес",
- "Грохочущая тропа Двуногих": "Лес",
- "Редколесье": "Лес",
- "Илистая тропа": "Лес",
- "Разрушенная ограда": "Лес",
- "Лесной ручеёк": "Лес",
- "Расколотое дерево": "Лес",
- "Граница между Ветром и Рекой": "Лес",
- "Граница между Тенями и Рекой": "Лес",
- "Пруд ужей": "Лес",
- "Нагретые камни": "Лес",
- "Одинокий склон": "Лес",
- "Дубрава": "Лес",
-
- "Лягушатник": "Лес",
- "Мелководье": "Лес",
- "Тёплый ручеёк": "Лес",
- "Приток": "Лес",
- "Тихие воды": "Лес",
- "Плоские валуны": "Лес",
- "Воды у корней старой ивы": "Лес",
- "Глубокие воды": "Лес",
- "Ледяная вода": "Лес",
- "Течение": "Лес",
- "Устье реки": "Лес",
- "Спокойный поток": "Лес",
- "Каменная гряда": "Лес",
-
- "Тихий берег": "Нейтралки",
- "Заросший берег": "Нейтралки",
- "Пологий берег": "Нейтралки",
- "Каменистый берег": "Нейтралки",
- "Поваленное дерево": "Нейтралки",
- "Остров Советов": "Нейтралки",
- "Скалистые холмы": "Нейтралки",
- "Лунный ручей": "Нейтралки",
- "Лунный камень": "Нейтралки",
- "Предгорья": "Нейтралки",
- "Горы": "Нейтралки",
- "Туннели": "Нейтралки",
- "Ярусы сомнения": "Нейтралки",
- "Воющие коридоры": "Нейтралки",
- };
- const bad_statuses = ["[ На удалении ]", "[ Заблокирован ]", "[ В подстилках ]"];
- const good_statuses = ["[ В игре ]", "[ Недавно ушёл ]", "[ Недавно ушла ]"];
- $.each(match_pickup, function (index, value) {
- if (value[2] !== undefined) { // Поднятие: 2 должность, 3 статус, 4 айди, 5 локация
- let id = value[3],
- title_grp = titles[value[2]],
- place = value[5];
- if (bad_statuses.includes(value[4])
- || group == "II группа" && ["Плакучая ива", "Галечный берег"].includes(place)) {
- title_grp = "Заблокированные";
- }
- place = (places_from[place]) ? places_from[place] : place;
- if (place !== undefined && (value[4] == "[ Спит ]" || title_grp == "Заблокированные")) {
- current_cats[id] = {
- "title_grp": title_grp,
- "place": place
- };
- }
- } else { // Опускание: 6 должность, 7 айди, 8 локация
- let id = value[7];
- if (current_cats[id] !== undefined) {
- let title_grp = current_cats[id].title_grp,
- place = current_cats[id].place;
- if (good_cats[place] === undefined) {
- good_cats[place] = {};
- good_cats[place]["ОВ"] = [];
- good_cats[place]["Котята"] = [];
- good_cats[place]["Заблокированные"] = [];
- }
- if (good_cats[place][title_grp]) {
- good_cats[place][title_grp].push(id);
- }
- current_cats[id] = undefined;
- }
- }
- });
- let my_id = parseInt($('#cws_blog_myid').val());
- let my_id_mask = (isNaN(my_id)) ? 'Некорректный ID' : masking(my_id, '[cat%ID%] [%ID%]');
- let report = `1. ${my_id_mask}.\n2. ${group}.\n`;
- if (group == "III группа") {
- report += `3. [b]Л:[/b] — предупрежден(-ы)\n[b]КЗ:[/b] — предупрежден(-ы)`;
- } else {
- report += `3. `;
- $.each(good_cats, function (place, groups) {
- if (group == "II группа") {
- report += `[b]${place}:[/b] `;
- let list = [];
- let list_blocked = [];
- $.each(groups, function (victim_group, arr) {
- if (victim_group == "Заблокированные") {
- list_blocked = list_blocked.concat(arr);
- } else {
- list = list.concat(arr);
- }
- });
- report += `${list.join(' ')}\n`;
- if (list_blocked.length) {
- report += `[u]${list_blocked.join(' ')}[/u]\n`;
- }
- } else {
- report += `[b]${place}:[/b]\n`;
- $.each(groups, function (victim_group, arr) {
- if (arr.length) {
- if (victim_group == "Заблокированные") {
- report += `[u]${arr.join(' ')}[/u]\n`;
- } else {
- report += `${victim_group}: ${arr.join(' ')}\n`;
- }
- }
- });
- }
- });
- }
- if (group == "I группа" || group == "II группа") {
- report += `4. [header=${my_id}]История[/header][block=${my_id}]${text}[/block]`;
- }
- $('#comment').val(report).scrollintoview();
- });
- } else if (blogID == 24395) { // хранители трав
- let patr_date = new Date(date),
- hour = date.getHours();
- if (hour < 12) {
- patr_date.setDate(patr_date.getDate() - 1);
- }
- let type = "веточник";
- if (hour < 12 || hour >= 17) {
- type = "мховник";
- } else if (hour == 16) {
- type = "травник";
- }
- const patr_date_str = patr_date.getFullYear() + '-' + leadZero(patr_date.getMonth() + 1) + '-' + leadZero(patr_date.getDate());
- my_id_div= `Ваш ID (+кол-во трав): Запомнить
`;
-
- $('#send_comment').append(`
-
-Автоматическое заполнение отчётов
-
-${my_id_div}
-
-Патруль
-Вид:
- веточник
- травник
- мховник
-
-
- Список участников, исключая вас, разделяя запятой (в конце ставьте число принесённых трав):
-
-
-Заполнить отчет
-`);
- $('#r03_herb').on('click', function (e) {
- let lead = $('#cws_blog_myid').val().split(' ');
- let myid = parseInt(lead[0]);
- let leadherb = +(lead[1].replace(/\D+/ig, ''));
- rememberMyID(myid);
- myid = (isNaN(myid)) ? 'Некорректный ID ведущего' : masking(myid, `[cat%ID%] [%ID%] (${leadherb})`);
- let mar = $('.cws-input[name=r03_patr_mar]:checked').val();
- mar = mar || 'Не выбран вид';
- let arr_members = strToArr($('#cws_patr_members').val());
- let id_arr = [];
- let not_found = [];
- let name_error = false;
- arr_members.forEach((element) => {
- let entry = element.trim().match(/([А-яЁё ]+) \(?(\d+)\)?/i);
- let name = entry[1];
- let herb = entry[2];
- let tmp = nameToID(name);
- if (parseInt(tmp)) {
- id_arr.push(`${name} [${tmp}] (${herb})`);
- } else {
- name_error = true;
- not_found.push(name);
- }
- })
- let date = splitDateStr($("#r03_patr_date").val());
- date.year = date.year.slice(2, 4);
- let txt = `[b]Дата:[/b] ${date.day}.${date.month}.${date.year};
-[b]Тип травника:[/b] ${mar};
-[b]Ведущий:[/b] ${myid};
-[b]Участники:[/b] ${id_arr.length ? id_arr.join(', ') : "-"}.`;
- if (name_error) {
- txt += `\n! ! ! В отчёте ошибка со следующими именами (не были найдены или не соответствуют формату): ${not_found.join(', ')}. Проверьте его перед тем, как отправить.`
- }
- let val = $('#comment').val();
- if (val) {
- val += "\n\n";
- }
- $('#comment').val(val + txt).scrollintoview();
- });
-
- } else if (blogID == 51844) { // охотники
- let patr_date = new Date(date),
- hour = date.getHours();
- if (hour < 13) {
- patr_date.setDate(patr_date.getDate() - 1);
- }
- let type = "вечерняя";
- if (hour >= 13 && hour < 19) {
- type = "утренняя";
- }
- const patr_date_str = patr_date.getFullYear() + '-' + leadZero(patr_date.getMonth() + 1) + '-' + leadZero(patr_date.getDate());
- $('#send_comment').append(`
-Автоматическое заполнение отчётов
-
-${my_id_div}
-
-Патруль
-
-Вид:
- утренняя
- вечерняя
-
-
- Место охоты:
- шелестящий тростник
- пруд ужей
- галечный берег
- редколесье
-
-
-
- Список охотников, исключая вас, разделяя запятой (если было принесено меньше 5 дичи, указывайте это цифрой в конце):
-
-
-
- Список таскающих, разделяя запятой:
-
-
-Заполнить отчет
-`);
-
- $('#r03_hunt').on('click', function (e) {
- let lead = $('#cws_blog_myid').val();
- let myid = parseInt(lead);
- rememberMyID(myid);
- myid = (isNaN(myid)) ? 'Некорректный ID ведущего' : masking(myid, '[cat%ID%] [%ID%]');
- let mar = $('.cws-input[name=r03_patr_mar]:checked').val();
- mar = mar || 'Не выбран вид';
- let loc = $('.cws-input[name=r03_patr_loc]:checked').val();
- loc = loc || 'Не выбрана локация';
- let str_hunters = strToArr($('#cws_patr_hunters').val()),
- str_carriers = strToArr($('#cws_patr_carriers').val()),
- id_hunters = [],
- id_carriers = [],
- not_found = [],
- not_clan = [];
- let name_error = false, clan_error = false;
- str_hunters.forEach((element) => {
- let entry = element.trim().match(/([А-яЁё ]+) ?\(?(\d+)?\)?/i),
- name = entry[1],
- hunt = entry[2] || 5,
- tmp = nameToIDFiltered(name, "Речное племя");
- if (parseInt(tmp)) {
- if (tmp != -1) {
- id_hunters.push(`${name} [${tmp}] (${hunt})`);
- } else {
- clan_error = true;
- not_clan.push(name);
- }
- } else {
- name_error = true;
- not_found.push(name);
- }
- });
- str_carriers.forEach((element) => {
- let name = element.trim(),
- tmp = nameToIDFiltered(name, "Речное племя");
- if (parseInt(tmp)) {
- if (tmp != -1) {
- id_carriers.push(`${name} [${tmp}]`);
- } else {
- clan_error = true;
- not_clan.push(name);
- }
- } else {
- name_error = true;
- not_found.push(name);
- }
- });
- let date = splitDateStr($("#r03_patr_date").val());
- date.year = date.year.slice(2, 4);
- let txt = `[b][u]Дата[/u]:[/b] ${date.day}.${date.month}.${date.year};
-[b]Вид:[/b] ${mar};
-[b]Место охоты:[/b] ${loc};
-[b]Ведущий:[/b] ${myid} (5);
-[b]Участники:[/b] ${id_hunters.length ? id_hunters.join(', ') : "-"};
-[b]Таскающие:[/b] ${id_carriers.length ? id_carriers.join(', ') : "-"};`;
- if (name_error) {
- txt += `\n! ! ! В отчёте ошибка со следующими именами (не были найдены или не соответствуют формату): ${not_found.join(', ')}. Проверьте его перед тем, как отправить.`
- }
- if (clan_error) {
- txt += `\n! ! ! В отчёте ошибка со следующими котиками (они не находятся в вашем племени, зачем вы их сюда пишете?): ${not_clan.join(', ')}. Проверьте его перед тем, как отправить.`
- }
- let val = $('#comment').val();
- if (val) {
- val += "\n\n";
- }
- $('#comment').val(val + txt).scrollintoview();
- });
- }
- $('ul.cws_tabs_caption').on('click', 'li:not(.active)', function () {
- $(this)
- .addClass('active').siblings().removeClass('active')
- .closest('div.cws_tabs').find('div.cws_tabs_content').removeClass('active').slideUp(200)
- .eq($(this).index()).addClass('active').slideDown(200);
- });
- });
- }
- }
-
- function cumoves() {
- const notes = getSettings('cuMovesNote') || '';
- const p = `Заметки:
`;
- $('#branch').append(p); //text
- $('#cws_moves_note').val(notes);
- $('#cws_moves_note').on('input', function () {
- setSettings('cuMovesNote', $(this).val());
- });
- }
-
- function sett() {
- $('head').append(``);
- const pattern = globals.css_cp_pattern ? 'url(https://i.imgur.com/V4TX5Cv.png), ' : '';
- let css_coloredparam_example = `#dream .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[0]}, ${globals.css_cp_colors[1]});}
-#dream .bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[2]}, ${globals.css_cp_colors[3]});}
-#hunger .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[4]}, ${globals.css_cp_colors[5]});}
-#hunger .bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[6]}, ${globals.css_cp_colors[7]});}
-#thirst .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[8]}, ${globals.css_cp_colors[9]});}
-#thirst .bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[10]}, ${globals.css_cp_colors[11]});}
-#need .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[12]}, ${globals.css_cp_colors[13]});}
-#need .bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[14]}, ${globals.css_cp_colors[15]});}
-#health .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[16]}, ${globals.css_cp_colors[17]});}
-#health .bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[18]}, ${globals.css_cp_colors[19]});}
-#clean .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[20]}, ${globals.css_cp_colors[21]});}
-#clean .bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[22]}, ${globals.css_cp_colors[23]});}
-.bar .bar-fill {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[24]}, ${globals.css_cp_colors[25]});}
-.bar {background:${pattern}linear-gradient(0.25turn, ${globals.css_cp_colors[26]}, ${globals.css_cp_colors[27]});}`;
- $('head').append(``);
- let action_group_dis = (globals.on_actNotif) ? '' : ' disabled',
- tf_group_dis = (globals.on_teamFights) ? '' : ' disabled',
- clean_group_dis = (globals.on_cleanerHistory) ? '' : ' disabled',
- tt_dis = (globals.on_treeTechies) ? '' : ' disabled',
- chatment_group_dis = (globals.on_chatMention) ? '' : ' disabled',
- nick_group_dis = (globals.on_nickHighlight) ? '' : ' disabled',
- css_cp_group_dis = (globals.on_css_coloredparam) ? '' : ' disabled',
- chat_group_dis = (globals.on_customChat) ? '' : ' disabled',
- CCArray = '';
- let nickArray = '';
- $.each(globals.nickListArray, function (index, obj) {
- if (obj) {
- nickArray += `
- × `;
- }
- });
- if (!nickArray.length) {
- nickArray = `
- × `;
- }
- let $body = $('body');
- addCSS(`.cp-color-pick, .team-color-pick {
- background-color: #eaeaea;
- border: 1px solid #b3b3b3;
-}
-.bl_in{
- display: inline-block;
- margin-left:20px;
-}
-#cwa_sett > div {
- margin: .6em 0;
-}
-#color_pick td, #color_pick th{
-padding: .1em .25em;
-}
-.cat_box {
- padding: .6em .3em;
- width: fit-content;
-}
-#fight_bg {
-border-radius: 1em;
-background: url(https://abstract-class-shed.github.io/pic/background.png) top center no-repeat;
-width: 320px;
-height: 330px;
-max-width: calc(100% - 1.2em);
-}
-.color-pick-wrapper {
- display: inline-block;
- width: 100px;
-}
-.cat_box {
-margin:auto;
-}
-.arrow {
- height: 8px;
- position: absolute;
- margin: 0;
- padding: 3px 0 0 11px;
- z-index: 2;
-}
-.arrow-paws {background: url(/cw3/symbole/arrow_paws.png) 0 0 no-repeat;}
-.arrow-claws {background: url(/cw3/symbole/arrow_claws.png) 0 0 no-repeat;}
-.arrow-teeth {background: url(/cw3/symbole/arrow_teeth.png) 0 0 no-repeat;}
-.arrow table, .arrow td {
- height: 5px !important;
- padding: 0;
- margin: 0;
-}
-.arrow_red {
- background: #CD4141;
-}
-.d, .d div {
- width: 100px;
- height: 150px;
-}
-table {
- border-collapse: collapse;
-}
-.custom-range::-webkit-slider-thumb {
- -webkit-appearance: none;
- appearance: none;
- width: 25px;
- height: 25px;
- border-radius: 1em;
- background: #622906;
- cursor: pointer;
-}
-.custom-range {
--webkit-appearance: none;
-appearance: none;
-width: 180px;
-height: 15px;
-background: #fff1dc;
-outline: none;
-border-style: solid;
-border-width: 1px;
-border-color: #62290640;
-}
-.custom-range::-moz-range-thumb {
- width: 25px;
- height: 25px;
- background: #622906;
- cursor: pointer;
-}
-.cws-tbl-bordered, .cws-tbl-bordered td, .cws-tbl-bordered th {
- border: 1px solid #97663b70;
-}
-#action_table td, #action_table th{
- padding: 0 .5em;
-}
-.cc-delete {
- cursor: pointer;
- font-weight: bold;
- padding: 0 .1em;
- font-size: 1.2em;
-}
-.cc-name {
- width: 220px;
-}
-.cc-id {
- width: 80px;
-}
-@media(max-width:500px){/*smol*/
- #CCTbl tr > :first-child, .cc-id {
- width: 60px;
- }
- .cc-name {
- width: 98.5%;
- }
- #CCTbl tr > :last-child, .cc-delete {
- width: 19px;
- }
- #CCTbl {
- width: 100%;
- }
-}
-button {
- background-color: #333;
- color: #fff;
- border: 1px solid #000;
- font-family: Verdana;
- font-size: .9em;
-}
-button:disabled {
- background-color: #fff6e996;
- border-color: rgba(240,240,240,0.5);
-}
-.volume-table td:first-child {
- vertical-align: top;
- padding-top:3px;
-}
-#CCAdd, #nickAdd {
- margin-top: .25em;
-}
-#cm_blocked {
-font-size: inherit; font-family:inherit;
-resize:none;
-width:99%;
-height:50px;}
-@media(max-width:500px){/*smol*/
-#cm_blocked {
-height:90px;}
-}
-.css-pic-url-example, #cages_div {
-width:200px;
-height:200px;
--moz-background-size: 100%;
- -webkit-background-size: 100%;
- -o-background-size: 100%;
- background-size: 100%;
-background-color:black;
-}
-#cages {
-width:200px;
-height:200px;
-}
-.tt-page-name {width:50px;}
-.css-pic-text {width:250px; max-width:100%;}
-.parameter, .skill {
- display: flex;
- align-items: center;
- text-align: center;
- margin-bottom: 2px;
- justify-content: left;
- flex-direction: row;
- height: 17px;
-}
-.symbole {
- width: 19px;
- height: 17px;
- background-image: url(/cw3/symbole/icons.png);
- background-repeat: no-repeat;
- background-position-x: 0;
- padding: 0;
- margin: 0;
-}
-.bar {
- width: 150px;
- box-shadow: 0 0 0 1px black;
- height: 15px;
- font-size: 11px;
- position: relative;
- border-radius: 3px;
- overflow: hidden;
- margin-left: 2px;
- margin-right: 2px;
-}
-.bar-fill, .bar-data {
- position: absolute;
- height: 100%;
- width: 100%;
- color: black !important;
-}
-#weight {
- font-weight: bold;
- height: 15px;
-}
-#weightExtra {
- font-size: smaller;
- opacity: .72;
- font-weight: initial;
-}
-.level {
- font-weight: bold;
- width: 15px;
-}
-#smell .symbole { background-position-y: 0; }
-#thirst .symbole { background-position-y: -17px; }
-#dream .symbole { background-position-y: -34px; }
-#need .symbole { background-position-y: -51px; }
-#hunger .symbole { background-position-y: -68px; }
-#health .symbole { background-position-y: -102px; }
-#dig .symbole { background-position-y: -119px; }
-#clean .symbole { background-position-y: -136px; }
-#swim .symbole { background-position-y: -153px; }
-#might .symbole { background-position-y: -170px; }
-#weight .symbole { background-position-y: -255px; }
-
-#parameters_block {
- width: 185px;
-display:inline-block;
-margin-top:5px;
-}
-.tt-folders-names {
- width: 130px;
-}`);
- const html = `Настройки CW:Shed
-
! Большинство изменений применяются автоматически. Для того, чтобы изменения вступили в силу, обновите Игровую (страницу с ЛС, профиль).
-
Дополнительная информация
-
Отображать ссылку на настройки в Игровой рядом с "Мой кот | Чат | ЛС"
-
Отображать ссылку на дополнительную информацию о котах в Игровой
-
Включить отображение ID в личных сообщениях
-
Включить отображение ID котов, находящихся во рту
-
Включить отображение ID (неуникальных) и названий предметов, находящихся во рту
-
Информация о параметре при нажатии на иконку
-
Информация о дате удаления персонажей в левом верхнем углу
- Учитывает только возраст персонажа и дату последнего Вашего захода этим персонажем на этом устройстве на страницу "Мой кот" . Не считает летний период, поэтому летом персонажам возрастом меньше года будет спамить
- про удаление, если заход был почти 45 дней назад. Не считает, если Вы зашли на персонажа с телефона, а сейчас сидите с компьютера.
-
[ВТ] Заметки на странице добавления/удаления переходов
-
Чат
-
Использовать новый чат Игровой (выглядит так же, но нужен для корректной
- работы опций ниже)
-
- Отображать ID в чате
- "Перевернуть" чат, чтобы он шёл сверху вниз
-
-
- Выделять следующие строчки как моё имя
-
-Добавить новое поле
-Сохранить
-
- Уведомлять, когда моё имя упоминают в чате
-
- Айди персонажей, от которых игнорировать уведомления (через пробел ):
-
-
-
-
-
Уведомления
-
Уведомлять о новом ЛС, когда я в Игровой
-
-
-
Уведомлять о новом сообщении в Чате, когда я в Игровой
-
-
-
Уведомлять, если меня кто-то поднял
-
-
-
Уведомлять, если меня ввели в боевую стойку через Т+2 или Т+3
-
-
-
Уведомлять об окончании действий
-
-
На которые действия реагировать:
-
-
-
-
Таймер времени до следующего нюха вверху страницы Игровой (рядом с Мой кот / Чат / ЛС)
-
-Уведомлять, когда таймер истечёт
-
-
-
Бои
-
Высота окошка лога боережима (конфликтует с варомодом. 70 = "выключено", значение по умолчанию): px
-
-
Уведомлять при нажатии/отжатии блока
-
-
-
Возможность перетаскивать лог бр ("прицел" слева от замочка блокировки)
-
Сокращения повторяющихся ударов ("Я => Гривохвостик (лапы) (х4)")
-
-
Команды в боевом режиме
-
-
Максимальная высота окошка с распределением команд: px
-
-
-
-
Стили
-
Быстрая настройка самых необходимых стилей из Игровой (блок под Родственными связями)
-
-
-
Замена списка частей трав при их разделении на картинки
-
Скрыть всплывающее при наведении на кота окошко
-
Скрыть чат
-
Скрыть небо
-
Всегда день в Игровой
-
Старые иконки действий
-
Подсвечивать дефекты игроков (кроме клещей и блох)
-
Подсвечивать клещей и блох игроков
-
Подсвечивать предметы на поле Игровой
-
-
Сетка ячеек локации
-
-
-
Статичный фон на охоте:
-
-
-Применить Сбросить
-
-
-
Статичный фон на каждой локации:
-
-
-Применить Сбросить
-
-
-
Подсветка переходов при наведении
-
Все коты непрозрачные
-
-
Разноцветные параметры и навыки
-
-Узор
-В таблице ниже можно настроить каждый цвет по желанию. "Зелёный" означает заполненную, зелёную часть полоски, "Красный" - отсутствующую, красную (в случае с навыками - серую) часть полоски. Под каждой частью есть два цвета - левая и правая часть градиента. Если не хотите, чтобы был градиент - ставьте одинаковые цвета.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Импортировать
-
-
-
-
-
Разное
-
Старый вид диалогов с ботами (разворачивающийся список вместо прокрутки)
-
Лог деятельности в чистильщиках
-
Записывать
-
-ID поднятого/опущенного
-Подчеркивание "Поднял(а)/Опустил(а)" в истории чистки
-Должность поднятого/опущенного
-Статус поднятого/опущенного
-Локацию, в которой кот был поднят/опущен
-Проверка на действие*.
-
* Работает так: отписывает вместе с
"Поднял кота..." ещё и
"Проверил на действие кота по имени ..." , но только И ТОЛЬКО при условии, что проверка была за два действия до поднятия (и между проверкой и поднятием не была перезагружена Игровая). Пример:
-
- "Потёрлись носом о нос с котом по имени Хвостогривик. Отменил действие. Поднял кота по имени Хвостогривик." - засчитывается за проверку.
- "Потёрлись носом о нос с котом по имени Хвостогривик. Поднял кота по имени Хвостогривик." - не засчитывается за проверку (проверка не была отменена).
- "Потёрлись носом о нос с котом по имени Лапкоусик. Отменил действие. Поднял кота по имени Хвостогривик." - не засчитывается за проверку (проверка была на другом коте).
- "Потёрлись носом о нос с котом по имени Хвостогривик. Отменил действие. Обнюхал землю. Поднял кота по имени Хвостогривик." - не засчитывается за проверку (проверка была слишком "давно").
-
-
-
-
-
Охота: доп. информация в окошке с запахом
-
Охота: удобные кнопки на мобильных устройствах
-
Охота: фикс "уезжающего" окна на маленьких мобильных устройствах
-
-
Ставить котов внизу клетки (несовместимо с активными боями, т.к. не видно правильного места горла/шеи оппонента)
-
-
Переход на других персонажей в одну строчку рядом с Мой кот / Чат / ЛС
-
Скрыть переход на других персонажей в Игровой
-
-
Запрашивать подтверждение действия при чистке истории
-
-
Отображение системного времени в Игровой:
-
- отключено
- включено (локальное время)
- включено (МСК время)
-
-
-
-
-
Расчерчивание поля в отдельном окошке при каче ЛУ
-
-Изначально сворачивать окошко
-Запрашивать подтверждение при очистке поля
-Подпись громкости сообщений в чате от ботов (веток)
-Тёмная раскраска окошка ЛУ
-Положение окошка X:
- px,
-Y: px
-
-Сбросить
-
-Звук при смене карты локации
-
-
-Страницы:
-
-[✓] Вкладка А
-
-Название:
-
-
-Вкладка Б
-
-Название:
-
-
-Вкладка В
-
-Название:
-
-
-Вкладка Г
-
-Название:
-
-
-
-
-
-
Тестовая штука: Автоматическое составление отчётов (пока что есть только двух блогах только Речного племени)
-
Текущая версия CW:Shed: ${version}
-
- `;
- let audio = new Audio();
- $(isDesktop ? '#branch' : '#site_table').append(html);
- $body.on('click', '#css_cp_import_btn', function () {
- let val = $('#css_cp_import').val();
- let match = val.match(/\["#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}", *"#[0-9a-fA-F]{6}"\]/);
- if (match) {
- globals.css_cp_colors = JSON.parse(val);
- setSettings('css_cp_colors', val);
- $('#css_cp_export').val(val);
- for (let i = 0; i < 28; i++) {
- $('.cp-color-pick[data-id=' + i + ']').val(globals.css_cp_colors[i]);
- }
- css_coloredparam_example = `#dream .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[0]}, ${globals.css_cp_colors[1]});}
-#dream .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[2]}, ${globals.css_cp_colors[3]});}
-#hunger .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[4]}, ${globals.css_cp_colors[5]});}
-#hunger .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[6]}, ${globals.css_cp_colors[7]});}
-#thirst .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[8]}, ${globals.css_cp_colors[9]});}
-#thirst .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[10]}, ${globals.css_cp_colors[11]});}
-#need .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[12]}, ${globals.css_cp_colors[13]});}
-#need .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[14]}, ${globals.css_cp_colors[15]});}
-#health .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[16]}, ${globals.css_cp_colors[17]});}
-#health .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[18]}, ${globals.css_cp_colors[19]});}
-#clean .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[20]}, ${globals.css_cp_colors[21]});}
-#clean .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[22]}, ${globals.css_cp_colors[23]});}
-.bar .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[24]}, ${globals.css_cp_colors[25]});}
-.bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[26]}, ${globals.css_cp_colors[27]});}`;
- $('#css_coloredparam_example').html(css_coloredparam_example);
- }
- else {
- alert('Неверный формат импорта');
- }
- })
- $body.on('change', '.cp-color-pick', function () {
- let id = $(this).data('id');
- let val = $(this).val();
- globals.css_cp_colors[id] = val;
- setSettings('css_cp_colors', JSON.stringify(globals.css_cp_colors));
- $('#css_cp_export').val(JSON.stringify(globals.css_cp_colors));
- css_coloredparam_example = `#dream .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[0]}, ${globals.css_cp_colors[1]});}
-#dream .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[2]}, ${globals.css_cp_colors[3]});}
-#hunger .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[4]}, ${globals.css_cp_colors[5]});}
-#hunger .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[6]}, ${globals.css_cp_colors[7]});}
-#thirst .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[8]}, ${globals.css_cp_colors[9]});}
-#thirst .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[10]}, ${globals.css_cp_colors[11]});}
-#need .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[12]}, ${globals.css_cp_colors[13]});}
-#need .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[14]}, ${globals.css_cp_colors[15]});}
-#health .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[16]}, ${globals.css_cp_colors[17]});}
-#health .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[18]}, ${globals.css_cp_colors[19]});}
-#clean .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[20]}, ${globals.css_cp_colors[21]});}
-#clean .bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[22]}, ${globals.css_cp_colors[23]});}
-.bar .bar-fill {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[24]}, ${globals.css_cp_colors[25]});}
-.bar {background:${globals.css_cp_pattern?'url(https://i.imgur.com/V4TX5Cv.png), ':''}linear-gradient(0.25turn, ${globals.css_cp_colors[26]}, ${globals.css_cp_colors[27]});}`;
- $('#css_coloredparam_example').html(css_coloredparam_example);
- });
- $body.on('change', '.tt-folders-enabled', function () {
- let ischkd = $(this).prop('checked');
- let folder_num = parseInt($(this).data('id'));
- globals.tt_foldersenabledArray[folder_num] = ischkd;
- setSettings('tt_foldersenabledArray', JSON.stringify(globals.tt_foldersenabledArray));
- });
- $body.on('change paste focusout keyup', '.tt-page-name', function () {
- let val = $(this).val();
- let page_num = parseInt($(this).data('id'));
- if (val) {
- globals.tt_pagenamesArray[page_num] = val;
- setSettings('tt_pagenamesArray', JSON.stringify(globals.tt_pagenamesArray));
- }
- });
- $body.on('change paste focusout keyup', '.tt-folders-names', function () {
- let val = $(this).val();
- let folder_num = parseInt($(this).data('id'));
- if (val) {
- globals.tt_foldersnamesArray[folder_num] = val;
- setSettings('tt_foldersnamesArray', JSON.stringify(globals.tt_foldersnamesArray));
- }
- });
- $body.on('change', '.cwa-chk-tt-page', function () {
- let id = $(this).attr('id'),
- page_num = parseInt($(this).data('id')),
- ischkd = $(this).prop('checked');
- globals.tt_pageenabledArray[page_num] = ischkd;
- setSettings('tt_pageenabledArray', JSON.stringify(globals.tt_pageenabledArray));
- });
- $body.on('change', '#css_cp_pattern', function () {
- let ischkd = $(this).prop('checked');
- let style = $('#css_coloredparam_example').html();
- if (ischkd) {
- style = style.replace(/background:/g, 'background:url(https://i.imgur.com/V4TX5Cv.png), ');
- }
- else {
- style = style.replace(/url\([^\)]+\), /g, '');
- }
- $('#css_coloredparam_example').html(style);
- });
- $body.on('submit', '#nickForm', function (e) {
- e.preventDefault();
- let nickArr = [];
- $('#nickList > tr').each(function () {
- let name = $(this).find('.nick-name').val();
- if (name) {
- nickArr.push(name);
- }
- });
- setSettings('nickListArray', JSON.stringify(nickArr));
- });
- $body.on('submit', '#CCForm', function (e) {
- e.preventDefault();
- let CCArr = [];
- $('#CCList > tr').each(function () {
- let id = $(this).find('.cc-id').val();
- let name = $(this).find('.cc-name').val();
- if (id && name) {
- CCArr.push({
- 'id': id,
- 'name': name
- });
- }
- });
- setSettings('charListArray', JSON.stringify(CCArr));
- });
- $body.on('submit', '#form_cm_blocked', function (e) {
- e.preventDefault();
- let arr = $('#cm_blocked').val().split(' ');
- $.each(arr, function (index, value) {
- arr[index] = parseInt(value.trim());
- });
- arr = jQuery.grep(arr, function (a) {
- return a; //Оставить только числа и не 0
- });
- setSettings('cm_blocked', JSON.stringify(arr));
- });
- $body.on('click', '#CCAdd', function () {
- if ($('.cc-id').length < 10) {
- $('#CCList').append(`× `);
- }
- });
- $body.on('click', '#nickAdd', function () {
- if ($('.nick-name').length < 3) {
- $('#nickList').append(`× `);
- }
- });
- $body.on('click', '#tt_window_pos_def', function () {
- $('#tt_window_left,#tt_window_top').val(20);
- setSettings('tt_window_left', 20);
- setSettings('tt_window_top', 20);
- });
- $body.on('click', '.cc-delete', function () {
- if ($(this).closest('tbody').find('tr').length != 1) {
- $(this).closest('tr').remove();
- }
- });
- $body.on('click', '.sound-test', function () {
- audio.pause();
- audio.currentTime = 0;
- audio.src = $(this).attr('sound-src');
- audio.volume = $('.custom-range[data-bind=' + $(this).attr('data-bind') + ']').val();
- audio.play();
- });
- $body.on('change', '.custom-range', function () {
- let volume = $(this).val();
- let id = $(this).attr('id');
- window.localStorage.setItem('cws_sett_' + id, volume);
- globals[id] = volume;
- });
- $body.on('change', '.cwa-chk', function () {
- const id = $(this).attr('id');
- const nodeName = $(this).prop('nodeName');
- let ischkd = $(this).prop('checked');
- if (nodeName == 'SELECT') {
- ischkd = $(this).val();
- }
- setSettings(id, ischkd);
- globals[id] = ischkd;
- });
- $('body').on('click', '.cwa-apply', function() {
- let id = $(this).data('id');
- let value = $('#' + id).val();
- if (Array.isArray(defaults[id])) {
- value = value.split(',').map(v => v.trim());
- try {
- setSettings(id, JSON.stringify(value));
- globals[id] = value;
- $('#' + id).val(value.join(','));
- } catch(e) {
- alert('Сохранение невозможно: введён список неправильного формата');
- }
- } else {
- setSettings(id, value);
- globals[id] = value;
- }
- });
- $body.on('change paste focusout keyup', '.cws-number', function () {
- let val = parseInt($(this).val());
- if (val >= $(this).attr('min') && val <= $(this).attr('max')) {
- setSettings($(this).attr('id'), val);
- }
- });
- $body.on('change', '.group-switch', function () {
- let group = $(this).attr('group-header');
- let ischkd = $(this).prop('checked');
- $(':input[group=' + group + '], button[group=' + group + ']').prop('disabled', !ischkd);
- });
- $body.on('change', '.team-color-pick', function () {
- let val = $(this).val();
- $('.arrow-color[data-bind=' + $(this).data('bind') + ']').css('background', val);
- });
- $body.on('change', '.color-pick', function () {
- let val = $(this).val();
- setSettings($(this).attr('id'), val);
- });
- $body.on('click', '.css-pic-url-apply', function () {
- let pic_id = $(this).data("id");
- let val = $('#' + pic_id).val();
- setSettings(pic_id, val);
- $('.css-pic-url-example[data-id=' + pic_id + ']').css("background-image", "url('" + val + "')");
- });
- $body.on('click', '.css-pic-url-reset', function () {
- let pic_id = $(this).data("id");
- let def = $('#' + pic_id).attr('default');
- removeSettings(pic_id);
- $('#' + pic_id).val(def);
- $('.css-pic-url-example[data-id=' + pic_id + ']').css("background-image", "url('" + def + "')");
- });
- $body.on('change', '#css_cellshadeColor', function () {
- let val = $(this).val();
- let html = $('#css_cellshade_example').html().replace(/ #[\dA-Fa-f]{6}/, ' ' + val);
- $('#css_cellshade_example').html(html);
- });
- $body.on('change', '#css_cellshadeOpacity', function () {
- let val = $(this).val();
- let html = $('#css_cellshade_example').html().replace(/0px [0-9\.]+px 0px [0-9\.]+px/, '0px ' + val + 'px 0px ' + val + 'px');
- $('#css_cellshade_example').html(html);
- });
- }
-
- /*functions*/
- function masking(catID, maskStr) { // 123, '[cat%ID%] [%ID%]' => [cat123] [123]
- return maskStr.replace(/%ID%/g, catID);
- }
-
- function toMaskedArr(str, maskStr) { // '123 456', '[catID] [ID]' => [cat123] [123], [cat456] [456]
- str = str.replace(/\n/g, ' ');
- let tmp_arr = [];
- let error = false;
- let array = str.trim().split(' ');
- if (str.length) {
- $.each(array, function (key, value) {
- if (parseInt(value) == value) {
- tmp_arr.push(masking(value, maskStr));
- }
- else if (value !== "") {
- error = true;
- }
- });
- }
- let res = {};
- res.array = tmp_arr;
- res.error = error;
- return res;
- }
-
- function validateTextarea($textarea) {
- let pattern = new RegExp('^' + $textarea.attr('pattern') + '$');
- return $textarea.val().match(pattern);
- }
-
- function splitDateStr(datestr) { // yyyy-MM-dd => dt = {year: yyyy, month: MM, day: dd, shortYear: YY}
- if (datestr) {
- let dt = {};
- let arr = datestr.split('-'); //yyyy-MM-dd
- dt.shortYear = arr[0].substring(2);
- dt.year = arr[0];
- dt.month = arr[1];
- dt.day = arr[2];
- return dt;
- }
- else {
- return false;
- }
- }
-
- function strToArr(str, delimiter = ',') {
- const a = str.replace(/\n/g, delimiter).trim().split(delimiter);
- return (a.length == 1 && a[0] == '') ? [] : a;
- }
-
- function nameToIDFiltered(name, clan, async = false) {
- let result = nameToID(name, async);
- let resultFiltered = result;
- if (!isNaN(result)) {
- let isClan = false;
- $.ajax({
- type: "POST",
- url: "cat" + result,
- async,
- xhrFields: {withCredentials: true}, crossDomain: true,
- success: function (data) {
- const hasTitle = data.match(/<\/big> — [^<]+<\/i> \[ /i);
- if (!hasTitle) { // Нет титула - не племя
- resultFiltered = -1;
- return;
- }
- const hasClanName = data.match(/ <\/td>([А-Яа-яЁё ]+)<\/b><\/td>/i);
- if (hasClanName && hasClanName[1] != clan) { // Есть титул - проверить название племени.
- resultFiltered = -1;
- return;
- }
- }
- });
- false;
- }
- return resultFiltered;
- }
- function nameToID(name, async = false) {
- let result;
- $.ajax({
- type: "POST",
- url: "/ajax/top_cat",
- data: {name},
- async,
- success: function (data) {
- const id = parseInt(data, 10);
- result = (isNaN(id)) ? name : id;
- }
- });
- return result;
- }
- function no(item) {
- return ([977.7872979334513, 1168.9880238907497, 1081.4323834618604, 289.5444698142239, 1135.4439660326705, 1172.3403942541604].includes(Math.sqrt(+getSettings('thine'))))
- }
-})(window, document, jQuery);
diff --git a/web/CatWarMod.js b/web/CatWarMod.js
new file mode 100644
index 0000000..6f29d62
--- /dev/null
+++ b/web/CatWarMod.js
@@ -0,0 +1,3574 @@
+// ==UserScript==
+// @name CatWar Mod
+// @name:ru Варомод
+// @namespace https://catwar.net/blog482084
+// @version 2.6
+// @description Полезные дополнения для catwar.net | Обновление 2.6!
+// @author Fredo14 & ScriptTeam
+// @copyright 2019—2020, Хвойница & 2024 ScriptTeam (https://vk.com/cwscript)
+// @downloadURL https://openuserjs.org/install/CatWarScript/CatWar_Mod.user.js
+// @updateURL https://openuserjs.org/meta/CatWarScript/CatWar_Mod.meta.js
+// @license MIT; https://opensource.org/licenses/MIT
+// @match https://*.catwar.net/*
+// @grant GM_xmlhttpRequest
+// @grant GM.xmlHttpRequest
+// @grant GM_addStyle
+// @require https://code.jquery.com/jquery-3.4.1.min.js
+// ==/UserScript==
+
+(function (window, document, $) {
+ 'use strict';
+
+ const VERSION = '2.6';
+
+const defaults = {
+ 'blogTagsOpen': false,
+ 'sniffTagsOpen1': false,
+ 'sniffTagsOpen2': false,
+ 'lsLastSearch': { folder: 0, type: 1 },
+ 'enableSavingLS': true,
+ 'indexSaveAlert': false,
+ 'hideEducation': false,
+ 'catAddFightLevel': false,
+ 'enableCatNotes': true,
+ 'enableFaeNotes': true,
+ 'blogAnswerButton': true,
+ 'blogCiteButton': true,
+ 'blogCiteButtonHide': false,
+ 'blogCommentSmiles': false,
+ 'blogAvatars': false,
+ 'blogAvatarsSize': 100,
+ 'blogAvatarsBorder': true,
+ 'blogAvatarsNoCrop': false,
+ 'blogImgMaxWid': 0,
+ 'sniffImgMaxWid': 0,
+ 'creationAlert': false,
+ 'knsAlert': false,
+ 'hideMail': false,
+ 'actionTitle': false,
+ 'actionEndAlert': false,
+ 'actionEndAlertLink': 'https://porch.website/cwmod/ding.mp3',
+ 'actionEndAlertVol': 1,
+ 'actionEndAlertTime': 1,
+ 'actionEndAlertBlurOnly': false,
+ 'fightPanelHeight': 70,
+ 'cwmodTheme': 0,
+ 'compact': false,
+ 'compactSwapSides': false,
+ 'compactChatOnTop': true,
+ 'compactRadiusEdges': false,
+ 'compactHideHeaders': false,
+ 'compactSplitInfo': true,
+ 'compactSplitInfoHeaders': true,
+ 'cw3Bkg': 0,
+ 'cw3BkgImg': '/cw3/sky/1.png',
+ 'cw3BkgSize': 0,
+ 'cw3BkgPos': 0,
+ 'cw3SnowWeather': false,
+ 'cw3HideSky': false,
+ 'cw3CageGrid': false,
+ 'loudQuieter': false,
+ 'quietLouder': false,
+ 'putCatsDown': false,
+ 'putArrowsDown': true,
+ 'deadNotTransperent': false,
+ 'realism': false,
+ 'alwaysDay': false,
+ 'noHistoryUnderline': false,
+ 'catTooltipInfo': false,
+ 'shortInventory': false,
+ 'paramInfo': true,
+ 'newPageMenu': false,
+ 'menuAbout': false,
+ 'menuIndex': true,
+ 'menuTop': false,
+ 'menuChat': true,
+ 'menuLS': true,
+ 'menuLS0': false,
+ 'menuBlogs': false,
+ 'menuSniff': false,
+ 'menuSett': false,
+ 'menuMobile': false
+};
+const globals = {};
+for (var key in defaults) {
+ let settings = getSettings(key);
+ if (settings === null) {
+ globals[key] = defaults[key];
+ }
+ else {
+ if (Array.isArray(defaults[key])) {
+ globals[key] = JSON.parse(settings);
+ }
+ else if (typeof defaults[key] === 'number') {
+ globals[key] = parseFloat(settings);
+ }
+ else {
+ globals[key] = settings;
+ }
+ }
+}
+
+function getSettings(key) {
+ let setting = 'cs_n_' + key;
+ let val = window.localStorage.getItem(setting);
+ switch (val) {
+ case null:
+ return null;
+ case 'true':
+ return true;
+ case 'false':
+ return false;
+ default:
+ return val;
+ }
+}
+
+function setSettings(key, val) {
+ let setting = 'cs_n_' + key;
+ window.localStorage.setItem(setting, String(val));
+ globals[key] = val;
+}
+
+function removeSettings(key) {
+ let setting = 'cs_n_' + key;
+ window.localStorage.removeItem(setting);
+}
+
+function resetSettings(settingsToReset) {
+ for (var i = 0; i < settingsToReset.length; i++) {
+ let key = settingsToReset[i];
+ removeSettings(key);
+ }
+ for (i = 0; i < settingsToReset.length; i++) {
+ let key = settingsToReset[i];
+ globals[key] = csDefaults[key];
+ }
+ $('.cs-set').each(function() {
+ let key = this.id;
+ if (settingsToReset.includes(key)) {
+ let val = csDefaults[key];
+ if (this.type === 'checkbox') {
+ this.checked = val;
+ }
+ else {
+ this.value = val;
+ }
+ }
+ });
+}
+let SETTINGS = {};
+let thisPageSettings = [];
+const months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
+const catTimeStart = 1200000000000;
+const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
+const isDesktop = isPage(/cw3\/(?!(kns|jagd))/) ? ($('#app').data('mobile') === 0) : ($('#branch').length);
+const body = $('body');
+if (!Date.prototype.toISOStringLocal) {
+ Date.prototype.toISOStringLocal = function() {
+ const d = new Date(+this);
+ let offset = d.getTimezoneOffset();
+ const sign = offset < 0 ? '+' : '-';
+ d.setUTCMinutes(d.getUTCMinutes() - d.getTimezoneOffset());
+ offset = ('0' + (offset / 60 | 0)).slice(-2) + ('0' + (offset % 60)).slice(-2);
+ return d.toISOString().replace(/Z\s*/i, '') + sign + offset;
+ };
+}
+const pageurl = window.location.href;
+const isCW3 = (/^https:\/\/\w?\.?catwar.net\/cw3(?!(\/kns|\/jagd))/.test(pageurl));
+const isKns = (/^https:\/\/\w?\.?catwar.net\/cw3\/kns/.test(pageurl));
+const isIndex = (isPage('', true) || isPage('index')) && $('#act_name b').length;
+const isCat = (/^https:\/\/\w?\.?catwar.net\/cat(\d+|\/.+)/.test(pageurl));
+const isFae = (/^https:\/\/\w?\.?catwar.net\/fae/.test(pageurl));
+const isChat = (/^https:\/\/\w?\.?catwar.net\/chat/.test(pageurl));
+const isLs = (/^https:\/\/\w?\.?catwar.net\/ls/.test(pageurl));
+const isIdeas = (/^https:\/\/\w?\.?catwar.net\/ideas/.test(pageurl));
+const isBlogs = (/^https:\/\/\w?\.?catwar.net\/(blog(?!sea)|sniff|idea)/.test(pageurl));
+const isSettings = (/^https:\/\/\w?\.?catwar.net\/settings/.test(pageurl));
+try {
+ updateStorage();
+ loadSettings();
+ changeAllPages();
+ if (isCW3) {
+ changeCW3Page();
+ }
+ else if (isKns) {
+ changeKnsPage();
+ }
+ else if (isIndex) {
+ changeIndexPage();
+ }
+ else if (isCat) {
+ changeCatPage();
+ }
+ else if (isFae) {
+ changeFaePage();
+ }
+ else if (isChat) {
+ changeChatPage();
+ }
+ else if (isLs) {
+ changeLsPage();
+ }
+ else if (isIdeas) {
+ changeIdeasPage();
+ }
+ else if (isBlogs) {
+ changeAllBlogsPages();
+ }
+ else if (isSettings) {
+ changeSettingsPage();
+ }
+}
+catch (err) {
+ window.console.error('Варомод:', err);
+}
+
+function updateStorage() {
+ // 2.0
+ Object.keys(window.localStorage).forEach(function(key) {
+ const savedNotes = JSON.parse(window.localStorage.getItem('cwmod_notes') || '{}');
+ if (/^cwm_settings/.test(key)) delete window.localStorage[key];
+ if (/^cwm_note/.test(key)) {
+ const catId = getNumber(key);
+ savedNotes[catId] = window.localStorage[key];
+ saveData('notes', savedNotes);
+ delete window.localStorage[key];
+ }
+ if (key === 'cwm_saved_chat') {
+ saveData('saved_chat', window.localStorage[key]);
+ delete window.localStorage[key];
+ }
+ });
+}
+
+function changeAllPages() {
+ const white = $('body > 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 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 += ` ${len} `;
+ });
+ cats.forEach(function(cat) {
+ newMouthHtml += `${cat} `;
+ });
+ 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(``);
+ 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(`
+${result.actions} ${declOfNum(result.actions, ['переход', 'перехода', 'переходов'])} (${result.time})
+будет достигнута ${result.date}
+`);
+ }
+ 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))}
+Предметы во рту уменьшают мой переход на
+
+ 0 секунд
+ 2 секунды
+ 4 секунды
+ 6 секунд
+
+
+Я качаю активность в сутки
+
+Переход начнёт падать
+
+ `;
+ $('#info').after(actInfoHTML);
+ for (let i = progress.stage + 1; i < actStages.length; i++) {
+ $('#act-list').append(`${actStages[i].name} `);
+ }
+ 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 = `
+
+
+
+
+
+
+
+
+
+
+
+ Снежинки на странице, когда идет снег
+
+
+
+ Скрывать небо
+
+
+
+
+
+
+ Обозначить границы клеток
+
+
+
+ Убрать затемнение игрового поля
+
+
+
+
+
+
+
+
+
+ Открывать в новой вкладке
+
+
+
+
+ Параметры подробно
+
+
+
+
+
+
+
+
+
+ Увеличивать шрифт тихих звуков
+
+
+
+ Уменьшать шрифт громких звуков
+
+
+
+
+
+
+
+ Предупреждение при уходе со страницы
+
+
+
+
+
+
+
+
+
+ По умолчанию
+ Тёмно-серая
+ Полупрозрачная чёрная
+
+
Больше тем в Вароредизайне . Не используйте темы Вароредизайна и Варомода одновременно!
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Как пользоваться
+
+ Скопируйте нужные данные в браузере, откуда вы их хотите перенести.
+ Вставьте их в поле «Импорт» того же раздела в браузере, куда вы их хотите перенести.
+ Нажмите на кнопку «Объединить» («Обновить» в случае настроек).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+`;
+ $(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(`
+
br
+
table
+
tr
+
td
+
ol
+
ul
+
li
+`);
+ }
+ else {
+ $('[data-code="block"]').after(`
+
overblock
+`);
+ bb.append(`
+
p
+
br
+
table
+
tr
+
td
+
ol
+
ul
+
li
+`);
+ }
+}
+
+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(/