Ssieth / FunTrivia Answer Guesser

// ==UserScript==
// @name         FunTrivia Answer Guesser
// @namespace    http://gaxx.co.uk/funTrviaRanomizer
// @version      1.6
// @description  Select a random answer or educated guess to each question
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @author       Gaxx
// @include      http://www.funtrivia.com/private/play.cfm
// @include      http://www.funtrivia.com/private/play.cfm?tid=86650
// @include      https://www.funtrivia.com/private/play.cfm
// @include      https://www.funtrivia.com/private/play.cfm?tid=86650
// @include      https://www.funtrivia.com/private/submit2.cfm
// @include      http://www.funtrivia.com/private/submit2.cfm
// @grant       GM_xmlhttpRequest
// @connect     www.googleapis.com
// @connect      cabbit.org.uk
// @license      MIT
// ==/UserScript==

(function() {
    var autoSubmit = false;
    var guessCount = 0;
    var aStore = {};
    var useStore = true;
  
    function showTimer() {
      var $timer = $("<div style='position: fixed; top: 10px; right: 10px; display: table; height: 50px; overflow: hidden; width: 75px; background-color: #ddd; border-radius: 25px; border: thin solid black;'><div style='display: table-cell; vertical-align: middle; text-align: center; font-size: 1.5rem'><div id='timerVal'>000</div></div></div>");
      $("body").append($timer);
      setInterval(function(){
        var tm = parseInt($("#timerVal").text());
        ++tm;
        $("#timerVal").html(tm);
      }, 1000);
    }
  
    function cabbitLoadSettings(callback) {
        var strData = '';
        var strURL = "https://cabbit.org.uk/eli/?site=eli&user=eli&hash=musicquiz";
        GM_xmlhttpRequest({
            method: "GET",
            url: strURL,
            headers: {
                "Content-Type": "application/json"
            },
            onload: function (response) {
                var data = JSON.parse(response.responseText);
                var settingsData = {};
                if (data.status == 'ok') {
                    aStore = JSON.parse(data.settings);
                }
                if (callback) {
                    callback(settingsData);
                }
            }
        });
    }

    function cabbitSaveSettings(callback) {
        var strData = JSON.stringify(aStore);
        var strURL = "https://cabbit.org.uk/eli/?site=eli&user=eli&hash=musicquiz";
        GM_xmlhttpRequest({
            method: "POST",
            url: strURL,
            data: strData,
            headers: {
                "Content-Type": "application/json"
            },
            onload: function (response) {
                if (callback) {
                    var data = JSON.parse(response.responseText);
                    callback(data);
                }
            }
        });
    }

    function guessFunc(questionNo, guessNo, guess, color) {
        console.log("Question #" + questionNo + " = Answer #" + guessNo + ": " + guess);
        var $t = $('table[style="border:1px #336600 solid;"]:eq(' + questionNo + ')');
        if (color) {
          $t.find("b").css("color",color);
        } else {
          $t.find("b").css("color","darkred");
        }
        $t.find("input[type='radio']:eq(" + guessNo + ")").trigger("click");
    }

    function getGuess(question, aryAnswers, questionNo) {
        // Check our store of q/a's
        var ans = aStore.answers[question.trim().toLowerCase()];
        if (ans && useStore) {
            for (var a = 0; a < aryAnswers.length; a++) {
                if (aryAnswers[a] === ans ) {
                    guessFunc(questionNo,a,ans,"darkgreen");
                    guessCount--;
                    return;
                }
            }
        }
        // statr all answers out as 0 weighted
        var answerWeights = Array.apply(null, Array(aryAnswers.length)).map(function () { return 0});
        GM_xmlhttpRequest({
            method: "GET",
            url: "https://www.googleapis.com/customsearch/v1?cx=003992053095861909355:pa3mtkk4xks&key=AIzaSyBcdsv-J_rM493ZZMixL6aUs4E8Xr77PCI&q=" + encodeURI(question.replace(/\_/g,"")),
            onload: function(response) {
                var objResponse = JSON.parse(response.response);
                console.log(objResponse);
                console.log("#" + questionNo + ": " + question);
                var aryPages = objResponse.items;
                var intMax = 0;
                var maxPos = 0;
                if (aryPages) {
                  for (var i = 0; i < aryPages.length; i++) {
                      for (var j = 0; j < answerWeights.length; j++) {
                          var myRe = new RegExp(aryAnswers[j], 'gi');
                          if (aryPages[i].snippet.match(myRe)) {
                              answerWeights[j] += (aryPages[i].snippet.match(myRe).length);
                          }
                      }
                  }
                  intMax = answerWeights[0];
                  for (var k = 1; k < answerWeights.length; k++) {
                      if (answerWeights[k] > intMax) {
                          maxPos = k;
                          intMax = answerWeights[k];
                      }
                  }
                } else {
                  console.log("No results");
                }
                console.log(answerWeights);
                if (intMax > 0) {
                    guessFunc(questionNo,maxPos,aryAnswers[maxPos]);
                } else {
                    if (question.indexOf("\"") > -1) {
                        console.log(questionNo + " trying quoted");
                        guessCount++;
                        setTimeout( () => {
                            getGuess(question.split('"')[1],aryAnswers,questionNo);
                        }, 4000);
                    } else if (question.indexOf("'") > -1) {
                        console.log(questionNo + " trying single-quoted");
                        guessCount++;
                        setTimeout( () => {
                            getGuess(question.split("'")[1],aryAnswers,questionNo);
                        }, 4000);
                    }
                }
                guessCount--;
            }
        });
    }

    function getGuesses() {
        $('table[style="border:1px #336600 solid;"]').each(function( index ) {
            var $list = $( this );
            var $ans = $list.find('input[type="radio"]');

            if ($ans.length > 1) {
                var $sel = $list.find("input[type='radio']:eq(" + Math.floor(Math.random() * $ans.length) + ")").trigger("click");
                var q = $ans.parent().parent().parent().parent().parent().parent().find("b").text();
                guessCount++;
                setTimeout(
                    () => {
                        getGuess(q,[$ans[0].value,$ans[1].value,$ans[2].value,$ans[3].value],index)
                    },
                    index * 700
                );

            }
        });
        window.scrollTo(0,0);
        if (autoSubmit) {
            $("input[type='submit']").trigger("click");
        }
    }

    function recordAnswers() {
        var as = aStore.answers;
        $('table.boxwhite').each(function(index) {
            var q = $(this).find("table.lighttable tbody tr td font").text();
            var iPos = q.indexOf(".");
            q = q.substring(iPos+1).toLowerCase().trim();
            var a = $(this).find('font[color="green"]').text();
            as[q] = a;
        });
        aStore['answers'] = as;
        console.log(aStore);
        cabbitSaveSettings(function() { console.log("Saved answers") });
    }

    console.log("== FunTrivia Answer Guesser v" + GM_info.script.version + " ==");
    var path = window.location.pathname;
    var page = path.split("/").pop();
    page = page.split("?")[0];
    console.log(page);
    cabbitLoadSettings( function() {
        switch (page.toLowerCase()) {
            case "play.cfm":
                showTimer();
                getGuesses();
                break;
            case "submit2.cfm":
                recordAnswers();
                break;
            default:
                break;
        }
    });
    console.log("/= FunTrivia Answer Guesser v" + GM_info.script.version + " =/");
})();