Newt300 / shiki UI extender

// ==UserScript==
// @name         shiki UI extender
// @namespace    https://vk.com/shiki_ex
// @updateURL    https://openuserjs.org/meta/Newt300/shiki_UI_extender.meta.js
// @downloadURL  https://openuserjs.org/install/Newt300/shiki_UI_extender.user.js
// @version      1.1.5
// @description  [shikimori.org] ### Этот скрипт входит в пакет скриптов shiki extender (by STorn) ###
// @author       STorn
// @match        https://shikimori.org/*
// @match        http://shikimori.org/*
// @match        https://shikimori.one/*
// @match        http://shikimori.one/*
// @match        https://play.shikimori.org/*
// @match        http://play.shikimori.org/*
// @license      MIT
// @grant        none
// ==/UserScript==

/*jshint multistr: true */

//Code Conventions?? Не, не слышал!

var kGlobal = 0;

function start() {
    if ((window.location.pathname.indexOf("animes") > 0) || (window.location.pathname.indexOf("ranobe") > 0) || (window.location.pathname.indexOf("mangas") > 0)) {
        if(($(".friend-rate").length > 0) && ($("#friendRateAVG").length === 0)) {
            if ($(".anons").length > 0) return;
        	friendRateAVG();
        }
        if(($("#shikiRatingDup").length === 0)) {
        	shikiRatingDup();
        }
    }
    if (window.location.pathname.indexOf("/list/anime") > 0 | window.location.pathname.indexOf("/list/manga/") > 0) {
    	if (($("#userlistRateAVG").length === 0)) {
           userlistRateAVG();
        }
    }

    if (($(".mfp-bg.mfp-ready").length > 0)) {
    	if ($("#modalWindow").length > 0 & ($("iframe.mfp-iframe").length > 1)) $("#modalWindow").remove();
        if ($(document).width() < 935) return;
    	if ($(".mfp-close").length > 2) return;

		var el = document.createElement("button");
    	el.setAttribute("title", "Свернуть");
		el.setAttribute("type", "button");
		el.setAttribute("class", "mfp-close");
		el.setAttribute("style", "margin: -1px 30px 0px 0");
    	el.innerText = "-";
    	$(".mfp-iframe-scaler").append(el);
    	el.onclick = function () {moduleWindow(); };
    }

    document.querySelectorAll('a[href^="//shikimori.org/animes/kind/"][href*="="]').forEach(function(e){e.href=e.getAttribute('href').replace(/^(\/\/shikimori.org\/animes)\/kind\/(.+?)=(.+?)$/,'$1/$2/$3');});
}

function moduleWindow() {
	var closeBtn = document.querySelectorAll(".mfp-close")[0];

	var div = document.createElement("div");
	div.class = "tooltip";
	var t;
	if (document.querySelectorAll("aside.l-menu").length > 0) {
		t = document.querySelectorAll("aside.l-menu")[0].getBoundingClientRect().left;
	} else {
		t = document.querySelectorAll(".b-main_search")[0].getBoundingClientRect().left - 100;
	}

	div.setAttribute("style", "width: 321px; z-index: 20; display: ; position: fixed; top: 70%; left: " + t + "px;");
	div.id = "modalWindow";
	div.innerHTML = '<div class="tooltip-inner" style="width: 321px"><a onclick=\'$("#modalWindow").remove();\' id="closeBtn" title="закрыть" align="right" class="b-link bubbled-processed">закрыть </a><br><br></div>';
	document.querySelectorAll("body")[0].append(div);
	$("#modalWindow > div")[0].append($(".mfp-iframe")[0]);


	document.querySelectorAll("#topics_show > div.mfp-wrap.mfp-close-btn-in.mfp-auto-cursor.mfp-ready")[0].style.display = "none";
	document.querySelectorAll(".mfp-bg.mfp-ready")[0].remove();
	document.querySelectorAll("html")[0].style = "none";

	$("#closeBtn")[0].onclick = function () {
		$("#modalWindow").remove();
		closeBtn.click();
	};

	//Реализую передвижение окна

	div.onmousedown = function(e){
    	var coords = getCoords(div);
  		var shiftX = e.clientX - coords.left;
 		var shiftY = e.clientY - coords.top;

 		moveAt(e);


 		function moveAt(e) {
  			div.style.left =  e.clientX - shiftX + 'px';
    		div.style.top = e.clientY - shiftY + 'px';
  		}

  		document.ondragstart = function() {
  			return false;
		};

  		document.onmousemove = function(e) {
   			moveAt(e);
  		};

  		document.onselectstart = function() {
  			return false;
		};

  		div.onmouseup = function() {
    		document.onmousemove = null;
    		div.onmouseup = null;
    		document.ondragstart = null;
    		document.onselectstart = null;
  		};

	};

	div.ondragstart = function() {
  		return false;
	};

}

function getCoords(elem) {   // кроме IE8-
  var box = elem.getBoundingClientRect();
  return {
    top: box.top,
    left: box.left
  };
}

function friendRateAVG() {
	console.log('######################################################\n[UI ex]: Module "friendRateAVG" successfully activated.\n######################################################');
	var friendRate = document.querySelectorAll("div[class*=friend-rate] div[class=status]");
    var friendRateStatus = [];
    var sum = 0;
    var avg = 0;
    var count = 0;
	for (var i = friendRate.length - 1; i >= 0; i--) {
		friendRateStatus[i] = friendRate[i].innerText.replace(/[^-0-9]/gim,'');
        if (friendRateStatus[i] !== "") {
        	sum += Number(friendRateStatus[i]);
        	count++;
        }
	}
	avg = sum / count;

    //Вставляем элемент
	var insertAVG = document.createElement("div");
	insertAVG.setAttribute("class", "b-options-floated collapse");
	insertAVG.setAttribute("id", "friendRateAVG");
	insertAVG.setAttribute("align", "right");
	insertAVG.setAttribute("style", "margin: 6px 0px 0px 0");
	insertAVG.innerHTML = '<h1>avg: ' + avg.toFixed(2) + '</h1>';
	var avgNextChild = document.querySelectorAll("div[class=b-animes-menu] div[class=block]")[2];
    avgNextChild.prepend(insertAVG);
}

function shikiRatingDup() {
	console.log('######################################################\n[UI ex]: Module "shikiRatingDup" successfully activated.\n######################################################');
    var scoreData = jQuery.parseJSON($("#rates_scores_stats").attr("data-stats"));
    var sumScore = 0;
    var totalCount = 0;
    for (var i = 0; i < scoreData.length; i++) {
            sumScore += scoreData[i].value * scoreData[i].name;
            totalCount += scoreData[i].value;
    }
    var avg = sumScore / totalCount;

	//Вставляем элемент
	var insertAVG = document.createElement("div");
	insertAVG.setAttribute("class", "b-options-floated collapse");
	insertAVG.setAttribute("id", "shikiRatingDup");
	insertAVG.setAttribute("align", "right");
	insertAVG.setAttribute("style", "margin: 6px 0px 0px 0");
	insertAVG.setAttribute("title", "Средняя оценка пользователей шикимори");
	insertAVG.innerHTML = '<h1>avg: ' + avg.toFixed(2) + '</h1>';
	var avgNextChild = document.querySelectorAll("div.b-animes-menu div.block")[0];
    avgNextChild.prepend(insertAVG);
}

function userlistRateAVG() {
	console.log('######################################################\n[UI ex]: Module "userlistRateAVG" successfully activated.\n######################################################');
    var scoreData = jQuery.parseJSON($("#scores").attr("data-stats"));
    var sumScore = 0;
    var totalCount = 0;
    for (var i = 0; i < scoreData.length; i++) {
            sumScore += scoreData[i].value * scoreData[i].name;
            totalCount += scoreData[i].value;
    }
    var avg = sumScore / totalCount;

    //Вставляем элемент
	var insertAVG = document.createElement("div");
	insertAVG.setAttribute("class", "b-options-floated collapse");
	insertAVG.setAttribute("id", "userlistRateAVG");
	insertAVG.setAttribute("align", "right");
	insertAVG.setAttribute("style", "margin: 6px 0px 0px 0");
	insertAVG.innerHTML = '<h1>avg: ' + avg.toFixed(2) + '</h1>';
	var avgNextChild = document.querySelectorAll("div.block.mini-charts div.scores.block")[0];
    avgNextChild.prepend(insertAVG);
}

$(document).bind('mouseup mousemove ready', function(){
    start();
});
(function loops(){
   setTimeout(function(){
       start();
       loops(); // рекурсия
   }, 2000);
})();
$(document).ready(start());
$(document).ready(function(){kGlobal = 0; start();});
$(document).on('page:load', function(){kGlobal = 0; start();});
$(document).on('turbolinks:load', function(){kGlobal = 0; start();});