CrazyJeux / Renickname

// ==UserScript==
// @name        Renickname
// @namespace   CrazyJeux/Daring-Do
// @author		CrazyJeux/Daring-Do
// @match		*://www.jeuxvideo.com/*
// @match		*://*.jvforum.fr/*
// @description Permet de surnommer les forumeurs que l'on veut en utilisant le menu contextuel (clic droit sur un pseudo).
// @version		10
// @resource	jQueryJS    https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js
// @grant       GM_getResourceText
// @grant		unsafeWindow
// ==/UserScript==

function unique() {
	function renicknameScript() {	
		function getAuthors() {
			return $(".bloc-pseudo-msg, .topic-author, " //JVC
			+ ".message__byline-author-pseudo, .topic__author"); //JVForum
		}
			
		function onContextMenu() {
			$authors.filter(function() {
				return !$(this).is("[data-contextmenu-is-done-for-renickname]");
			}).on("contextmenu", function (event) {
				if (event.ctrlKey || event.shiftKey || event.altKey) {
					return true;
				}
				event.preventDefault();
				
				var realNickname = $(this).attr("data-real-nickname");
				$realNickname.html("Vrai pseudo : " + realNickname).attr("data-real-nickname", realNickname);
				
				var resultArray = nicknames.filter(function(el) {
					return el.author.toLowerCase() === realNickname.toLowerCase();
				});
				if (resultArray.length === 1) {
					$changeNickname.text("Changer le surnom");
					$removeNickname.show();
				} else {
					$changeNickname.text("Ajouter un surnom");
					$removeNickname.hide();
				}
				
				if (nicknames.length > 0) {
					$removeAllNicknames.text("Supprimer tous les surnoms ("+nicknames.length+" surnom"+((nicknames.length>1) ? "s" : "")+" au total)").show();
					$showAllNicknames.show();
				} else {
					$removeAllNicknames.hide();
					$showAllNicknames.hide();
				}
				
				$customMenu.finish().toggle(100).
					//At the mouse position
					css({
						top: event.pageY + "px",
						left: event.pageX + "px"
					});
			}).attr("data-contextmenu-is-done-for-renickname", "true");
		}
		
		function updateNicknames(update) {
			//console.log("update="+update);
			if (typeof update !== "undefined" && update === true) {
				$authors = getAuthors();
				onContextMenu();
			}
			
			$authors.each(function() {
				if ($(this).is("[data-real-nickname]")) {
					$(this).text($(this).attr("data-real-nickname"));
				}
				$(this).removeAttr("title");
				
				var realNickname = $(this).text().trim();
				if (!$(this).is("[data-real-nickname]")) {
					$(this).attr("data-real-nickname", realNickname);
				}
				var resultArray = nicknames.filter(function(el) {
					return el.author.toLowerCase() === realNickname.toLowerCase();
				});
				if (resultArray.length === 1) {
					$(this).text(resultArray[0].nickname);
					$(this).attr("title", "Vrai pseudo : " + realNickname);
				}
			});
		}
		
		var $authors = getAuthors();
		//console.log("$authors.length: "+$authors.length);
		if ($authors.length === 0) {
			return;
		}
		
		var nicknames = localStorage.getItem("script-renickname-nicknamesarray");
		if (nicknames === "" || nicknames === null) {
			nicknames = [];
		} else {
			nicknames = JSON.parse(nicknames);
		}
		
		if (!$("body").is("[data-eventlisteners-for-renickname]")) {
			//console.log("init only called once");
			$("body").attr("data-eventlisteners-for-renickname", "true");

			var style = document.createElement("style");
			style.type = "text/css";
			style.setAttribute("data-script-renickname", "true");
			style.innerHTML = "#custom-menu {" +
                    "display: none;" +
				    "z-index: 1000;" +
				    "position: absolute;" +
				    "overflow: hidden;" +
				    "border: 1px solid #CCC;" +
				    "white-space: nowrap;" +
				    "font-family: sans-serif;" +
				    "background: #FFF;" +
				    "color: #333;" +
				    "border-radius: 5px;" +
                    "list-style-type: none;" +
                    "-webkit-padding-start: 10px;" +
                "}" +

				"#custom-menu li {" +
					"padding-right: 0px;" +
					"margin-right: 10px;" +
					"margin-bottom: 2px;" +
				"}" +

				"#custom-menu li:not(#realNickname) {" +
					"cursor: pointer;" +
				"}" +

				"#custom-menu li:not(#realNickname):hover {" +
					"background-color: #DEF;" +
				"}";
			document.head.appendChild(style);

			$("body").get(0).appendChild($('<ul id="custom-menu">' +
						'<li id="realNickname"></li>' +
						'<li id="changeNickname"></li>' +
						'<li id="removeNickname">Supprimer le surnom</li>' +
						'<li id="removeAllNicknames"></li>' +
						'<li id="showAllNicknames">Afficher tous les surnoms</li>' +
				'</ul>').get(0));

			var $customMenu = $("#custom-menu");
			var $realNickname = $customMenu.find("#realNickname");
			var $changeNickname = $customMenu.find("#changeNickname");
			var $removeNickname = $customMenu.find("#removeNickname");
			var $removeAllNicknames = $customMenu.find("#removeAllNicknames");
			var $showAllNicknames = $customMenu.find("#showAllNicknames");

			onContextMenu();

			$(document).on("mousedown", function (e) {
				if (!$(e.target).parents("#custom-menu").length > 0) {
					$customMenu.hide(100);
				}
			});

			$customMenu.find("li:not(#realNickname)").click(function(){
				switch (this) {
					case $changeNickname.get(0):
						var realNickname = $realNickname.attr("data-real-nickname");
						var index = null;
						var element = null;
						nicknames.filter(function(el, i) {
							var isEq = (el.author.toLowerCase() === realNickname.toLowerCase());
							if (isEq) {
								index = i;
							}
							return isEq;
						});
						var isNew = false;
						if (index !== null) {
							element = nicknames[index];
						} else {
							nicknames.push({
								author: realNickname
							});
							element = nicknames[nicknames.length - 1];
							isNew = true;
						}
						var newNickname = window.prompt("Nouveau surnom pour " + realNickname + " ?");
						if (newNickname === null) {
							if (isNew === true) {
								nicknames.pop();
							}
							break;
						}
						while (newNickname.trim() === "") {
							newNickname = window.prompt("Merci d'entrer au moins un caractère qui ne soit pas un espace.\n\nNouveau surnom pour " + realNickname + " ?");
							if (newNickname === null) {
								break;
							}
						}
						if (newNickname === null) {
							if (isNew === true) {
								nicknames.pop();
							}
							break;
						}
						element.nickname = newNickname;
						localStorage.setItem("script-renickname-nicknamesarray", JSON.stringify(nicknames));
						updateNicknames();
						break;
					case $removeNickname.get(0):
						var realNickname = $realNickname.attr("data-real-nickname");
						var index = null;
						nicknames.filter(function(el, i) {
							var isEq = (el.author.toLowerCase() === realNickname.toLowerCase());
							if (isEq) {
								index = i;
							}
							return isEq;
						});
						if (index !== null) {
							nicknames.splice(index, 1);
							localStorage.setItem("script-renickname-nicknamesarray", JSON.stringify(nicknames));
							updateNicknames();
						}
						break;
					case $removeAllNicknames.get(0):
						var r = confirm("Êtes-vous vraiment sûr de vouloir supprimer tous les surnoms de tous les pseudos ?");
						if (r === true) {
							nicknames = [];
							localStorage.setItem("script-renickname-nicknamesarray", JSON.stringify(nicknames));
							updateNicknames();
						}
						break;
					case $showAllNicknames.get(0):
						var s = "";
						for (var i=0; i<nicknames.length; i++) {
							s += 'Le surnom de ' + nicknames[i].author + ' est : "' + nicknames[i].nickname + '"';
							if (i !== nicknames.length - 1) {
								s += "\n";
							}
						}
						$customMenu.hide();
						alert(s);
						return;
					default:
						alert("Erreur dans le script Nicknames : l'auteur de ce script a oublié un cas à gérer dans le switch.");
				}

				$customMenu.hide(100);
			});

			//TopicLive
			addEventListener('topiclive:newmessage', function() {
				setTimeout(function() {
					//console.log("new message in topiclive");
					updateNicknames(true);
				}, 10);
			});
		}
		
		updateNicknames();

		if (window.location.hostname.indexOf("jvforum.fr")>=0 && !$("body").is("[data-setinterval-for-renickname]")) {
			$("body").attr("data-setinterval-for-renickname", "true");
			//var prevLength = $(".message").length;
			//console.log("setting setinterval for jvforum...");
			setInterval(function() {
				//console.log("in setInterval 0");
				//if ($(".message").length !== prevLength) {
					//console.log("new message (jvforum)");
					//prevLength = $(".message").length;
					updateNicknames(true);
				//}
				//console.log("in setInterval 1");
			}, 1000);
		}
	}

	function callMe() {
		/*var prevScript = document.querySelector("script[data-script-renickname]");
		if (prevScript !== null) {
			prevScript.remove();
		}*/
        
        if (called == true)
        {
            return;
        }
        
        called = true;

		var script = document.createElement("script");
		script.type = "text/javascript";
		script.setAttribute("data-script-renickname", "true");
		script.innerHTML = "(function(){ " + renicknameScript.toString() + " renicknameScript();})();";
		document.body.appendChild(script);
	}

    if (typeof unsafeWindow.jQuery === "undefined") {
        var jQueryEl = document.createElement("script");
        jQueryEl.type = "text/javascript";
        var content = GM_getResourceText("jQueryJS");
        jQueryEl.innerHTML = content;
        jQueryEl.setAttribute("data-info", "jQueryJS");
        document.head.appendChild(jQueryEl);
    }

	callMe();

	//Respeed
	//addEventListener('instantclick:newpage', callMe);

	if (typeof InstantClick !== "undefined") {
		InstantClick.on('change', function() {
			//console.log("new page in jvforum");
			callMe();
		});
	}
}

called = false;

unique();

/*document.addEventListener('DOMContentLoaded', unique, false);
window.addEventListener('load', unique, false);
window.onload = unique;*/