ImThatGuy / FastStickers

// ==UserScript==
// @name         FastStickers
// @author       ImThatGuy
// @description  Ajoutez vos stickers préférés très rapidement ! (plugin pour JVCpremium)
// @include      http://www.jeuxvideo.com/*
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require      https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js
// @require      https://jvcpremium.000webhostapp.com/files/remodal.min.js
// @require      https://raw.githubusercontent.com/avxto/nuContextMenu/master/src/jquery.nu-context-menu.js
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @version      0.7
// @icon         https://i.imgur.com/LgIKzNa.png
// @copyright    2018+, ImThatGuy
// @license      MIT
// ==/UserScript==

/*
FastStickers. 2017-2018.
Codé par ImThatGuy.

2018+, ImThatGuy.

Plugin pour JVCpremium : https://openuserjs.org/scripts/ImThatGuy/JVCpremium

FastStickers vous permet d'ajouter les stickers de JVCpremium très rapidement.
Plus besoin d'ouvrir le menu principal de JVCpremium.

Nouveauté : Utilise l'api risibank pour chercher un sticker très rapidement
0.4 : Mise à jour de la recherche via API risibank
0.5 : Mise à jour pour la 2.7 de JVCpremium, changement des logos
21/09/17 : Correction bug api risibank
0.6 : Correction input mozilla firefox
0.7 : Amélioration design scrollbar
      Compatible (design) avec DarkJVC
	  Ajout d'un panneau de configuration dans la partie plugins de JVCpremium
	  permettant de personnaliser la hauteur du cadre à stickers
*/

/*jshint multistr: true */
(function() {
    'use strict';

	const version = '0.7';
	// CSS IMPORT
	// Modal
    $('head').append('<link rel="stylesheet" type="text/css" href="https://jvcpremium.000webhostapp.com/files/remodal.css"/>');
    $('head').append('<link rel="stylesheet" type="text/css" href="https://jvcpremium.000webhostapp.com/files/remodal-default-theme.css"/>');
	// Icons
	$('head').append('<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>');
	// Context menu
	$('head').append('<link rel="stylesheet" type="text/css" href="https://jvcpremium.000webhostapp.com/files/nu-context-menu.css"/>');

	var icons = {
		risitas: 'http://i.imgur.com/f4sMH3D.png',
		autres: 'http://i.imgur.com/XCRBUCP.png',
		personnels: 'http://i.imgur.com/HJZCsJq.png'
	};

	var focus = $('#risi');
	var stickersRisibank = [];

	function addSticker(sticker) {
        var $textarea = $("#message_topic");
        var caretPos = $textarea[0].selectionStart;
        var textAreaTxt = $textarea.val();

		var txtToAdd = sticker + ' ';

        $textarea.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
        $textarea.focus();
    }

	function logConsole(text) {
		$('#consolePremium').append('<p style="margin:10px;">'+text+'</p>');
	}

	// Dark JVC check
	function darkJVC() {
		if ( $("body").css("background-color") == "rgb(18, 18, 18)" ) {
			return true;
		} else {
			return false;
		}
	}

	setTimeout(function() {
		var JVCpremiumPlugin;
		if (document.getElementById("PREMIUM") !== null) {
			JVCpremiumPlugin  = true;
		} else {
			JVCpremiumPlugin  = false;
		}

		if (JVCpremiumPlugin) {
			// Get height value
			var heightValue = GM_getValue("heightValue");
			if (!heightValue) {
				heightValue = "80"; // Par defaut
			}


			logConsole('[INFO] Plugin FastStickers '+version+' chargé.');
			// Appends à JVCpremium
			$('#plugin').append('<img width=70 height=70 src="https://image.noelshack.com/fichiers/2017/06/1486728381-faststickers.png">\
<h5>Vous utilisez FastStickers version '+version+'.</h5>\
<h5>Configuration</h5>\
<label for="heightValue">Hauteur du cadre à stickers (en pixels)</label> <input type="text" value="'+heightValue+'" placeholder="Valeur en pixels" id="heightValue" style="width:67px;padding: 1px 2px;margin: 2px 0;box-sizing: border-box"> \
<a class="btn btn-default" id="validheight" style="font-size:11px; padding: 3px 6px; border-radius: 0;">Valider</a>\
<hr>');

			$('#tabs-1').append("<p><b>Vous utilisez FastStickers ("+version+").</b> Les packs de stickers s'ajouteront ici.</p>");
			$('i').each(function() {
				if (this.innerHTML == 'Clic droit sur un sticker pour accéder au menu') {
					this.remove();
				}
			});
			$('#fsinstall').remove();
			$('#non-installer').remove();
			$('#risibank').remove();
			$('#risibankBtn').remove();
			// Move stickers box
			$('.jv-editor-toolbar').append('<div style="padding:5px;">\
<img hspace="6" class="iconStickers" title="Stickers risitas" height=16 width=16 src="'+icons.risitas+'">\
<img hspace="6" class="iconStickers" title="Stickers autres" height=16 width=16 src="'+icons.autres+'">\
<img hspace="6" class="iconStickers" title="Stickers personnels" height=16 width=16 src="'+icons.personnels+'">\
<input type="text" id="risibank" placeholder="Rechercher dans risibank...">\
</div>');
			// Css input risibank
			GM_addStyle('#risibank { background-image:url(http://www.freeiconspng.com/uploads/search-icon-png-18.png);\
                        outline: none;\
						background-repeat:no-repeat;background-size: 15px 15px;\
						background-position:165px center;\
                        background-color:#F3F3F5;\
                        color:gray;font-size:12px;font-family:Arial,sans-serif;\
						height:25px;\
                        width:185px;\
						border: 1px solid #ccc;\
						border-radius:2px;\
						padding-right:19px;\
						padding-left:5px;\
						box-sizing: border-box;\
						float:right }');

			// AppendTo
			$('#risi').appendTo('.jv-editor-toolbar');
			$('#autres-st').appendTo('.jv-editor-toolbar');
			$('#stPerso').appendTo('.jv-editor-toolbar');
			// CSS
			var cssOptions;
			// CSS DarkJVC 0.7
			if (darkJVC()) {
				cssOptions = {
					'border-radius': '3px',
					'height': heightValue, // 80px par defaut
					'margin-top': '7px',
					'margin-bottom': '3px',
					'background-color': '#3b3b3b',
					'border-color': '#222',
				};
			} else {
				cssOptions = {
					'border-radius': '3px',
					'height': heightValue, // 80px par defaut
					'margin-top': '7px',
					'margin-bottom': '3px',
					'background-color': 'white',
				};
			}
			// Applique le CSS
			$('#risi').css(cssOptions);
			$('#autres-st').css(cssOptions);
			$('#stPerso').css(cssOptions);
			// CSS pour la conf
			//GM_addStyle("#heightValue { padding-right: 5px; padding-left: 5px; border: 1px solid #ccc; outline: none; }");
			// Hide
			$('#autres-st').hide();
			$('#stPerso').hide();
			// iconStickers
			//$('.iconStickers').tooltip();
			GM_addStyle('.iconStickers { opacity:0.7; margin-bottom: -5px;}');
			GM_addStyle('.iconStickers:hover { opacity:1; cursor:pointer }');
			// Listeners
			$('.iconStickers').click(function() {
				if (this.title == 'Stickers risitas') {
					$('#risi').show();
					$('#autres-st').hide();
					$('#stPerso').hide();
					focus = $('#risi');
				} else if (this.title == 'Stickers autres') {
					$('#autres-st').show();
					$('#stPerso').hide();
					$('#risi').hide();
					focus = $('#autres-st');
				} else {
					$('#stPerso').show();
					$('#risi').hide();
					$('#autres-st').hide();
					focus = $('#stPerso');
				}
			});
			// Valid height
			$("#validheight").click(function() {
				GM_setValue("heightValue", $("#heightValue").val());
				location.reload();
			});
			// risibank search
			$('#risibank').focus(function() {
				$(focus).children().hide();
			});

			$('#risibank').focusout(function() {
				if (!this.value) {
					$(focus).children().show();
					$('.sticker-risibank').remove();
				}
			});

			$('#risibank').on("keyup", function() {
				/*
				if (this.value) {
					var win = window.open('http://risibank.fr/#'+this.value, '_blank');
					win.focus();
				}
				*/
				if (this.value) {
					GM_xmlhttpRequest({
						method: "POST",
						url: "https://api.risibank.fr/api/v0/search",
						data: "search=" + this.value,
						headers: {
							"Content-Type": "application/x-www-form-urlencoded"
						}, onload: function (response) {
							stickersRisibank = [];
							$(focus).children().hide();
							//console.log(response.responseText);
							var r = JSON.parse(response.responseText);
							logConsole("[FastStickers] Risibank recherche : " + r.stickers.length + " stickers trouvés pour « "+ $('#risibank').attr('value') +" ».");

							if ( r.stickers.length === 0 ) {
								//$('#risi').append('Aucun résulat pour <i>'+$('#risibank').attr('value')+'.</i>');
							} else {
								for (var i=0; i<r.stickers.length; i++)
								{
									$(focus).append('<img code="'+i+'" title="Sticker de '+r.stickers[i].pseudo+'" class="sticker-risibank" style="opacity:0.7;max-height:56px;max-width:56px" src="http://image.noelshack.com/fichiers/' + r.stickers[i].link+'">');
									stickersRisibank.push({
										id: r.stickers[i].id,
										link: r.stickers[i].link,
										tags: r.stickers[i].tags,
										pseudo: r.stickers[i].pseudo
									});
								}
								$('.sticker-risibank').tooltip();
								// listener
								$( ".sticker-risibank" ).click(function() {
									addSticker( $(this).attr('src') );
								});

								var context = $('body').nuContextMenu({

									hideAfterClick: true,

									items: '.sticker-risibank',

									callback: function(key, element) {
										if ( key == 'download' ) {
											var a = document.createElement('a');
											a.href = element.src;
											a.download = element.src;
											a.style.display = 'none';
											document.body.appendChild(a);
											a.click();
										} else if ( key == 'infos' ) {
											var j = $(element).attr('code');
											$('[data-remodal-id=infoSticker]').remove();
											$('body').append('<div style="text-align:left;max-width:100% !important;width:70%" class="remodal" data-remodal-id="infoSticker">\
<button data-remodal-action="close" class="remodal-close"></button>\
<h2>Informations sur le sticker <img style="max-height:100px;max-width:100px" src="http://image.noelshack.com/fichiers/'+stickersRisibank[j].link+'"></h2><hr>\
<p><b>ID :</b> '+stickersRisibank[j].id+'</p>\
<p><b>Lien :</b> <a href="http://image.noelshack.com/fichiers/'+stickersRisibank[j].link+'">http://image.noelshack.com/fichiers/'+stickersRisibank[j].link+'</a></p>\
<p><b>Tags :</b> '+stickersRisibank[j].tags+'</p>\
<p><b>Auteur :</b> '+stickersRisibank[j].pseudo+'</p>\
</div>');
											var infoSticker = $('[data-remodal-id=infoSticker]').remodal();
											infoSticker.open();
										} else {
											addSticker($(element).attr('src'));
										}
									},

									menu: [

										{
											name: 'download',
											title: 'Télécharger ce sticker',
											icon: 'download',
										},

										{
											name: 'reply',
											title: 'Ajouter à mon post',
											icon: 'reply',
										},

										{
											name: 'void'
										},

										{
											name: 'infos',
											title: 'Informations',
											icon: 'info',
										},
									]

								});
							}
						}
					});
				}
			});

			// Sticker risibank css
			GM_addStyle('.sticker-risibank:hover {opacity:1!important;transition:opacity 0.4s!important;cursor:pointer!important;}');
			// Scroll bar 0.7
			if (!$.browser.mozilla) {
				GM_addStyle("#risi::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 3px rgba(0,0,0,0.2); background-color: #f7f7f7; }\
#risi::-webkit-scrollbar { width: 9px; background-color: #F5F5F5; }\
#risi::-webkit-scrollbar-thumb { background-color: #ccc; }\
#risi::-webkit-scrollbar-thumb:hover { background-color: #bbb; }\
#risi::-webkit-scrollbar-thumb:active { background-color: #aaa; }");
			}

		} else {
			console.log("Vous devez installer JVCpremium pour que FastStickers puisse fonctionner correctement.");
		}
	}, 1000);

})();