Wykop XS

Wykop XS służy do wspomagania działania stylu "Wykop X", który jest wymagany do poprawnego działania niniejszego skryptu. Wykop X zainstaluj stąd: http://style.wykopx.pl

נכון ליום 18-02-2023. ראה הגרסה האחרונה.

// ==UserScript==
// @name        Wykop XS
// @name:pl     Wykop XS
// @name:en     Wykop XS
// @version     2.8.0
// @author      SebastianDosiadłgo <[email protected]>
// @author      xXdeepfriedXx: "getObserveCount", "getTagsFingerPrint", "newAutoCompleteWindowAdded" - xXdeepfriedXx napisał funkcje pobierające z API wykopu liczbę obserwujących tagi podczas ich wpisywania! Podziękowania, za uzyczenie kodu.
// @namespace   Violentmonkey Scripts
// @match       https://wykop.pl/*
// @require     https://unpkg.com/xhook@latest/dist/xhook.min.js
// @require     https://unpkg.com/[email protected]/dist/localforage.min.js
// @require     https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require     https://greasyfork.org/scripts/383527-wait-for-key-elements/code/Wait_for_key_elements.js?version=701631
// @require     https://greasyfork.org/scripts/458629-depaginator-for-wykop-pl/code/Depaginator%20for%20Wykoppl.user.js
// @supportURL  http://wykop.pl/tag/wykopwnowymstylu
// @contributionURL  https://buycoffee.to/sebastiandosiadlgo
// @compatible  firefox, chrome, opera, safari, edge
// @grant       GM_addStyle
// @license     No License
// @description Wykop XS służy do wspomagania działania stylu "Wykop X", który jest wymagany do poprawnego działania niniejszego skryptu. Wykop X zainstaluj stąd: http://style.wykopx.pl
// @description:en Wykop XS is a helper script for userstyle "Wykop X" which modifies wykop.pl website and make it easier to use adding enhancements and new features. Check it out here: http://style.wykopx.pl
// ==/UserScript==
const currentVersion = "2.8.0";
const dev = false;

// ustawienieLocalStorage do zapisywania dostawcow w pamięci
let wykopxStorageMirkoukrywacz = localforage.createInstance({
	driver: localforage.LOCALSTORAGE,
	name: "wykopx",
	storeName: "mirkoukrywacz",
});

// przenoszenie na tagi:                              wykop.pl/#heheszki
// i na profile użytkownikow:                         wykop.pl/@m__b
// wyszukiwanie wpisów danej osoby w konkretnym tagu  wykop.pl/@m__b/#internet   albo  wykop.pl/#internet/@m__b/
(async () => {
	consoleX("(async () => {", 1);
	let pathname = new URL(document.URL).pathname;
	let hash = new URL(document.URL).hash;
	let at, tag;

	// #
	if (hash.length > 0) {
		let tagWithHash = hash.split("/")[0];
		let tagWithoutHash = tagWithHash.slice(1);
		let tagNumber = Number.parseInt(tagWithoutHash);

		if (tagWithoutHash.length > 1 && (tagNumber == "NaN" || tagWithoutHash.length < 9) && tagWithoutHash != "dodaj") {
			if ((tag = getTagFromUrl(tagWithHash, "#"))) {
			}
			if ((at = getAtFromUrl(hash, "@"))) {
			}
		}
	}

	// @
	if (pathname.split("/")[1] !== "szukaj" && pathname.length > 2) {
		if (at || (at = getAtFromUrl(pathname, "@"))) {
		}
	}

	if (tag && at) window.location.replace(`https://wykop.pl/szukaj/wszystkie/@${at}?tags=${tag}`);
	else if (tag) window.location.replace("https://wykop.pl/tag/" + tag);
	else if (at) window.location.replace("https://wykop.pl/ludzie/" + at);

	function getTagFromUrl(hashPath) {
		let tagArray = hashPath.split("/");
		for (let element of tagArray) {
			if (element.charAt(0) == "#") {
				element = element.slice(1);
				if (typeof Number.parseInt(element) == "NaN" || element.length < 9) {
					return element;
				}
			}
		}
		return false;
	}
	function getAtFromUrl(atPath) {
		let atArray = atPath.split("/");
		for (let element of atArray) {
			if (element.charAt(0) == "@") {
				return element.slice(1);
			}
		}
		return false;
	}
})();




/* Mirkoukrywacz */
waitForKeyElements("section.actions", mirkoukrywaczAddButtons, false);

waitForKeyElements("section.entry", addWykopXActionBoxToEntryAndComment, false);
//waitForKeyElements("section.entry.reply", addWykopXActionBoxToEntryAndComment, false);

function addWykopXActionBoxToEntryAndComment(jNode)
{
  // console.log(jNode);
  const comment_id = jNode.context.id.replace("comment-", "");
  const $entry_object = $(`#comment-${ comment_id }`);
  const comment_username = $entry_object.find("> article > header > div.left > a.avatar > span").text();
  getUserNotes(comment_username, comment_id);

//   console.log("comment_id: " + comment_id);
//   console.log("$entry_object: ");
//   console.log($entry_object);
//   console.log("comment_username: " + comment_username);

  // let html = `<div class="wykopxs wykopx_action_box"
  //                  id="wykopx_action_box-${ comment_id }"
  //                  data-username="${ comment_username }"
  //                  data-comment-id="${ comment_id }"
  //                  data-base-uri="${ jNode.context.baseURI }"
  //                  data-entry-type="entry-subcomment"
  //                  data-parent-comment-id="123456789"
  //                  data-grandparent-comment-id="123456789">
  //   <div class="wykopx_action_box_username">${ comment_username }</div>
  // </div>`;
  //jNode.find("> article > header").after(html);
}


const apiGetNotes = "https://wykop.pl/api/v3/notes/";
async function getUserNotes(username, comment_id)
{
  const response = await fetch(apiGetNotes + username, {
    method: 'GET', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
      'Authorization': "Bearer " + window.localStorage.token
    },
  })
  .then((response) => response.json())
  .then((user) => {
    const usernote = user.data.content;
    if(usernote.length > 0)
      {
        $(`section#comment-${ comment_id } > article > header`).after(`<div class="wykopxs wykopx_action_box_usernote">Twoja notatka do <strong>${ user.data.username}</strong> : <var>${ user.data.content }</var></div>`);
      }
    return user.data.content;
  });
}






function mirkoukrywaczAddButtons(jNode) {
	consoleX("mirkoukrywaczAddButtons(jNode)", 1);
	mirkoukrywaczHideAllBlockedElements();

	let html = `<button class="wykopxs hideThisShit" title="Wykop X - Mirkoukrywacz - Ukryj to na zawsze">Ukryj</button>`;

	jNode.find(`ul li.right`).prepend(html);
	consoleX(`Dodano przycisk "Ukryj" z Mirkoukrywacza`, 1);

	$(".hideThisShit").on("click", function () {
		let type = "unknown";

		let entry_stream = $(this).closest(".stream");
		if (entry_stream.hasClass("microblog")) type = "entry";
		else if (entry_stream.hasClass("entry-comments")) type = "entry";
		else if (entry_stream.hasClass("entry-subcomments")) type = "entry-subcomments";
		else if (entry_stream.hasClass("link-comments")) type = "link-comments";

		let entry = $(this).closest(".entry");

		let comment_id = entry.attr("id").split("-")[1];
		let username = entry[0].querySelector("a.username span").innerText;
		let text = entry[0].querySelector("div.content div.wrapper").innerText.replace(/\n/g, " ");

		let grandcomment_id = comment_id; /* id nad-komentarza */
		if (type == "entry-subcomments") {
			let entry_grandparent = entry.parent().closest(".entry");
			grandcomment_id = entry_grandparent.attr("id").split("-")[1];
		}

		/*let link_id = null;
        if (type == "link-comments")
        {

			entry.parents("aside.slots-info").addClass("dupa");
            console.log(link_aside);
			link_id = link_aside.attr("data-url").split("/")[1];      // /link/7013759/tu-najwiecej-polskich-dzieci-probuje-popelnic-samobojstwo
		}*/
		if (text.length > 50) text = text.substring(0, 50);
		mirkoukrywaczAddNewBlockedElement(comment_id, grandcomment_id, username, text, type);
	});
}

function mirkoukrywaczAddNewBlockedElement(id, grandcomment_id, username, text, type) {
	wykopxStorageMirkoukrywacz
		.setItem(id, {id, grandcomment_id, type, username, text, date: dayjs()})
		.then(function (value) {
			consoleX(`Mirkoukrywacz dodał do listy ukrywanych @${username}: ${text}`);
		})
		.catch(function (err) {
			consoleX(`mirkoukrywaczAddNewBlockedElement = error: ` + err);
		});
	mirkoukrywaczHideAllBlockedElements();
}

function mirkoukrywaczHideAllBlockedElements() {
	wykopxStorageMirkoukrywacz
		.iterate(function (value, key, iterationNumber) {
			$(`section#comment-${key}`).addClass("wykopx_mirkoukrywacz_hide");
		})
		.then(function () {})
		.catch(function (err) {});
}

function mirkoukrywaczAppendOneElementToHideList(value, key, iterationNumber = "⭐") {
	let hidden_element_html = ``;
	hidden_element_html += `
            <div class="wykopx_mirkoukrywacz_element" id="wykopx_mirkoukrywacz_element_${key}">
                <div class="wykopx_mirkoukrywacz_unhide" id="${key}" title="Przestań ukrywać ten element">❌</div>
                <div class="wykopx_mirkoukrywacz_lp">${iterationNumber}</div>
                <div class="wykopx_mirkoukrywacz_text">${value.text}</div>
                <div class="wykopx_mirkoukrywacz_id">${key}</div>
                <div class="wykopx_mirkoukrywacz_type">${value.type}</div>
                <div class="wykopx_mirkoukrywacz_date">${dayjs(value.date).format("YYYY-MM-DD HH:mm")}</div>
            </div>`;
	$("#wykopx_modal_mirkoukrywacz .wykopx_mirkoukrywacz_list_of_hidden_items").append(hidden_element_html);
	$(".wykopx_mirkoukrywacz_unhide").on("click", function () {
		mirkoukrywaczRemoveHiddenElement($(this).attr("id"));
	});
}

function mirkoukrywaczRefreshHideList() {
	wykopxStorageMirkoukrywacz
		.iterate(function (value, key, iterationNumber) {
			mirkoukrywaczAppendOneElementToHideList(value, key, iterationNumber);
		})
		.then(function () {})
		.catch(function (err) {});
}

function mirkoukrywaczBuildListOfHiddenElements() {
	let html = `
    <div class="wykopxs wykopx_modal" id="wykopx_modal_mirkoukrywacz">
        <div class="wykopx_modal-content">
           <aside class="wykopxs_info_bar wykopx_hide_this_if_stylus_is_installed">Masz już działający skrypt Wykop XS. Aby Mirkoukrywacz działał, musisz zainstalować i włączyć w Stylusie <a href="http://wiki.wykopx.pl" target="_blank">Wykop X</a></aside>
           <aside class="wykopxs wykopx_modal_mirkoukrywacz_is_turned_off wykopx_hide_this_if_mirkoukrywanie_is_turned_on">Wykop XS oraz Wykop X są zainstalowane poprawnie, ale Mirkoukrywacz jest wyłączony. Aby Mirkoukrywacz działał, włącz go w ustawieniach Stylusa. <A href="https://github.com/wykopx/WykopX/wiki/Extra#mirkoukrywacz" target="_blank">Zobacz instrukcję obsługi Mirkoukrywacza</a></aside>
           <header class="wykopxs"><span>Mirkoukrywacz: </span?><span>Lista ukrytych elementów</span></header>
           <section class="wykopxs wykopx_mirkoukrywacz_list_of_hidden_items">
              <span class="wykopx_mirkoukrywacz_hidden_list_is_empty">Żadne treści nie zostały jeszcze zaznaczone do ukrycia</span>
           </section>
        </div>
    </div>`;

	$("body").prepend(html);

	createNewProfileDropdownMenuItem("Wykop X - Mirkoukrywacz", "Wykop X - lista elementów ukrytych przez Mirkoukrywacz", "mirkoukrywacz", "mirkoukrywacz_open_modal_button");

	let modal = document.getElementById("wykopx_modal_mirkoukrywacz");
	let btn = document.getElementById("mirkoukrywacz_open_modal_button");
	//var span = document.getElementsByClassName("wykopx_close")[0];
	btn.onclick = function () {
		mirkoukrywaczRefreshHideList();
		modal.style.display = "block";
	};
	/*span.onclick = function() {
  modal.style.display = "none";
}*/
	window.onclick = function (event) {
		if (event.target == modal) {
			modal.style.display = "none";
		}
	};
}

function mirkoukrywaczRemoveHiddenElement(id) {
	wykopxStorageMirkoukrywacz
		.removeItem(id)
		.then(function () {
			$(`#wykopx_mirkoukrywacz_element_${id}`).remove();
		})
		.catch(function (err) {
			console.log(err);
		});
}

function consoleX(text, dev_mode = false) {
	let tpl = `background-color:black; border:1px solid rgba(244, 244, 244, 0.4); font-weight: bolder; padding: 0px 9px; font-family: "Segoe UI", "Open Sans", sans-serif; margin-right: 10px;`;
	if (dev_mode) tpl += `color:rgba(43, 255, 75, 1);`;
	else tpl += `color:rgba(255, 255, 255, 0.8);`;

	if (dev_mode == false || dev == true) console.log(`%cWykop X%c` + text, `${tpl}`, `font-family: "Segoe UI", "Open Sans"`);
}

let wykopxSettings = getComputedStyle(document.querySelector("body > section > aside.slots-info"));

/* Automatycznie "pokaż całość" długich treści */
function autoOpenMoreContentEverywhere() {
	if (wykopxSettings.getPropertyValue("--autoOpenMoreContentEverywhere")) {
		let numberOfShowMoreButtons = $("div.wrapper button.more").length;
		if (numberOfShowMoreButtons > 0) {
			$("div.wrapper button.more").click();
			consoleX(`Automatycznie rozwinięto ${numberOfShowMoreButtons} długich wpisów i komentarzy`);
		}
	}
}
/* Kliknięcie w logo wykopu odświeża stronę */
function refreshOrRedirectOnHomeButtonClick() {
	if (wykopxSettings.getPropertyValue("--refreshOrRedirectOnHomeButtonClick")) refreshOrRedirectOnButtonClick("header.header div.left > a", "/");
}
/* Kliknięcie w Mikroblog odświeża stronę */
function refreshOrRedirectOnMicroblogButtonClick() {
	if (wykopxSettings.getPropertyValue("--refreshOrRedirectOnMicroblogButtonClick")) refreshOrRedirectOnButtonClick(`nav.main ul li a[href="/mikroblog"]`, "/mikroblog");
}
function refreshOrRedirectOnButtonClick(selector, pathToRefresh = "/") {
	$(document).on("click", selector, function () {
		let pathname = new URL(document.URL).pathname;
		if (pathname == pathToRefresh) window.location.reload();
		else window.location.href = pathToRefresh;
	});
}

/* add micro button on left menu open, 2 versions
$(`header.header > div.left > button`).on("click", function(){
    //categoryRedirectToMicroblogButton();
}); */

// waitForKeyElements("aside.left-panel", categoryRedirectToMicroblogButton);

waitForKeyElements(`ul.categories`, categoryRedirectToMicroblogButton, false);
function test() {}

function categoryRedirectToMicroblogButton() {
	consoleX("categoryRedirectToMicroblogButton()", 1);
	$(`section.links div.content ul.categories li`).each(function (index) {
		if ($(this).children(".wykopx_categories_microblog_a").length == 0) {
			const kategoria = $(this).context.outerText;
			let href = "";
			switch (kategoria) {
				case "Ciekawostki":
					href = "/k/ciekawostki";
					break;
				case "Informacje":
					href = "/k/informacje";
					break;
				case "Rozrywka":
					href = "/k/rozrywka";
					break;
				case "Sport":
					href = "/k/sport";
					break;
				case "Motoryzacja":
					href = "/k/motoryzacja";
					break;
				case "Technologia":
					href = "/k/techologia";
					break;
				case "Ukraina":
					href = "/k/gospodarka";
					break;
				case "Podróże":
					href = "/k/podroze";
					break;
				default:
					null;
			}
			const microblogButtonHtml = `<a class="wykopxs wykopx_categories_microblog_a" href="${href}">M</a>`;
			$(this).append(microblogButtonHtml);
		}
	});
	$(`section.links div.content ul.buckets li`).each(function (index) {
		let href = $(this).children("a").attr("href");
		consoleX(href, 1);
		if (!href.endsWith("/mikroblog")) href += "/mikroblog";
		const microblogButtonHtml = `<a class="wykopxs wykopx_categories_microblog_a" href="${href}">M</a>`;
		$(this).append(microblogButtonHtml);
	});
}

/* środkowy przycisk na powiadomieniu otwiera je w nowej karcie */
$("body").on("mousedown", "section.notifications-stream section.notify", function (e1) {
	if (e1.which === 2) {
		$(this).one("mouseup", function (e2) {
			if (e1.target === e2.target) {
				let url_to_open = $(this).find(`a[href^="/wpis/"`).attr("href");
				let tab_handle = window.open(url_to_open, "_blank"); // tab_handle.blur();  //window.focus();
				var e3 = $.event.fix(e2);
				e3.type = "middleclick";
				$(e2.target).trigger(e3);
			}
		});
	}
});

/* środkowy przycisk na obrazku otwiera je w nowej karcie */
$("body").on("mousedown", "section.entry section.entry-photo", function (e1) {
	if (e1.which === 2) {
		$(this).one("mouseup", function (e2) {
			if (e1.target === e2.target) {
				let url_to_open = $(this).find(`a[href^="https://wykop.pl/cdn/"`).attr("href");
				var handle = window.open(url_to_open, "_blank");
				var e3 = $.event.fix(e2);
				e3.type = "middleclick";
				$(e2.target).trigger(e3);
			}
		});
	}
});

if (wykopxSettings.getPropertyValue("--allowToDownloadImage")) {
	waitForKeyElements("section.entry section.entry-photo figure", allowToDownloadImage, false);
	function allowToDownloadImage(jNode) {
		if (wykopxSettings.getPropertyValue("--allowToDownloadImage")) {
			let html = `<figcaption class="wykopxs wykopx_download_image_ico"><a title="Pobierz ten obrazek w pełnej rozdzielczości ${promoString}" href="${jNode.find("figcaption a").attr("href")}" download>Pobierz ten obrazek</a></figcaption>`;
			$(jNode).append(html);
		}
	}
}

const adjacentCode = `
  <style>
    /* wykop x promo ON */
    .wykopx_promo { width: 100%; display: block!important; height: 300px!important; background: url('https://raw.githubusercontent.com/wykopx/WykopX/main/promo-images/wykopx-install-sidebar-day.png'); }
    [data-night-mode] .wykopx_promo { background: url('https://raw.githubusercontent.com/wykopx/WykopX/main/promo-images/wykopx-install-sidebar-night.png'); }

    /* hide wykopxs features if wykopx is not installed */
    .wykopxs { display: none; }

    /* wykopxs-promo OFF */
    body div.main-content section > section.sidebar:after,
    section.editor.expand section.inline-autocomplete section.inline-autocomplete-stream div.content:after,
    header.header div.right section.search-input section.inline-autocomplete section.inline-autocomplete-stream div.content:after
    { display: none!important; }

    /* wykopxs new version available, mirkoukrywacz modal info bar */
    .wykopxs_info_bar { display: flex;   align-items: center;border-bottom: 1px solid rgba(128, 128, 128, 0.2); color: rgba(128, 128, 128, 1); padding: 8px 20px; font-size: 14px; }
    aside.wykopxs_info_bar a { display: inline-block;background: rgb(0,85,0);color: white;display: inline-block;background-color: #005200;padding: .3em 0.7em;margin: 0 10px;}
    aside.wykopxs_info_bar a:hover { background: rgba(0,85,0, 0.7); text-decoration: none!important; }
    aside.wykopxs_info_bar footer { opacity: 0.6; margin-left: auto; }
    @media (max-width: 640px)
    {
    body > section > aside.wykopxs_info_bar {  flex-direction: column; padding-top: 30px; }
    body > section > aside.wykopxs_info_bar a { margin: 11px; padding: 14px;  width: 100%; text-align: center;}
    body > section > aside.wykopxs_info_bar span.wykopxs_new_version_second,
    body > section > aside.wykopxs_info_bar > footer { display: none; }
    }


  </style>`;
document.head.insertAdjacentHTML("beforeend", adjacentCode);

/* checking for new versions */
if (!dev) console.clear();
consoleX("Sprawdzanie aktualizacji Wykop XS...");

$.get(`https://raw.githubusercontent.com/wykopx/WykopX/main/old-versions/wykopxs.${currentVersion}.gif`)
	.done(function () {
		addWykopXSNewVersionAvailableToast(); // new version available
		consoleX("Hej, jest nowa wersja skryptu Wykop XS. Wejdź na http://script.wykopx.pl i zaktualizuj go");
	})
	.fail(function () {
		consoleX("Masz najnowszą wersję skryptu Wykop XS v." + currentVersion);
	});

function hideWykopXSPromo() {
	$(`body div.main-content section > section.sidebar:after`).css("display: none!important;");
}

function addWykopXPromo() {
	let wykopxpromo = `<section class="wykopx_promo"></section>`;
	$(wykopxpromo).insertBefore(`section.sidebar > footer`);
}

function addWykopXSNewVersionAvailableToast() {
	let wykopxsnewversionavailabletoast = `<aside class="wykopxs_new_version wykopxs_info_bar"><span class="wykopxs_new_version_first">Dostępna jest nowa wersja skryptu Wykop XS.</span><a href="http://script.wykopx.pl" target="_blank" style="color: #fff!important;">Zaktualizuj Wykop XS</a><span class="wykopxs_new_version_second">do najnowszej wersji</span><footer>Twoja wersja Wykop XS to v.${currentVersion}</footer></aside>`;
	$(wykopxsnewversionavailabletoast).insertAfter(`header.header`);
}

function runWithDelay(f, time) {
	consoleX(`runWithDelay(f , ${time})`, 1);
	setTimeout(function () {
		f();
	}, time);
}

const unreadNotifications = {
	tags: 0,
	tags_new_entry_with_observed_tag: 0,
	tags_new_link_with_observed_tag: 0,
	entries: 0,
	pm: 0,
	total: 0,
};

function countNumberOfNotificationsOnDesktop() {
	$("header .right ul li.dropdown").removeClass("unread_5").removeClass("unread_4").removeClass("unread_3").removeClass("unread_2").removeClass("unread_1");

	$("header .right ul li.dropdown:has(a.new)").each(function (index, value) {
		const lastWord = $(this).attr("class").split(" ").pop();
		let numberOfNotifications = 0;
		// liczba powiadomień o tagach / wołaniach
		$(this)
			.find(".notify:not(.read)")
			.each(function (index, value) {
				++numberOfNotifications;
				$(this).addClass(`unread_${numberOfNotifications}`);

				if (lastWord == "tags") {
					unreadNotifications["tags"]++;
					if ($(this).find(`div.content p.new-entry-with-observed-tag`).length > 0) {
						unreadNotifications["tags_new_entry_with_observed_tag"]++;
					} else if ($(this).find(`div.content p.new-link-with-observed-tag`).length > 0) {
						unreadNotifications["tags_new_link_with_observed_tag"]++;
					}
				} else if (lastWord == "entries") {
					unreadNotifications["entries"]++;
				}
			})
			.parents(`.notifications.dropdown`)
			.addClass(`unread_${numberOfNotifications}`);
	});
	if (unreadNotifications["tags"] > 0) {
		consoleX(`Liczba nowych powiadomień z obserwowanych tagów: ${unreadNotifications["tags"]} (w tym ${unreadNotifications["tags_new_entry_with_observed_tag"]} z wpisów i ${unreadNotifications["tags_new_link_with_observed_tag"]} ze znalezisk)`);
	}
	if (unreadNotifications["entries"] > 0) {
		consoleX(`Liczba nowych zawołań: ${unreadNotifications["entries"]}`);
	}

	$("header .right ul li.pm.dropdown:has(a.new)").each(function (index, value) {
		let numberOfNotifications = 0; // liczba powiadomień o wiadomościach PM

		$(this)
			.find(".item.unread")
			.each(function (index, value) {
				++numberOfNotifications;
				++unreadNotifications["total"];
				$(this).addClass(`unread_${numberOfNotifications}`);
			})
			.parents(`.pm.dropdown`)
			.addClass(`unread_${numberOfNotifications}`);
		unreadNotifications["pm"] = numberOfNotifications;
		consoleX(`Liczba nowych wiadomości: ${unreadNotifications["pm"]}`);
	});

	if (unreadNotifications.tags > 0) {
		createNewProfileDropdownMenuItem(`Powiadomienia z #tagów: (${unreadNotifications.tags})`, "Masz nowe powiadomienia z obserwowanych #tagów", "wykopx_notifications_tags", undefined, "/powiadomienia/tagi", "_self", null, unreadNotifications.tags);
	}
	if (unreadNotifications.entries > 0) {
		createNewProfileDropdownMenuItem(`Zawołania w komentarzach: (${unreadNotifications.entries})`, "Zawołano Cię w komentarzu", "wykopx_notifications_entries", undefined, "/powiadomienia/moje", "_self", null, unreadNotifications.entries);
	}
	if (unreadNotifications.pm > 0) {
		createNewProfileDropdownMenuItem(`Nowe wiadomości: (${unreadNotifications.pm})`, "Masz nowe, nieprzeczytane wiadomości prywatne", "wykopx_notifications_pm", undefined, "/wiadomosci", "_self", null, unreadNotifications.entries);
	}
}

navigation.addEventListener("navigate", (event) => {
	consoleX(`navigation.addEventListener("navigate", (event) =>`, 1);
	categoryRedirectToMicroblogButton();
	runWithDelay(countNumberOfNotificationsOnDesktop, 1000);
	runWithDelay(autoOpenMoreContentEverywhere, 2000);
});

let user = null;
window.onload = function (event) {
	user = $("body > section > aside").data("user");
	consoleX(`Cześć ${user.username} (⌐ ͡■ ͜ʖ ͡■)`);

	runWithDelay(countNumberOfNotificationsOnDesktop, 1000);
	addNotificationSummaryButtonToNavBar();
	addWykopXButtonsToNavBar();

	createNewProfileDropdownMenuItem("Wykop X - Informacje", "Otwórz stronę Wiki z informacjami o dodatku Wykop X", "wykopx_wiki", undefined, "http://wiki.wykopx.pl/", "_blank", null, null);

	unrollDropdowns();
	focusOnAddingNewMicroblogEntry();
	addExtraButtons();
	addWykopXPromo();
	hideWykopXSPromo();
	// categoryRedirectToMicroblogButton();
	mirkoukrywaczBuildListOfHiddenElements();
	runWithDelay(autoOpenMoreContentEverywhere, 1000);
	refreshOrRedirectOnHomeButtonClick();
	refreshOrRedirectOnMicroblogButtonClick();
};

const promoString = "[Przycisk dodany przez Wykop X #wykopwnowymstylu]";

function addWykopXButtonsToNavBar() {
	let $clone = $(`body header nav ul li:not(.active):not(:has(a[href="/wykopalisko"])):first`).clone();
	let $cloneHits = $clone.clone();
	let $cloneMyWykop = $clone.clone();
	let $cloneAddNewEntry = $clone.clone();
	let $cloneAddNewLink = $clone.clone();
	let $cloneWykopWNowymStylu = $clone.clone();
	let $cloneInstallWykopX = $clone.clone();

	$cloneMyWykop
		.attr({class: "wykopxs wykopx_mywykop_li"})
		.find("a")
		.attr({href: "/obserwowane", class: "wykopxs wykopx_mywykop_button", title: `Mój Wykop ${promoString}`})
		.find("span")
		.text("Mój Wykop");
	$cloneHits
		.attr({class: "wykopxs wykopx_hits_li"})
		.css("display", "none")
		.find("a")
		.attr({href: "/hity", class: "wykopxs wykopx_hits_button", title: `Hity ${promoString}`})
		.find("span")
		.text("Hity");
	$cloneAddNewLink
		.attr({class: "wykopxs wykopx_add_new_link_li wykopx_plus_li"})
		.css("display", "none")
		.find("a")
		.attr({href: "/dodaj-link", class: "wykopxs wykopx_add_new_link wykopx_plus_button", title: `Dodaj nowe Znalezisko ${promoString}`})
		.find("span")
		.text("+");
	$cloneAddNewEntry
		.attr({class: "wykopxs wykopx_add_new_entry_li wykopx_plus_li"})
		.css("display", "none")
		.find("a")
		.attr({href: "/mikroblog/#dodaj", class: "wykopxs wykopx_add_new_entry wykopx_plus_button", title: `Dodaj nowy wpis na Mirko ${promoString}`})
		.find("span")
		.text("+");

	$cloneInstallWykopX
		.attr({class: "wykopx-promo wykopx_install_wykopx_li"})
		.find("a")
		.attr({
			href: "https://bit.ly/wykopx_install_wykopx_button",
			target: "_blank",
			class: "wykopx-promo wykopx_install_wykopx_button",
			title: `Zainstaluj style CSS "𝗪𝘆𝗸𝗼𝗽 𝗫" w rozszerzeniu Stylus i odkryj dziesiątki dodatkowych funkcji Wykopu. Masz już zainstalowane rozszerzenie `,
		})
		.find("span")
		.text("Zainstaluj Wykop X");

	$cloneHits.insertAfter(`body header nav.main ul li:has(a[href="/wykopalisko"])`);
	$cloneAddNewLink.insertAfter(`body header nav.main ul li:has(a[href="/wykopalisko"])`);
	$cloneAddNewEntry.insertAfter(`body header nav.main ul li:has(a[href="/mikroblog"])`);
	$cloneMyWykop.appendTo(`body header nav.main ul`);
	$cloneInstallWykopX.appendTo(`body header nav.main ul`);
}

function createNewProfileDropdownMenuItem(text, title, className, id = null, url = null, target = "_blank", icon = null, number = null) {
	$(`body header div.right nav ul li.account.dropdown ul.dropdown-body li.${className}_li`).remove();
	let $clonedDropdownItem = $(`body header div.right nav ul li.account.dropdown ul.dropdown-body li.settings`).clone();
	$clonedDropdownItem.attr({class: `${className}_li`});

	let $clonedDropdownItemLink = $clonedDropdownItem.find("a");
	$clonedDropdownItemLink.attr("href", url);
	$clonedDropdownItemLink.attr("target", target);
	$clonedDropdownItemLink.attr("class", className + "_button");
	$clonedDropdownItemLink.attr("id", id);
	$clonedDropdownItemLink.attr("title", title);
	$clonedDropdownItemLink.text(text);
	$clonedDropdownItem.appendTo(`body header div.right nav ul li.account.dropdown ul.dropdown-body`);
}

function addNotificationSummaryButtonToNavBar() {
	let mojeLubTagi = $("header .right ul li.account.dropdown ul.dropdown-body li.notifications.new a").attr("href");

	let wykopx_notification_summary_url = "/powiadomienia/";
	if (typeof mojeLubTagi == "string") {
		mojeLubTagi = mojeLubTagi.split("/").pop();
		if (mojeLubTagi == "tagi") {
			createNewProfileDropdownMenuItem(`Powiadomienia z #tagów`, "Masz nowe powiadomienia z obserwowanych #tagów", "wykopx_notifications_tags", undefined, "/powiadomienia/tagi", "_self", null, null);
		}
		if (mojeLubTagi == "moje") {
			createNewProfileDropdownMenuItem(`Powiadomienia z #tagów`, "Masz nowe powiadomienia z obserwowanych #tagów", "wykopx_notifications_tags", undefined, "/powiadomienia/tagi", "_self", null, null);
			createNewProfileDropdownMenuItem(`Zawołania w komentarzach`, "Zawołano Cię w komentarzu", "wykopx_notifications_entries", undefined, "/powiadomienia/moje", "_self", null, null);
		}
		wykopx_notification_summary_url += mojeLubTagi;
	}

	let wykopx_notification_summary = `<li class="wykopxs wykopx_notification_summary notifications dropdown" title="Nowe powiadomienia ${promoString}"><a href="${wykopx_notification_summary_url}"><figure></figure></a></li>`;
	$(wykopx_notification_summary).prependTo(`header.header > .right > nav > ul`);
}

function addExtraButtons() {
	let wykopx_mywykop_mobile_li = `<li class="wykopxs wykopx_mywykop_mobile_li"><a href="/obserwowane" class="wykopx_mywykop_mobile_button" title="Mój Wykop ${promoString}"><figure></figure></a></li>`;
	$(wykopx_mywykop_mobile_li).appendTo(`header.header > .right > nav > ul`);
	/* dolna belka mobilna */
	$(wykopx_mywykop_mobile_li).appendTo(`body section.default-layout nav.mobile-navbar > ul`);

	let wykopx_microblog_mobile_li = `<li class="wykopxs wykopx_microblog_mobile_li"><a href="/mikroblog" class="wykopx_microblog_mobile_button" title="Mikroblog ${promoString}"><figure> </figure></a></li>`;
	$(wykopx_microblog_mobile_li).appendTo(`header.header > .right > nav > ul`);

	let wykopx_wykopwnowymstylu_li = `<li class="wykopxs wykopx_wykopwnowymstylu_li"><a href="/tag/wykopwnowymstylu" class="wykopx_wykopwnowymstylu_button" title="Przejdź na #wykopwnowymstylu"><span>#</span></a></li>`;
	$(wykopx_wykopwnowymstylu_li).appendTo(`header.header > .right > nav > ul`);

	let wykopx_messages_mobile_li = `<li class="wykopxs wykopx_messages_mobile_li"><a href="/wiadomosci" class="wykopx wykopx_messages_button" title="Wiadomości ${promoString}"><figure></figure></a></li>`;
	/* dolna belka mobilna */
	$(wykopx_messages_mobile_li).appendTo(`body section.default-layout nav.mobile-navbar > ul`);

	if (user !== null) {
		let wykopx_profile_mobile_li = `<li class="wykopxs wykopx_profile_mobile_li ${user.username}"><a href="/ludzie/${user.username}" class="wykopx wykopx_profile_button" title="Przejdź na swój profil ${user.username} ${promoString}"><figure></figure></a></li>`;
		$(wykopx_profile_mobile_li).appendTo(`body section.default-layout nav.mobile-navbar > ul`);
	}
}

function focusOnAddingNewMicroblogEntry() {
	let wykop_url = new URL(document.URL);
	if (wykop_url.hash == "#dodaj") {
		document.querySelector(`section.microblog-page section.microblog section.editor div.content textarea`).focus();
	}
}

// waitForKeyElements("section.stream div.content section.entry div.comments section.entry-subcomments div.content section.reply", sortCommentsByID);
// document.removeEventListener('click', this.documentClick)

function unrollDropdowns(dropdown) {
	document.removeEventListener("click", this.documentClick);
}

/*
function sortCommentsByID(comment)
{
    let commentID = comment.attr ("id").substr(8, 9);
    console.log(commentID);
    comment.css("order", commentID);
}
*/

/* browarek programisto piekielny, przestań mi kurka kod prześladować! */

waitForKeyElements(".inline-autocomplete-stream", newAutoCompleteWindowAdded);

const tagsAutocompleteURL = "https://wykop.pl/api/v3/tags/";
const profilesAutocompleteURL = "https://wykop.pl/api/v3/profile/users/";

function newAutoCompleteWindowAdded(element) {
	let suggestions = element[0].getElementsByTagName("span");
	if (typeof this.lastFingerPrint == "undefined" || this.lastCount != suggestions.length || this.lastFingerPrint != getTagsFingerPrint(suggestions)) {
		for (let i = 0; i < suggestions.length; i++) {
			let suggestion = suggestions[i];
			getObserveCount(suggestion);
		}
	}
	this.lastFingerPrint = getTagsFingerPrint(suggestions);
	this.lastCount = suggestions.length;
	return true;
}

function getTagsFingerPrint(suggestions) {
	let fingerPrint = "";
	for (let i = 0; i < suggestions.length; i++) {
		let suggestion = suggestions[i];
		fingerPrint += suggestion.innerText.substring(1).split(" ")[0];
	}
	return fingerPrint;
}

function getObserveCount(element) {
	var type = element.innerText.substring(0, 1);
	var query = element.innerText.substring(1);
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function () {
		if (this.readyState == 4 && this.status == 200) {
			var details = JSON.parse(this.responseText);
			addCount(type, element, details.data);
		}
	};
	xmlhttp.open("GET", (type === "@" ? profilesAutocompleteURL : tagsAutocompleteURL) + query);
	xmlhttp.setRequestHeader("Authorization", "Bearer " + window.localStorage.token);
	xmlhttp.send();
}

function addCount(prefix, element, data) {
	const name = prefix === "@" ? data.username : data.name;
	const followers = prefix === "@" ? data.summary.followers : data.followers;
	if (prefix != "@") {
		$(element)
			.parent()
			.attr({style: `order: ${followers}`, "data-followers": `${followers}`}).html(`<div class="wykopxs wykopx_autocomplete_element wykopx_autocomplete_tag">
                        <div class="wykopx_autocomplete_prefix">${prefix}</div>
                        <div class="wykopx_autocomplete_name">${name}</div>
                        <div class="wykopx_followers_counter">${followers}</div>
                        <meter class="wykopx_followers_meter" min="0" max="1000" low="99" high="500" optimum="999"  value="${followers}"></meter>`);
	}
}