Mudada_ / JVC - Recherche Topic

// ==UserScript==
// @name         JVC - Recherche Topic
// @version      1.1.0
// @description  Permet de faire des recherches sur un topic
// @author       Mudada_
// @match        http://www.jeuxvideo.com/forums/*
// @require      https://code.jquery.com/jquery-1.12.4.js
// @require      http://code.jquery.com/ui/1.12.1/jquery-ui.js
// @license      MIT
// ==/UserScript==
(function() {
    "use strict";

    // Ajout du css de jQuery UI
    $("head").append ('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/dark-hive/jquery-ui.min.css" rel="stylesheet" type="text/css">');

    var stop = false, nbMatch;

    // Si on est sur un topic
    if($(".conteneur-messages-pagi").length){
        // On ajoute un bouton de recherche en haut et en bas de la page
        $(".bloc-pre-right").prepend($("<span/>", {
            text: "Rechercher",
            class: "btn btn-actu-new-list-forum",
            style: "float: left; margin-right: 5px",
            click: function() {
                ShowSearchForm(undefined, "Message");
            }
        }));

        // Sur chaque message on ajoute un bouton racourcis pour une recherche rapide
	    $(".bloc-message-forum ").each(function(index, message){
            var style = "width:16px;height:16px;background:#999999;color:#FAFAFA;opacity:0.33;line-height:18.57px;margin:0px;display:inline-block;padding-bottom:4px;border-radius:3px;overflow:hidden;padding-left:3px;cursor:pointer;";

            $(message).find(".bloc-options-msg").prepend("<div id='rechercheSC" + index + "' style='" + style + "' title='Recherche'>R</div>");
            $(message).find(".bloc-options-msg").prepend("<div id='pseudoSC" + index + "' style='" + style + "visibility: hidden;' title='Par pseudo'>P</div>");
            $(message).find(".bloc-options-msg").prepend("<div id='citationSC" + index + "' style='" + style + "visibility: hidden;' title='Par citation'>C</div>");

            (function(_index) {
                $("#rechercheSC" + _index).click(function() {
                    if($("#pseudoSC" + _index).css("visibility") == "hidden"){
                        $("#pseudoSC" + _index).css("visibility", "visible");
                        $('#pseudoSC' + _index).position({
                            my: 'right top+3',
                            at: 'left bottom',
                            of: $('#rechercheSC' + _index)
                        });

                        $("#citationSC" + _index).css("visibility", "visible");
                        $('#citationSC' + _index).position({
                            my: 'left top+3',
                            at: 'right bottom',
                            of: $('#rechercheSC' + _index)
                        });
                    }else{
                        $("#pseudoSC" + _index).css("visibility", "hidden");
                        $("#citationSC" + _index).css("visibility", "hidden");
                    }
                });

                $("#pseudoSC" + _index).click(function(){
                    var forumeur = $(message).find(".bloc-pseudo-msg").text().replace(/ /g, '');
                    console.log($(message));
                    var keywords = [forumeur];
                    ShowSearchForm(keywords, "Pseudo");
                });

                $("#citationSC" + _index).click(function(){
                    var date = $(message).find(".xXx.lien-jv").text();
                    var pseudo = $(message).find(".bloc-pseudo-msg").text();
                    var keyword = "Le" + date + pseudo + "aécrit:";
                    ShowSearchForm([keyword.replace(/ /g, '').replace(/(\r\n|\n|\r)/gm, "")], "Citation");
                });
            }(index));
	    });
    }

    function ShowSearchForm(keywords, mode) {
        window.scrollTo(0, 0);
        var lastPage = GetLastPageNumber();
        var range = [1, lastPage];

        $("<div/>",
            {
                id: "backgroundRecherche",
                style: "position: fixed;top: 0; left: 0; width: 100%; height: 100%;background: #000; opacity: 0.6; filter: alpha(opacity=60); z-index: 1;"
            }
        ).prependTo($("body"));

        $("<div/>",
            {
                id: "divRechercheForm",
                class: "container container-content",
                style: "min-height: 0; padding: 0; margin-left: 15%; border-top-right-radius: 5px; border-top-left-radius: 5px; margin-top:50px; position:absolute; top: 500 px; left: 0px; z-index:2; width: 70%;"
            }
        ).append($("<h1/>",
            {
                text: "Recherche",
                style: "margin-top: 10px; border-bottom: 2px solid #989898; width: 100%; text-align: center; padding-bottom: 5px; color: orange;"
            }
        )).append($("<input/>",
            {
                id: "inputRecherche",
                type: "text",
                class: "txt-search",
                style: "width: 20%; margin-left: 7.5%; border: 0.0625rem solid #d0d0d9; height: 1.75rem; padding: 0.1875rem; float: left;"
            }
        )).append($("<select/>",
            {
                id: "selectRecherche",
                style: "width: 15%; height: 1.75rem;"
            }
        ).append(
            $("<option/>",
                {
                    value: "Message",
                    text: "Message"
                }
            )).append($("<option/>",
                {
                    value: "Pseudo",
                    text: "Pseudo"
                }
            )   
            ).append($("<option/>",
                {
                    value: "Citation",
                    text: "Citation"
                }
        ))).append($("<div/>",
        {
            id: "sliderRange",
            style: "width: 20%; display: inline-block; margin-left: 5%"
        })).append($("<span/>", {
            text: "Recherche",
            class: "btn btn-actu-new-list-forum",
            style: "width: 15%; margin-left: 3%",
            click: function() {
                stop = false;
                nbMatch = 0;
                $("#loadingRecherche").show();
                $("#divRecherchePosts div").remove();
                keywords = $("#inputRecherche").val().split(" ").filter(Boolean);
                var startPage = window.location.href;
                startPage = startPage.replace(/(\/forums\/[\d]*-[\d]*-[\d]*-)[\d]*(-.*)/, "$1" + range[0] + "$2");

                ProcessSearch(startPage, keywords, $("#selectRecherche").val(), range[0], range[1]);
            }
        })).append($("<div/>",
            {
                id: "divRecherchePosts",
                style: "width: 100%; border-top: 2px solid #989898; margin-top : 15px; padding: 0 15px 0 15px;"
            }).append($("<p/>",
                {
                    id: "pRecherche",
                    style: "display: inline-block; font-size: 15px; width: 100%; text-align: center; color: orange; padding-top: 10px"
                })
        )).prependTo($("body"));

        $("#sliderRange").after("<div style='display:inline-block; position: absolute' id='min'></div><div style='display:inline-block; position: absolute' id='max'></div>");
        $("#sliderRange").slider({
          range: true,
          min: 1,
          max: lastPage,
          values: [ 1, lastPage ],
            slide: function(event, ui) {
                range[0] = ui.values[0];
                range[1] = ui.values[1];
                var delay = function() {
                    var handleIndex = $(ui.handle).index();
                    var label = handleIndex == 1 ? '#min' : '#max';
                    $(label).html(ui.value).position({
                        my: 'center top',
                        at: 'center bottom',
                        of: ui.handle,
                        offset: "0, 10"
                    });
                };
                setTimeout(delay, 5);
            }
        });

        $('#min').html($('#sliderRange').slider('values', 0)).position({
            my: 'center top',
            at: 'center bottom',
            of: $('#sliderRange span:eq(0)'),
            offset: "0, 10"
        });

        $('#max').html($('#sliderRange').slider('values', 1)).position({
            my: 'center top',
            at: 'center bottom',
            of: $('#sliderRange span:eq(1)'),
            offset: "0, 10"
        });

        $("#backgroundRecherche").click(function() {
            stop = true;
            $("#divRechercheForm").remove();
            $(this).remove();
        });

        if (keywords) {
            $("#inputRecherche").val(keywords[0]);
        }
        $("#selectRecherche").val(mode);
    }

    function ProcessSearch(page, keywords, mode, currPageNb, lastPageNb) {
        $.ajax({
            url: page,
            type: 'GET'
        }).done(function(data) {            
            if (mode === "Pseudo") {
                $(data).find(".bloc-message-forum").each(function(index, post) {
                    var pseudo = $(this).find(".bloc-pseudo-msg").text().replace(/ /g, '').replace(/(\r\n|\n|\r)/gm, "");
                    if (keywords.includes(pseudo)) {
                        nbMatch++;
                        $("#divRecherchePosts").append($(this));
                        $("#divRecherchePosts .bloc-message-forum:last .bloc-header .bloc-date-msg").append("<p style='padding-left: 5px; float:right; color: green'>Page : " + currPageNb + " - Post : " + (index + 1) + "</p>");
                    }
                });
            } else if (mode === "Message") {
                $(data).find(".bloc-message-forum").each(function(index, post) {
                    var nbFind = 0;
                    for (var i = 0; i < keywords.length; i++) {
                        var message = $(this).find(".txt-msg.text-enrichi-forum").text().toLowerCase();
                        if (message.indexOf(keywords[i].toLowerCase()) > -1) {
                            nbFind++;
                        }
                    }

                    if (nbFind == keywords.length) {
                        nbMatch++;
                        $("#divRecherchePosts").append($(this));
                        $("#divRecherchePosts .bloc-message-forum:last .bloc-header .bloc-date-msg").append("<p style='padding-left: 5px; float:right; color: green'>Page : " + currPageNb + " - Post : " + (index + 1) + "</p>");
                    }
                });
            } else if (mode === "Citation") {
                $(data).find(".bloc-message-forum").each(function(index, post) {                    
                    var blockquote = $(this).find(".txt-msg.text-enrichi-forum blockquote:first").text().replace(/ /g, '').replace(/(\r\n|\n|\r)/gm, "");
                    if(blockquote.indexOf(keywords[0]) > -1 ){
                        nbMatch++;
                        $(this).find(".img-shack").each((index, img) => {
                            $(img).click(() => {
                                window.open($(img).attr("alt"), "");
                            })
                        });
                        $("#divRecherchePosts").append($(this));
                        $("#divRecherchePosts .bloc-message-forum:last .bloc-header .bloc-date-msg").append("<p style='padding-left: 5px; float:right; color: green'>Page : " + currPageNb + " - Post : " + (index + 1) + "</p>");
                    }
                });
            }
            $("#pRecherche").text(currPageNb + " / " + lastPageNb + " Match : " + nbMatch);

            currPageNb++;
            if (!stop && currPageNb <= lastPageNb) {
                var nextPage = $(data).find(".page-active:first").next().find("a").attr("href");
                ProcessSearch(nextPage, keywords, mode, currPageNb, lastPageNb);
            }else{
                $("#loadingRecherche").hide();
                $("#pRecherche").text("Match : " + nbMatch);
            }
        });
    }

    function GetLastPageNumber(){
        var lastPage = $(".bloc-liste-num-page:first span:last");
        return lastPage.text() === "»" ? lastPage.prev().text() : lastPage.text();
    }
})();