JR Crowdsource keyword/ranking mturk.com scripts

A userscript for crowdsource keyword and ranking hits. It should be working for the keywords for any Google location. Also it will work for the ranking hits. It will even work for the choose the best URL hits.

As of 2014-12-08. See the latest version.

// ==UserScript==
// @name            JR Crowdsource keyword/ranking mturk.com scripts
// @version         0.75
// @description     A userscript for crowdsource keyword and ranking hits. It should be working for the keywords for any Google location. Also it will work for the ranking hits. It will even work for the choose the best URL hits.
// @author          John Ramirez (JohnnyRS) ([email protected])
// @license         Creative Commons Attribution License
// @include         *
// @require         http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js
// @require         http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js
// @run-at          document-end
// @grant       	GM_setClipboard
// @grant           GM_addStyle
// @namespace       https://greasyfork.dpdns.org/users/6406
// ==/UserScript==

// Version 0.75 - Cleaned up some coding. Fixed some small bugs dealing with searching. Added some newer versions of hits
// -- which it will work with. Zip codes still not perfect but works OK.
// -- Directions for the majority of hits:
//    There should be a search button after the keyword or question. Clicking on the button will take you to a Google page that displays 50 results.
//    It does this so you won't need to go to all 5 pages. It will know which page a result should be on. On the Google search page you will see a
//    box on the right side which is movable by you. It will stay on screen even when scrolling the page. This box will have instructions and
//    the URL or question that you need to find. Along the left side of the screen each result has a select button which you can press to select
//    that result. The script will color the button red for an exact match for a URL. Purple button means it's a close match so check it to see if
//    it's close enough. If you click on the button it will load up the page and show the same box with different instructions, buttons and question.
//    Answer the question and click on the buttons to send the selected answer, URL or type in your own answer in the text box.
// -- Instruction/Question box instructions:
//    You can move the box around the screen if it's in the way. Just click it and move it. You can press the F9 key to hide or show it. The box will
//    start out solid but will go transparent when you move your mouse away so you can see the page better. The selection button will send whatever
//    you have selected on the page as the answer. The URL button sends the URL of the page as the answer. The close page button closes the page and goes
//    back to Google search or back to the hit page. The none button will send none as your answer. The text input is for you to answer a question
//    yourself if you can't select it on the page. Send answer button sends what you have typed or what you have selected. You can use keyboard shortcuts
//    to make it easier:
//    - Pressing F9 will hide/show the instruction box if it gets in the way of the page.
//    - Pressing w will take the URL of the page as the answer and fill it in the hit automatically.
//    - Pressing e will focus on the input text field where you can type in your own answer. Pressing ENTER in the field will submit the text as the answer.
//    - Pressing p will close that window and return you to the Google search page so you can select another site or go back to the hit.
//    - Pressing s will submit whatever you selected as the answer.
//    - Pressing n will submit None as your answer.
// -- Zip Codes:
//    This script can work with the zip codes. It will fill it in automatically on the Google page. This does cause it to slow down so need to wait.
//    It might not work all the time. Couldn't find an easier way to fill in the zip code.
// -- Google Questions:
//    Some hits will ask for an answer on the Google search page itself. The script will usually find the number of results and time by itself.
//    It will show it's answer in the box and let you correct it if it's wrong. It will also show the result number by each button to make it easier
//    to select the numbered result you need. It will fill in the title, description or url of the result when you click on the button. It's smart.
// -- Compatible with these versions of hits:
// ==== Search: Keywords on Google......  
// ==== Search: Location and Keywords on Google...... 
// ==== Search: Ranking of a URL on Google...... 
// ==== Search: Ranking of a URL...... 
//
//  This should work on firefox and chrome. Should work with Pale Moon also. Because this script has to run for every page I recommend you
//  to disable it after you use it. Makes things go faster. It shouldn't interfere with any page in normal situations. But some rare situations
//  can occur so disable it. Newer versions will be added as needed. Yahoo and Bing will be added when I can catch one so I can test it.
// - John Ramirez / Email: [email protected]

// Constant variables used to verify it's working for only the correct hit.
// Also to check if it's in preview mode or not.
// gTag allows multiple sessions of this script without sending wrong messages to the wrong script.
// ------------------- CONSTANT VARIABLES - options
var VERIFY1 = "copy and paste the url of the most relevant result";
var VERIFY2 = "return information about a keyword search in";
var VERIFY3 = "record a url's search ranking on";
var VERIFY4 = "open google.cz, and search the provided keyword";
var VERIFY5 = "The information below will help clarify the instructions that are in each HIT.";
var VERIFY6 = "Click \"Search Tools\" then \"Search near...\"";
var VERIFY7 = "The information below will help clarify the instructions that are in each HIT.";
var PREVIEW1 = "You are currently in preview mode";
var ONPREVIEW = false;									  
var MYVERIFY = "feetsmell";                               // used for all my scripts to verify messages originating from my script.
var SCRIPTNAME = "JR Crowdsource keyword/ranking";        // used to make sure this script answers to messages originating from this script only.
// ----------------------------------------------------------

var gMyWindow = null, gSearchURLs = [], gTaskNumber = 0, gQuestions = [], gTag = -1, gMouseTimer = null, gSearchVersion = 0;
var gGoogleDomain = "google.com", gKbShortcutFired = false, gMyInstructionsBox = null, gLocation = document.URL.toString();
var gSearchUrl = "", gHostName="", gZipCodes=[], gTheKeyword=[];
var gLogging = false, gDebugging = false;
if (typeof console.log !== 'function') { gDebugging=false; gLogging=false; }
else { gLogging = (gLogging) ? gLogging : gDebugging; }

function removeHTMLTags(htmlString){
    if(htmlString) {
        var mydiv = document.createElement("div");
        mydiv.innerHTML = htmlString;
        if (document.all) return mydiv.innerText;  // IE Stuff 
        else return mydiv.textContent; // Mozilla does not work with innerText
    }
}
Number.prototype.isQuestionVersion = function() {
    if (this==2 || this==3 || this==5 || this==7 || this==6) return true;
    else return false;
};
Number.prototype.isZipCodeVersion = function() {
    if (this==5 || this==6) return true;
    else return false;
};
Number.prototype.hasSelectNone = function() {
    if (this==3) return false;
    else return true;
};
Number.prototype.isGoogleQuestion = function() {
    if (this==7 || this==5) return true;
    else return false;
};
function getHostName(url) {
    var match = url.match(/(.+:\/\/)?([^\/]+)(\/.*)*/i);
    if (match !== null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) return match[2].replace("www.","");
    else return "";
}
function getDomainName(url) {
    var hostName = getHostName(url);
    var splitHostName = hostName.split('.');
    if ( splitHostName.length > 2 ) return splitHostName[splitHostName.length-2] + "." + splitHostName[splitHostName.length-1];
    else return hostName;
}
function dataFill(action, data1, data2, data3, data4, data5, data6) {
    if(typeof(data1)==='undefined') data1 = "";
    if(typeof(data2)==='undefined') data2 = "";
    if(typeof(data3)==='undefined') data3 = "";
    if(typeof(data4)==='undefined') data4 = "";
    if(typeof(data5)==='undefined') data5 = "";
    if(typeof(data6)==='undefined') data6 = "";
    var tempe = {"verify": MYVERIFY, "scriptName": SCRIPTNAME, "tag": gTag, "action": action,
            "data1": data1, "data2": data2, "data3": data3, "data4": data4, "data5": data5,
            "data6": data6};
    return tempe;
}
function verifyMessage(e,thisLocation) {
    if (e.data.verify === MYVERIFY && e.data.scriptName === SCRIPTNAME) return true;
    else return false;
}
function urlMatch(url1, url2) { 
    if(typeof(url1)==='undefined' || typeof(url2)==='undefined') return 0;
    var hostName1 = getHostName(url1);
    var hostName2 = getHostName(url2);
    url1 = url1.replace(/(^http.?:\/\/)|(\/$)|(www\.)/g,'');
    url2 = url2.replace(/(^http.?:\/\/)|(\/$)|(www\.)/g,'');
    if ( url1.toLowerCase() == url2.toLowerCase() ) return 1;
    else if ( hostName1.toLowerCase() == hostName2.toLowerCase() ) return 2;
    else return 0;
}
function createMyElement(elementName,theClass,theId,theStyle) {
    var theElement = document.createElement(elementName);
    if (theClass) theElement.className = theClass;
    if (theId) theElement.id = theId;
    if (theStyle) theElement.setAttribute("style",theStyle);
    return theElement;
}
function createButton(theClass,theId,theValue,theName,theStyle) {
    var theButton = createMyElement("input",theClass,theId,theStyle);
    theButton.type = "button";
    if (theValue) theButton.value = theValue;
    if (theName) theButton.name = theName;
    return theButton;
}
function createTextInput(theClass,theId,theValue,theStyle) {
    var theInput = createMyElement("input",theClass,theId,theStyle);
    theInput.type = "text";
    if (theValue) theInput.value = theValue;
    return theInput;
}
function createLink(theClass,theId,theUrl,theTitle,theStyle) {
    var theLink = createMyElement("a",theClass,theId,theStyle);
    theLink.innerHTML = theTitle;
    theLink.href = theUrl;
    theLink.title = theTitle;
    theLink.setAttribute("target","_new");
    return theLink;
}
function createDiv(theClass,theId,theStyle) {
    var theDiv = createMyElement("div",theClass,theId,theStyle);
    if (theId) theDiv.id = theId;
    if (theClass) theDiv.className = theClass;
    return theDiv;
}
function answerURL() {
    data = dataFill( "found answer", gTaskNumber, document.URL.toString() );
    parent.window.opener.postMessage(data,"*");
}
function answerSel() {
    data = dataFill( "found answer", gTaskNumber, window.getSelection().toString() );
    GM_setClipboard( window.getSelection().toString() );
    parent.window.opener.postMessage(data,"*");
}
function answerThis(answer) {
    data = dataFill( "found answer", gTaskNumber, answer );
    parent.window.opener.postMessage(data,"*");
}
function answerInput() {
    data = dataFill( "found answer", gTaskNumber, document.getElementById("enterAnswer").value );
    parent.window.opener.postMessage(data,"*");
}
function foundNone() {
    data = dataFill( "found answer", gTaskNumber, "None" );
    parent.window.opener.postMessage(data,"*");
}
function answerNone() {
    data = dataFill( "found page and rank", gTaskNumber, "None", "None", "None" );
    parent.window.opener.postMessage(data,"*");
}
function goToSearch() {
    data = dataFill( "initialize google" );
    parent.window.opener.postMessage(data,"*");
}
function textInputFocus() {
    var gRightSideBar    = $('#myInstructionsBox');
    gKbShortcutFired = false;
    gRightSideBar.stop (true, false).fadeTo (50,  1  );
}
function textInputFocusout() {
    var gRightSideBar    = $('#myInstructionsBox');
    if ( !gRightSideBar.is(":hover") ) gRightSideBar.stop (true, false).fadeTo (2900, 0.1);
}
function attrInstructionsBox() {
    gMyInstructionsBox    = $('#myInstructionsBox');
/*jshint multistr: true */
    GM_addStyle ( "                                                     \
        #myInstructionsBox { \
            position:               fixed; \
            top:                    100px; \
            right:                  0; \
            margin:                 1px; \
            padding:                2px 6px 10px 10px; \
            background:             #0B0B3B; \
            width:                  460px; \
            z-index:                99999; \
            opacity:                1.0; \
            color:                  #F7F8E0; \
            text-align:             left; \
            line-height:            18px; \
            font-family:            Helvetica,Arial,Sans-Serif; \
            cursor:                 move; \
            font-size:				12px; \
            font-weight:			normal; \
            background-color:		grey; \
        } \
        #myInstructionsBox p { \
            font-size:              14px; \
        } \
        #myInstructionsBox #myInstructions { \
            font-size:              13px; \
            color:                  #F7F8E0; \
            padding:                2px 0 10px 8px; \
            margin:                 2px 5px; \
            line-height:            normal; \
        } \
        #myInstructionsBox #theQuestion { \
            font-size:              16px; \
            color:                  cyan; \
            margin-top:             8px; \
            padding:                12px 0 10px 5px; \
            background-color:       black; \
            cursor: text; \
        } \
        #myInstructionsBox #theControls {  \
            padding:                0 0 0 15px;  \
        } \
        #myInstructionsBox .myButton {  \
            background-color:		WhiteSmoke; \
            cursor: pointer; \
            color: black !important; \
            text-shadow: none; \
            text-decoration: none; \
            font-weight: normal; \
            font-size:14px; \
            border: none; \
            font-family:            Helvetica,Arial,Sans-Serif; \
        } \
        #myInstructionsBox .myTextInput { \
            font-size:              14px; \
            padding:                1px 2px 3px 2px; \
            color:                  black; \
            width:                  440px; \
            height:                 16px; \
        } \
        #myInstructionsBox ul {  \
            margin:                 0; \
        } \
        #myInstructionsBox input { \
            margin:                 2px; \
            color:                  #000000; \
            font-size:              16px; \
            padding:                1px 6px; \
        } \
        #myInstructionsBox a { \
            color:                  white; \
        } \
     " );
    gKbShortcutFired = false;
    //-- Fade panel when not in use
    gMyInstructionsBox.hover (
        function () {
            $(this).stop (true, false).fadeTo (50,  1  );
            gKbShortcutFired = false;
        },
        function () {
            if ( !$("#enterAnswer").is(":focus") ) {
                if ( ! gKbShortcutFired ) {
                    $(this).stop (true, false).fadeTo (2900, 0.1);
                }
                gKbShortcutFired = false;
            }
        }
    );
    document.getElementById("theQuestion").onmouseover = function() { gMyInstructionsBox.draggable("destroy"); };
    document.getElementById("theQuestion").onmouseout = function() { gMyInstructionsBox.draggable(); };
    $(window).keydown ( function(e) {
        if (e.keyCode == 120) { // F9 to toggle box
            gKbShortcutFired = true;
    
            if (gMyInstructionsBox.is (":visible") ) {
                gMyInstructionsBox.stop (true, false).hide ();
            }
            else {
                //-- Reappear opaque to start
                gMyInstructionsBox.stop (true, false).show ();
                gMyInstructionsBox.fadeTo (0, 1);
                if ( !$("#enterAnswer").is(":focus") ) gRightSideBar.fadeTo (3900, 0.1);
            }
    
            e.preventDefault ();
            e.stopPropagation ();
            return false;
        }
    },false);
    gMyInstructionsBox.draggable();
}
function createInstructionsBox(name,instructions,question,answer) {
    var frag = document.createDocumentFragment();
    var closeButton = createButton("myButton","closeMe","Close page (p)");
    closeButton.onclick = function () { 
        if (name == "google") self.close();
        else location.replace(gSearchUrl);
    };
    var instructionsBox = createDiv("myDiv","myInstructionsBox");
    var instructionsH3 = createMyElement("h3","myH3","myInstructions");
    instructionsH3.innerHTML = "[ F9 toggles visibility ] [ Move me around ]<br>" + instructions;
    var textInput = createTextInput("myTextInput","enterAnswer","");
    var submitButton = createButton("myButton","submitInput","Send Answer");
    submitButton.onclick = function () { 
        var theValue = document.getElementById("enterAnswer").value;
        answerThis( theValue === "" ? window.getSelection().toString() : theValue );
    };
    var controlsDiv = createMyElement("div","myDiv","theControls");
    var questionDiv = createMyElement("div","myDiv","theQuestion");
    var respondDiv = createMyElement("div","myDiv","theResponse");
    questionDiv.innerHTML = "Question: " + question;
    var answerDiv = createMyElement("div","myDiv","yourAnswer");
    answerDiv.innerHTML = "Type in Answer:<br>";
    answerDiv.appendChild(textInput);
    answerDiv.appendChild(submitButton);

    if (name == "google") {
        var sendAnswer = createButton("myButton","sendTheAnswer","Answer is correct. Send it.");
        sendAnswer.onclick = function () { answerThis(answer); };
        var wrongAnswer = createButton("myButton","wrongAnswer","Answer is wrong.");
        wrongAnswer.onclick = function () { 
            respondDiv.removeChild(sendAnswer);
            respondDiv.removeChild(wrongAnswer);
            respondDiv.appendChild(answerDiv);
            textInput.focus();
        };
        if (gSearchVersion.isQuestionVersion()) {
            var noneButton = createButton("myButton","noneAnswer","None (n)");
            controlsDiv.appendChild(noneButton);
            if (!gSearchVersion.isGoogleQuestion()) {
                questionDiv.innerHTML = "URL: " + gSearchURLs[0];
                noneButton.onclick = function () { answerNone(); };
            } else {
                noneButton.onclick = function () { foundNone(); };
            }
        }
        if (!gSearchVersion.isQuestionVersion() || gSearchVersion.isGoogleQuestion()){
            questionDiv.innerHTML = "Question: " + question;
            if (question.search("Please return the official website of the keyword") != -1) questionDiv.innerHTML += " ( " + gTheKeyword[0] + " )";
            if (answer !== "") {
                questionDiv.innerHTML += "<br><br><font color='LightYellow'><b>I found an answer: " + answer + "</b></font>";
                respondDiv.appendChild(sendAnswer);
                respondDiv.appendChild(wrongAnswer);
            }
        }
    } else {
        var urlButton = createButton("myButton","urlAnswer","URL (w)");
        urlButton.onclick = function () { answerURL(); };
        var selButton = createButton("myButton","selAnswer","Selection (s)");
        selButton.onclick = function () { answerSel(); };
        controlsDiv.innerHTML = "Answer: ";
        controlsDiv.appendChild(selButton);
        controlsDiv.appendChild(urlButton);
    }
    controlsDiv.appendChild(closeButton);
    instructionsBox.appendChild(instructionsH3);
    instructionsBox.appendChild(controlsDiv);
    instructionsBox.appendChild(questionDiv);
    instructionsBox.appendChild(respondDiv);
    if (name!="google" ) instructionsBox.appendChild(answerDiv);
    frag.appendChild(instructionsBox);
    document.body.appendChild(frag);
 
    textInput.onfocus = function(){ textInputFocus(); };
    textInput.onblur = function(){ textInputFocusout(); };
    
    attrInstructionsBox();
    document.onkeydown = function (e) {
        if (e.target.id !="enterAnswer") {
            if (name != "google") {
                if (e.keyCode == 87) answerURL(); // w = Use URL for answer.
                if (e.keyCode == 83) answerSel(); // s = to use your selection for answer.
                if (e.keyCode == 80) location.replace(gSearchURLs[0]); // p = close this window and go back to google search.
                if (e.keyCode == 69) { // e = Type in answer
                    textInput.focus(); 
                    e.preventDefault ();
                    e.stopPropagation ();
                    return false;
                }
            } else {
                if (e.keyCode == 80) self.close(); // p = close this window.
                if (e.keyCode == 78) { //answerNone(); // n = Can't find URL.
                    if (!gSearchVersion.isGoogleQuestion()) noneButton.onclick = function () { answerNone(); };
                    else noneButton.onclick = function () { foundNone(); };
                }
            }
        } else if ( e.keyCode == 13 ) answerInput(); // enter in input text will submit input value.
    };
}
function doZipCode() {
    var divTools = document.getElementById("hdtb_tls");
    divTools.click();
    var zipTextDiv = document.getElementsByClassName("mn-hd-txt")[3];
    if (zipTextDiv.innerHTML.indexOf(gZipCodes[0])==-1) {
        zipTextDiv.click();
        var zipCodeInput = document.getElementById("lc-input");
        var divZipCode = document.getElementById("_Zpd");
        var zipCodeSubmit = divZipCode.getElementsByClassName("ksb")[0];
        zipCodeInput.value = gZipCodes[0];
        zipCodeSubmit.click();
        return true;
    } else {
        setTimeout(function(){ divTools.click(); }, 2000);
        return false;
    }
}
String.prototype.getTextAfter = function(afterThis,stripand) {
    if ( typeof stripand === "undefined" ) stripand=true;
    var retText = removeHTMLTags(this).trim();
    var theIndex = retText.toLowerCase().indexOf(afterThis.toLowerCase());
    if (theIndex != -1) {
        retText = retText.substr(theIndex + afterThis.length).trim();
        if (stripand) retText = retText.replace(/&amp;/,"%26");
        else retText = retText.replace(/&amp;/g,"&");
    }
    return retText;
};
function getGoogleDomain() {
    if (gSearchVersion===0) return;
    var title = document.getElementsByClassName("projectTitle")[0].innerHTML;
    if (title.length>0 && title!="Search: Ranking of a Url") {
        title = title.replace("Search: Keywords on ","");
        title = title.replace("Search: Ranking of a Url on ","");
        title = title.replace("Search: Location and Keywords on ","");
        var splitTitle = title.split(' ');
        gGoogleDomain = splitTitle[0];
    }
}
function initializeGoogle(theTaskNumber) {
    var theData = null;
    if (gSearchVersion.isGoogleQuestion())
        theData = dataFill( "find google question", gSearchVersion, "", gQuestions[theTaskNumber-1],
                  gZipCodes[theTaskNumber-1], gTheKeyword[theTaskNumber-1] ,theTaskNumber );
    else if (gSearchVersion.isQuestionVersion())
        theData = dataFill( "search url", gSearchVersion, gSearchURLs[theTaskNumber-1], gQuestions[theTaskNumber-1],
                  gZipCodes[theTaskNumber-1], gTheKeyword[theTaskNumber-1] ,theTaskNumber );
    else theData = dataFill( "find best url", gSearchVersion, "", gQuestions[theTaskNumber-1], "", "", theTaskNumber );
    gMyWindow.postMessage(theData,"*");
}
function initializeQuestion() {
    var theData = dataFill( "answer question", gSearchVersion, gSearchUrl, gQuestions[gTaskNumber-1], "",
                  gTheKeyword[gTaskNumber-1] ,gTaskNumber  );
    gMyWindow.postMessage(theData,"*");
}
function getGoogleResultsPointer() {
    var results = document.getElementsByClassName("g");
    var pointers=[];
    if (results.length>0) {
        for (var i = 0, len=results.length; i < len; i++) {
            if ( !results[i].classList.contains("card-section") && results[i].id != "imagebox_bigimages" && 
                 results[i].getElementsByClassName("r").length>0 && 
                 results[i].getElementsByClassName("_SWb").length>0 && 
                 (results[i].getElementsByClassName("_YM").length===0 || results[i].getElementsByClassName("_Rm").length>0) &&
                 results[i].getElementsByClassName("kno-fb").length===0) {
                pointers.push(i);
            }
        }
    }
    return pointers;
}
function doGoogleButtons() {
    var urlPointers = getGoogleResultsPointer();
    var theAnswer = "", url="", pageRankText="";
    var results = document.getElementsByClassName("g");
    var resultStats = document.getElementById("resultStats").innerHTML.split(" ");
    var totalResults = resultStats[1] + " results";
    var totalTime = resultStats[3].substr(1) + " " + resultStats[4].split(")")[0];
    var searchTitle = (gQuestions[0].search("Please return the title of the") != -1) ? true : false;
    var searchDescription = (gQuestions[0].search("Please return the description of the") != -1) ? true : false;
    var searchUrl = ( (gQuestions[0].search("Please return the Url of the") != -1) || (gQuestions[0].search("Please return the official website of the keyword") != -1) ) ? true : false;
    var pageNum=1, rankNum=1;
    for (var i = 0, len=urlPointers.length; i < len; i++) {
        var btn = document.createElement("BUTTON");
        btn.innerHTML = "Select";
        if (searchTitle) btn.innerHTML += " The Title";
        else if (searchDescription) btn.innerHTML += " The Description";
        else if (searchUrl) btn.innerHTML += " The Url";
        btn.type = "button";
        btn.style.marginRight = "6px";
        btn.name = "B," + pageNum + "," + rankNum + "," + (urlPointers[i]);
        url = results[urlPointers[i]].getElementsByTagName("a")[0];
        matching = urlMatch( url.href, gSearchURLs[0] );
        if ( matching == 1 ) {
            btn.style.background='red';
            btn.style.color='#FFFFFF';
        } else if ( matching == 2 ) {
            btn.style.background="Purple";
            btn.style.color="#FFFFFF";
        } else if ( matching == 3 ) {
            btn.style.background="#F8E0F7";
            btn.style.color="#000000";
        }
            btn.style.fontSize="small";
        btn.onclick = function() {
            var splitName = this.name.split(',');
            var theIndex = splitName[3];
            var results = document.getElementsByClassName("g");
            var theUrl = results[theIndex].getElementsByTagName("a")[0];
            var theDescription = removeHTMLTags(results[theIndex].getElementsByClassName("st")[0].innerHTML);
            var theTitle = theUrl.innerHTML;
            var theData = null;
            if (gSearchVersion.isQuestionVersion() && !gSearchVersion.isGoogleQuestion()) {
                theData = dataFill( "found page and rank", gTaskNumber, splitName[1], splitName[2] );
                parent.window.opener.postMessage(theData,"*");
                results[theIndex].getElementsByTagName("a")[0].click();
            } else {
                theData = dataFill( "found url", gTaskNumber, theUrl.href );
                if (searchTitle) theData = dataFill( "found answer", gTaskNumber, theTitle );
                else if (searchDescription) theData = dataFill( "found answer", gTaskNumber, theDescription );
                else if (searchUrl) theData = dataFill( "found answer", gTaskNumber, theUrl.href  );
                parent.window.opener.postMessage(theData,"*");
            }
        };
        if (gSearchVersion.isGoogleQuestion() && pageNum>1) pageRankText = "Page: " + pageNum + "- Rank: " + rankNum + " ";
        else if (gSearchVersion.isGoogleQuestion()) pageRankText = "Rank: " + rankNum + " ";
        url.parentNode.insertBefore(document.createTextNode(pageRankText),url);
        url.parentNode.insertBefore(btn,url);
        if (gSearchVersion.isGoogleQuestion()) url.parentNode.insertBefore(createMyElement("br"),url);
        rankNum++;
        if ( rankNum>10 ) {
            rankNum=1; pageNum++;
        }
    }
    var myInstructions = "[ p to go back ]<br>";
    if (gSearchVersion.isQuestionVersion() && !gSearchVersion.isGoogleQuestion()) myInstructions = "[ n to fill in nothing found ] [ p to go back ]<br><br>" + 
        "Red buttons are perfect matches<br>Purple buttons have same hostnames.<br>";
    if (gQuestions[0].search("Please return the number of results") != -1) theAnswer = totalResults;
    else if (gQuestions[0].search("Please return the time Google took to complete") != -1) theAnswer = totalTime;
    createInstructionsBox("google",myInstructions,gQuestions[0],theAnswer);
}
function taskSearchButtons() {
    if (gSearchVersion===0) return;
    var tasks = document.getElementsByClassName("task cf");
    for (var i = 0, len=tasks.length; i < len; i++) {
        var theTextReps = tasks[i].getElementsByClassName("text-rep");
        var theTextRep = theTextReps[0].innerHTML.trim();
        var splitTextRep = theTextRep.split('<br>');
        gTheKeyword[i] = splitTextRep[0].getTextAfter("keyword:");
        var btn = createButton("myButton","searchBut" + (i+1),"Search","B," + (i+1));
        btn.style.fontSize="small";
        btn.style.marginLeft = "5px";
        btn.style.padding = "4px 12px";
        btn.disabled = false;
        if (isPreviewMode() && !ONPREVIEW) { 
            btn.value = "You haven't accepted this hit";
            btn.style.color = "red";
        } else {
            btn.onclick = function() {
                var splitName = this.name.split(',');
                gTaskNumber = splitName[1];
                var theKeyword = gTheKeyword[gTaskNumber-1].replace(/\s+/g,"+");
                var showResults = 50;
                if (gSearchVersion.isGoogleQuestion()) showResults = 10;
                gSearchUrl = "http://www." + gGoogleDomain + "/search?ion=0&num=" + showResults + "&q=" + theKeyword + 
                             "&jrio=feetwalk&ttt=" + gTaskNumber;
                gMyWindow = window.open(gSearchUrl);
            };
        }
        if (gSearchVersion.isQuestionVersion()) {    // Version 2, 3, 5 and 7 needs the URL and question.
            var theZipCode="";
            var theURL="";
            var theQuestion="";
            if (splitTextRep.length>1) {
                theURL = splitTextRep[1];
                theQuestion = "Click Url and record one sentence on webpage that relates to the keyword: " + gTheKeyword[i];
                theTextReps[0].innerHTML = "";
                var text1 = document.createElement("span");
                text1.innerHTML=splitTextRep[0];
                theTextReps[0].appendChild(text1);
                theTextReps[0].appendChild(btn);
                var text2 = document.createElement("span");
                text2.innerHTML="<br>" + splitTextRep[1];
                theTextReps[0].appendChild(text2);
            } else {
                var x=1;
                if (gSearchVersion.isZipCodeVersion()) {
                    theZipCode = theTextReps[x++].innerHTML;
                    theZipCode = theZipCode.getTextAfter("zipcode:");
                    theZipCode = theZipCode.getTextAfter("Location (Zipcode or City, State):");
                }
                if (!gSearchVersion.isGoogleQuestion()) theURL = theTextReps[x++].innerHTML;
                theQuestion = theTextReps[x++].innerHTML.replace("Instructions: ","").trim();
                theTextReps[0].appendChild(btn);
            }
            theURL = theURL.getTextAfter("url:",false);
            gSearchURLs[i] = theURL;
            gQuestions[i] = theQuestion;
            gZipCodes[i] = theZipCode;
        } else {
            theTextReps[0].appendChild(btn);
            gQuestions[i] = "Select the most relevant result for the keyword: " + gTheKeyword[i];
        }
    }
}
function otherListener(e) {
    if (gDebugging && gLogging) console.log("..G Received message action - " + e.data.action);
    if (gTag == -1) {
        gSearchVersion = e.data.data1;
        gSearchURLs[0] = e.data.data2;
        gQuestions[0] = e.data.data3;
        gZipCodes[0] = e.data.data4;
        gTheKeyword[0] = e.data.data5;
        gTaskNumber = e.data.data6;
        gTag = e.data.tag;
        gSearchUrl = gLocation;
        if (e.data.action == "answer question") {
            var myInstructions = "[ w to use the URL for the answer ] ";
            myInstructions += "[ e to fill in answer ]<br />[ s to use selection as answer ] [ p to go back to google ]\n";
            gSearchUrl = gSearchURLs[0];
            createInstructionsBox("other",myInstructions,gQuestions[0],"");
        } else if (e.data.action == "search url" || e.data.action == "find best url" || e.data.action == "find google question") {
            if (gZipCodes[0]!=="") { if (!doZipCode()) doGoogleButtons(); }
            else doGoogleButtons();
            
        }
    }
}
function mainListener(e) { 					// Just a repeater to the frame (Google Chrome fix because messaging to the frame wasn't working.)
    if (gDebugging && gLogging) console.log("..M Received message action - " + e.data.action);
    var doc=document.getElementsByTagName("iframe")[0].contentWindow;
    doc.postMessage(e.data,"*");
}
function frameListener(e) {
    if (gDebugging && gLogging) console.log("..F Received message action - " + e.data.action);
    if (e.data.action == "initialize google") initializeGoogle(e.data.data1);
    else if (e.data.action == "initialize the question") initializeQuestion();
    else if (e.data.action == "found page and rank" && e.data.tag == gTag) {
        if (!gSearchVersion.hasSelectNone() && (e.data.data2=="None" || e.data.data3=="None")) {
            document.getElementById("PageNumber-"+e.data.data1).value = "";
            document.getElementById("Ranking-"+e.data.data1).value = "";
            document.getElementById("BeyondPage5-"+e.data.data1).click();
            document.getElementById("Sentence-"+e.data.data1).value = "";
        } else {
            document.getElementById("PageNumber-"+e.data.data1).value = e.data.data2;
            document.getElementById("Ranking-"+e.data.data1).value = e.data.data3;
            if (document.getElementById("BeyondPage5-"+e.data.data1)!==null) {
                document.getElementById("BeyondPage5-"+e.data.data1).checked = false;
            }
            if (e.data.data4 !== "") document.getElementById("WorkerResponse-"+e.data.data1).value = e.data.data4;
        }
        if (e.data.data2 == "None") gMyWindow.close();
        else initializeQuestion();
    } else if (e.data.action == "found url" && e.data.tag == gTag) { // This is for version 1 of the keyword search
        document.getElementById("URL-"+e.data.data1).value = e.data.data2;
        gMyWindow.close();
    } else if (e.data.action == "found answer" && e.data.tag == gTag) {
        if (!gSearchVersion.hasSelectNone()) document.getElementById("Sentence-"+e.data.data1).value = e.data.data2;
        else document.getElementById("WorkerResponse-"+e.data.data1).value = e.data.data2;
        gMyWindow.close();
    }
}
function enableTextSelections(className) {
    results = document.getElementsByClassName(className);
    for (var i = 0, len=results.length; i < len; i++) {
        results[i].setAttribute("unselectable", "off");
        var theStyle=results[i].getAttribute("style");
        if (theStyle !== null) {
            theStyle = theStyle.replace("-moz-user-select: none;","");
            theStyle = theStyle.replace("-webkit-user-select: none;","");
            results[i].setAttribute("style", theStyle);
        }
    }
}
function isPreviewMode() {
    if (!document.getElementById("preview")) return false;
    if (document.getElementById("preview").innerHTML.indexOf(PREVIEW1)==-1) return false;
    else return true;
}
function withPages_jQuery(NAMED_FunctionToRun) {
  var funcText        = NAMED_FunctionToRun.toString ();
  var funcName        = funcText.replace (/^function\s+(\w+)\s*\((.|\n|\r)+$/, "$1");
  var script          = document.createElement("script");
  script.textContent  = funcText + "\n\n";
  script.textContent += 'jQuery(document).ready(function() {'+funcName+'(jQuery);});';
  document.body.appendChild(script);
}
 function main0($) {  
  $.extend($.fn.enableTextSelect = function() {
    return this.each(function() { $(this).unbind("mousedown"); });
  });
  $("h2.text-rep").enableTextSelect();
  $("h1.text-rep").enableTextSelect();
}

var gHostName = getHostName(gLocation);
// Check if page is on crowdsource or google. If not then check if page was opened by script. If not then exit.
if ( gHostName === "work.crowdsource.com" || gLocation.indexOf("jrio=feetwalk") != -1 || gHostName === "mturk.com" || window.opener ) {
    // The magic begins here by first making sure I am on a crowdsource page
    // and then checking if it's a crowdsource hit that it will work with.
    // After I set up the buttons to make the search for keywords easier.
    if (gHostName=="work.crowdsource.com"){ // Make sure this is on the crowdsource site.
        var inPreview = isPreviewMode();
        withPages_jQuery(main0);
        window.addEventListener("message", function(e){ if ( verifyMessage(e) ) frameListener(e); }, false);
        gTag = new Date().getTime(); // A unique global tag used to pass messages only for this session.
        var instructions = document.getElementById("instructions").innerHTML.toLowerCase();
        if (instructions.indexOf(VERIFY1.toLowerCase()) != -1) gSearchVersion = 1;
        else if (instructions.indexOf(VERIFY2.toLowerCase()) != -1) {
            gSearchVersion = 2;
             if (instructions.indexOf(VERIFY7.toLowerCase()) != -1) gSearchVersion = 7;
       }
        else if (instructions.indexOf(VERIFY3.toLowerCase()) != -1) gSearchVersion = 3;
        else if (instructions.indexOf(VERIFY4.toLowerCase()) != -1) gSearchVersion = 4;
        else if (instructions.indexOf(VERIFY6.toLowerCase()) != -1) {
            gSearchVersion = 6;
            if (instructions.indexOf(VERIFY5.toLowerCase()) != -1) gSearchVersion = 5;
        }
        if (gSearchVersion!==0) {
            if (gDebugging && gLogging) console.log("..Found crowdsource version " + gSearchVersion);
            window.addEventListener("load", function(){ 
                enableTextSelections("text-rep");
                getGoogleDomain();
                taskSearchButtons();
            }, false);
        }
    } else if (gLocation.search(/^http.?:\/\/[^.]*\.google\./i) != -1 ) {
        var myInfo = -1;
        if ( (myInfo = gLocation.indexOf("jrio=feetwalk")) != -1) {
            gTaskNumber = gLocation.substr(myInfo).split("&")[1].substr(4);
            window.addEventListener("load", function(){
                window.addEventListener("message", function(e){ if ( verifyMessage(e) ) otherListener(e); }, false);
                var theData = dataFill( "initialize google", gTaskNumber );
                parent.window.opener.postMessage(theData,"*");
            }, false);
        }
    } else if (gHostName=="mturk.com") {
        window.addEventListener("message", function(e){ if ( verifyMessage(e) ) mainListener(e); }, false);
    } else {
        window.addEventListener("load", function(){
            window.addEventListener("message", function(e){ if ( verifyMessage(e) ) otherListener(e); }, false);
            var theData = dataFill( "initialize the question" );
            parent.window.opener.postMessage(theData,"*");
        }, false);
    }
}
长期地址
遇到问题?请前往 GitHub 提 Issues,或加Q群1031348184

赞助商

Fishcpy

广告

Rainyun

注册一下就行

Rainyun

一年攒够 12 元