// ==UserScript==
// @name JR Crowdsource keyword/ranking mturk.com scripts
// @version 0.84
// @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 (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.80 Added options for popup windows and changes for instruction box. A few bugs have been fixed as well. Yahoo and image searches added.
// -- New options that can be changed:
// [POPUPWINDOW] will open the search page in a window instead of a tab. [CLOSEPOPUPAFTER] will close popup window after every task is finished.
// You can have the window not close so it will be opened with every task and each hit. The window is best put on the left or right side of the screen
// or even on a second monitor. [GOTONEXTTASK] will automatically open next search page until all tasks are done. There are options to change
// the width and font sizes of the instruction box. [INSTRUCTIONSOFF] will not show the instruction box at the page start. F9 will bring it back.
// [INSTRUCTIONSSMALL] will only show the relevant information needed without the instructions for less space covered up.
// -- 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.
// -- Yahoo search (rare):
// It will also work exactly the same way as Google on the Yahoo searches but they don't have a lot available.
// -- Image search:
// This will now work with the image searches. There will be a thumbnail of the picture to search for in the instruction box. Usually the script can
// find the image by itself because it matches the picture location. If it can't it will label the images that are on the same domain names and you
// will have to find the matching image yourself. Click the image and then click visit page button.
// -- Compatible with these versions of hits:
// ==== Search: Keywords on Google......
// ==== Search: Location and Keywords 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.
// - John Ramirez / Email: [email protected]
// ------------------- CONSTANT VARIABLES - options --------------
var INSTRUCTIONBOXWIDTH = 460; // The width size of the instructionbox if you need it to be bigger or smaller.
var INSTRUCTIONFONTSIZE = 12; // The font size of the text in the instructionbox if you need it to be larger or smaller.
var INSTRUCTIONSOFF = false; // Instruction box will turn itself off at the beginning for faster answers with keyboard shortcuts.
var INSTRUCTIONSSMALL = false; // Show only information needed in instruction box so it doesn't cover up a large portion of screen.
var POPUPWINDOW = false; // Opens window in a popup window instead of a tab. Remember to allow pop ups or it won't show up.
var CLOSEPOPUPAFTER = true; // Allows the popup window to be closed after finishing hit.
var GOTONEXTTASK = true; // This will make it so the script goes to the next task after you finish a task.
// ----- Debugging options No reason to change ---------
var ONPREVIEW = false; // Allows search buttons to work in preview mode. Mostly for testing purposes.
var gLogging = false, gDebugging = false; // Gives lot of info in the console log for debugging purposes mostly.
// ---------------------------------------------------------------
var VERSION = [];
var PREVIEW1 = "You are currently in preview mode";
var MYVERIFY = "feetsmell"; // used for all my scripts to verify messages originating from my script.
var SCRIPTTAG = "JRCRK"; // Used for a unique tag for each script I make. Used in messaging and variables passing.
VERSION[1] = ["copy and paste the url of the most relevant result","Search: Keywords on Google","CrowdSource"];
VERSION[2] = ["return information about a keyword search in","Search: Keywords on Google","CrowdSource"];
VERSION[3] = ["record a url's search ranking on","Search: Ranking of a Url on Google","CrowdSource"];
VERSION[4] = ["open google.cz, and search the provided keyword","","CrowdSource"];
VERSION[5] = ["The information below will help clarify the instructions that are in each HIT.","","CrowdSource"];
VERSION[6] = ["Click \"Search Tools\" then \"Search near...\"","Search: Location and Keywords on Google","CrowdSource"];
VERSION[7] = ["The information below will help clarify the instructions that are in each HIT.","Search: Keywords on Google","CrowdSource"];
VERSION[8] = ["keyword search in Yahoo","","CrowdSource"];
VERSION[9] = ["Review the image in the task and find that same image on the Google Images page.","Search: Keywords on Google (9)","CrowdSource"];
VERSION[10] = ["Search each keyword in Google.co.uk, find the associated image, and follow the unique instructions.","Search: Image URL on Google.co.uk (7.1)","CrowdSource"];
VERSION[11] = ["Open Google.com and search Keyword 1.","Search: Keywords on Google.com (10)","CrowdSource"];
var gSearchURLs = [], gTaskNumber = 0, gQuestions = [], gTag = -1, gSearchVersion = 0, gRemoteUrl = false, gSearchUrl = "";
var gSearchDomain = "google.com", gKbShortcutFired = false, gMyInstructionsBox = null, gLocation = document.URL.toString();
var gHostName="", gZipCodes=[], gTheKeyword=[], gDefaultPage = "http://www.allbyjohn.com/blank.html?JRnewpage=now&ST=" + SCRIPTTAG;
var gPingAccepted = false, gUrl = gDefaultPage, gTimeout = null, gPopUpWindow = null, gInstructionHover = false, gTasksFinished = false;
if (typeof console.log !== 'function') { gDebugging=false; gLogging=false; }
else { gLogging = (gLogging) ? gLogging : gDebugging; }
function queryToAssoc(queryArray) {
var splits = null;
var returnAssoc = {};
for (var i = 0, len=queryArray.length; i < len; i++) {
splits = queryArray[i].split("=");
returnAssoc[splits[0]] = splits[1];
}
return returnAssoc;
}
var gHostName = getHostName(gLocation);
var queryString = (window.location.search).substring(1); // Get the querystring from current location removing the ? at front.
var gQueryAssoc = queryToAssoc(queryString.split("&")); // split querystring into an associative array with variables.
function isGoogle() { return gLocation.search(/^http.?:\/\/[^.]*\.google\./i) != -1 ? true : false; }
function isYahoo() { return gLocation.search(/^http.?:\/\/[^.]*\.yahoo\./i) != -1 ? true : false; }
function isBing() { return gLocation.search(/^http.?:\/\/[^.]*\.bing\./i) != -1 ? true : false; }
function isMturk() { return gLocation.search(/^http.?:\/\/[^.]*\.mturk\./i) != -1 ? true : false; }
function isCrowdsource() { return gLocation.search(/^http.?:\/\/[^.]*\.crowdsource\./i) != -1 ? true : false; }
function isHitPage() { return gLocation.search(/^http.?:\/\/work\.crowdsource\.com\/amt\/view/i) != -1 ? true : false; }
function isStartPage() { return gLocation.indexOf(gDefaultPage) != -1 ? true : false; }
function isJRIO() { return (gQueryAssoc["jrio"] == "feetwalk") ? true : false; }
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.isSearch = function(searchEngine) {
if (searchEngine=="yahoo" && isYahoo()) return true;
else if (searchEngine=="bing" && isBing()) return true;
else if (searchEngine=="google" && this!=8) return true;
else return false;
};
Number.prototype.isQuestionVersion = function() {
if (this==2 || this==3 || this==5 || this==7 || this==6 || this==8 || this==9 || this==10 || this==11) 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.isSearchQuestion = function() {
if (this==7 || this==5 || this==8 || this==11) return true;
else return false;
};
Number.prototype.isImageSearch = function() {
if (this==9 || this==10) return true;
else return false;
};
Number.prototype.isDoubleKeyword = function() {
if (this==11) 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, "scriptTag": SCRIPTTAG, "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.scriptTag === SCRIPTTAG) return true;
else return false;
}
function urlMatch(url1, url2) {
if(typeof(url1)==='undefined' || typeof(url2)==='undefined') return 0;
url1 = unescape(url1).toLowerCase();
url2 = url2.toLowerCase();
var hostName1 = getHostName(url1);
var hostName2 = getHostName(url2);
var domainName1 = getDomainName(hostName1);
var domainName2 = getDomainName(hostName2);
url1 = url1.replace(/(^http.?:\/\/)|(\/$)|(www\.)/g,'');
url2 = url2.replace(/(^http.?:\/\/)|(\/$)|(www\.)/g,'');
if ( url1 == url2 ) return 1;
else if ( hostName1 == hostName2 ) return 2;
else if ( domainName1 == domainName2 ) return 3;
else return 0;
}
function createMyElement(elementName,theClass,theId,theName,theText,theStyle) {
var theElement = document.createElement(elementName);
if (theClass) theElement.className = theClass;
if (theId) theElement.id = theId;
if (theName) theElement.name = theName;
if (theStyle) theElement.setAttribute("style",theStyle);
if (theText) theElement.innerHTML = theText;
return theElement;
}
function createButton(theClass,theId,theName,theValue,theStyle) {
var theButton = createMyElement("input",theClass,theId,theName,"",theStyle);
theButton.type = "button";
if (theValue) theButton.value = theValue;
return theButton;
}
function createTextInput(theClass,theId,theName,theValue,theStyle) {
var theInput = createMyElement("input",theClass,theId,theName,"",theStyle);
theInput.type = "text";
if (theValue) theInput.value = theValue;
return theInput;
}
function createLink(theClass,theId,theName,theUrl,theTitle,theText,theTarget,theStyle) {
var theLink = createMyElement("a",theClass,theId,theName,theText,theStyle);
theLink.setAttribute("href",theUrl);
theLink.title = theTitle;
if (theTarget) theLink.setAttribute("target",theTarget);
return theLink;
}
function createDiv(theClass,theId,theName,theText,theStyle) {
var theDiv = createMyElement("div",theClass,theId,theName,theText,theStyle);
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() {
gMyInstructionsBox = $('#myInstructionsBox');
gKbShortcutFired = false;
gMyInstructionsBox.stop (true, false).fadeTo (50, 1 );
}
function textInputFocusout() {
gMyInstructionsBox = $('#myInstructionsBox');
if ( !gMyInstructionsBox.is(":hover") ) gMyInstructionsBox.stop (true, false).fadeTo (2900, 0.1);
}
function searchInnerText(node,theText) { return node.innerHTML.indexOf(theText); }
function searchInNode(theNode,theText) {
if (theNode) {
return ( (retVal=searchInnerText(theNode,theText)) != -1) ? theNode.innerHTML.substr(retVal) : null;
} else return null;
}
function searchInAllElements(theNode,theElement,theText) {
var tagNodes = theNode.getElementsByTagName(theElement);
var i=0, found=false, returnvar=null;
while (tagNodes[i] && !found) {
found = ((returnvar = searchInNode(tagNodes[i],theText)) === null) ? false : true;
if (!found) i++;
}
return (found) ? tagNodes[i] : null;
}
function setArrayPointersElement(theNode,searchData) {
var arr=[], temp={}, tagNodes = null;
for (var index = 0, len=searchData.length; index < len; index++) {
if (searchData[index]) {
if (searchData[index].type == "tagName") { tagNodes = theNode.getElementsByTagName(searchData[index].tag); }
if (searchData[index].type == "className") tagNodes = theNode.getElementsByClassName(searchData[index].tag);
if (searchData[index].type == "id") tagNodes = [theNode.getElementById(searchData[index].tag)];
if (tagNodes) {
for (var i = 0, NodesLen=tagNodes.length; i < NodesLen; i++) {
if ( tagNodes[i].innerHTML.indexOf(searchData[index].search) !== -1 ) {
temp = {position:i,node:tagNodes[i],next:tagNodes[i+1]};
arr.push(temp);
break;
}
}
}
}
}
return arr;
}
function fadeOut( elem, toOpacity, time ) {
var startOpacity = elem.style.opacity || 1;
elem.style.opacity = startOpacity;
(function go() {
if (gInstructionHover) return;
elem.style.opacity -= (startOpacity / ( time / 100 ));
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')'; // for IE
if( elem.style.opacity > toOpacity ) setTimeout( go, 100 );
else {
elem.style.opacity = toOpacity;
}
})();
}
function fadeIn( elem, fromOpacity, time ) {
var startOpacity = elem.style.opacity || fromOpacity;
elem.style.opacity = startOpacity;
(function go() {
var newNumber = parseFloat(elem.style.opacity)+(1 / ( time / 100 ));
elem.style.opacity = newNumber;
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')'; // for IE
if (elem.style.opacity < 1) setTimeout( go, 100 );
else {
elem.style.opacity = 1;
}
})();
}
function attrInstructionsBox() {
gMyInstructionsBox = $('#myInstructionsBox');
/*jshint multistr: true */
GM_addStyle ( " \
#myInstructionsBox { \
position: fixed !important; \
top: 100px; \
margin: 1px; \
padding: 2px 6px 10px 10px; \
background: #0B0B3B; \
width: " + INSTRUCTIONBOXWIDTH + "px; \
z-index: 99999; \
opacity: 1.0; \
color: #F7F8E0; \
text-align: left; \
line-height: 18px; \
font-family: Helvetica,Arial,Sans-Serif; \
cursor: move; \
font-size: " + INSTRUCTIONFONTSIZE + "px; \
font-weight: normal; \
background-color: grey; \
} \
#myInstructionsBox p { \
font-size: " + (INSTRUCTIONFONTSIZE+2) + "px; \
} \
#myInstructionsBox #myInstructions { \
font-size: " + (INSTRUCTIONFONTSIZE+1) + "px; \
color: #F7F8E0; \
padding: 2px 0 10px 8px; \
margin: 2px 5px; \
line-height: normal; \
} \
#myInstructionsBox #theQuestion { \
font-size: " + (INSTRUCTIONFONTSIZE+4) + "px; \
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: " + (INSTRUCTIONFONTSIZE+2) + "px; \
border: none; \
font-family: Helvetica,Arial,Sans-Serif; \
width: auto; \
} \
#myInstructionsBox .myTextInput { \
font-size: " + (INSTRUCTIONFONTSIZE+2) + "px; \
padding: 1px 2px 3px 2px; \
color: black; \
width: 440px; \
height: 16px; \
} \
#myInstructionsBox ul { \
margin: 0; \
} \
#myInstructionsBox input { \
margin: 2px; \
color: #000000; \
font-size: " + (INSTRUCTIONFONTSIZE+4) + "px; \
padding: 1px 6px; \
} \
#myInstructionsBox a { \
color: white; \
} \
" );
if (gLocation.indexOf("google.ae") != -1) document.getElementById("myInstructionsBox").style.left = "0";
else document.getElementById("myInstructionsBox").style.right = "0";
gKbShortcutFired = false;
//-- Fade panel when not in use
gMyInstructionsBox.hover (
function () {
this.style.opacity = "1";
gInstructionHover = true;
},
function () {
if ( !$("#enterAnswer").is(":focus") ) {
gInstructionHover = false;
if (this.style.opacity == 1) fadeOut(this, 0.1, 2500);
}
}
);
document.getElementById("theQuestion").onmouseover = function() { gMyInstructionsBox.draggable("destroy"); };
document.getElementById("theQuestion").onmouseout = function() { gMyInstructionsBox.draggable(); };
gMyInstructionsBox.draggable();
}
function setupKeyDown(theDocs,name) {
theDocs.onkeydown = function (e) {
if (e.keyCode == 120) { // F9 to toggle box
gKbShortcutFired = (gKbShortcutFired) ? false : true;
if (gKbShortcutFired) {
document.getElementById("myInstructionsBox").style.opacity = "0.1";
document.getElementById("myInstructionsBox").style.display = "none";
} else {
document.getElementById("myInstructionsBox").style.display = "block";
document.getElementById("myInstructionsBox").style.opacity = "1";
fadeOut(document.getElementById("myInstructionsBox"), 0.1, 2500);
}
e.preventDefault ();
e.stopPropagation ();
return false;
}
if (e.target.id !="enterAnswer") {
if (name == "other") {
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 && CLOSEPOPUPAFTER) self.close(); // p = close this window.
if (e.keyCode == 78) { // n = Can't find URL.
if (!gSearchVersion.isSearchQuestion()) answerNone();
else foundNone();
}
}
} else if ( e.keyCode == 13 ) answerInput(); // enter in input text will submit input value.
};
}
function createInstructionsBox(name,instructions,question,answer) {
var frag = document.createDocumentFragment();
if (CLOSEPOPUPAFTER || name == "other") {
var closeButton = createButton("myButton","closeMe","","Close Page");
closeButton.onclick = function () {
if (name == "other") location.replace(gSearchUrl);
else self.close();
};
}
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 = "(E)dit Answer:<br>";
answerDiv.appendChild(textInput);
answerDiv.appendChild(submitButton);
if (name == "search") {
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");
if (!gSearchVersion.isSearchQuestion()) {
questionDiv.innerHTML = "URL: " + gSearchURLs[0];
if (gSearchVersion.isImageSearch()) {
questionDiv.innerHTML = "Look for this image anywhere on page:<br><img src='" + gSearchURLs[0] + "' width=160px><br>" + gQuestions[0];
} else {
noneButton.onclick = function () { answerNone(); };
controlsDiv.appendChild(noneButton);
}
} else {
noneButton.onclick = function () { foundNone(); };
controlsDiv.appendChild(noneButton);
}
}
if (!gSearchVersion.isQuestionVersion() || gSearchVersion.isSearchQuestion()){
questionDiv.innerHTML = "Question: " + question;
if (gSearchVersion.isDoubleKeyword()) { questionDiv.innerHTML = "Click on the select button of the first result which is not an AD."; }
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","","(W)eb Url");
urlButton.onclick = function () { answerURL(); };
var selButton = createButton("myButton","selAnswer","","(S)election");
selButton.onclick = function () { answerSel(); };
controlsDiv.innerHTML = "Answer: ";
controlsDiv.appendChild(selButton);
controlsDiv.appendChild(urlButton);
}
if (CLOSEPOPUPAFTER) controlsDiv.appendChild(closeButton);
if (!INSTRUCTIONSSMALL) instructionsBox.appendChild(instructionsH3);
if (!INSTRUCTIONSSMALL) instructionsBox.appendChild(controlsDiv);
instructionsBox.appendChild(questionDiv);
instructionsBox.appendChild(respondDiv);
if (name=="other" ) instructionsBox.appendChild(answerDiv);
frag.appendChild(instructionsBox);
document.body.appendChild(frag);
textInput.onfocus = function(){ textInputFocus(); };
textInput.onblur = function(){ textInputFocusout(); };
attrInstructionsBox();
if (gSearchVersion.isImageSearch() && isGoogle()) {
instructionsBox.style.left = "0px";
instructionsBox.style.right = "auto";
}
if (INSTRUCTIONSOFF && (!gSearchVersion.isImageSearch() || (gSearchVersion.isImageSearch() && answer !== ""))) {
instructionsBox.style.opacity = "0";
gKbShortcutFired = false;
}
setupKeyDown(document,name);
}
function doSecondKeyword() {
var secondKeyword = gQuestions[0].replace("Keyword 2:","").trim().replace(/\s+/g,"+");
setTimeout(function(){
var searchURL = "/search?ion=0&num=10&q=" + secondKeyword + "&jrio=feetwalk&2key=1&ttt=" + gTaskNumber;
location.replace(searchURL);
}, 2000);
}
function doZipCode() {
var divTools = document.getElementById("hdtb_tls");
divTools.click();
setTimeout(function(){
var zipTextNodes = document.getElementsByClassName("hdtb-mn-hd");
var zipTextDiv = zipTextNodes[zipTextNodes.length-1];
if (zipTextDiv.innerHTML.indexOf(gZipCodes[0])==-1) {
zipTextDiv.click();
setTimeout(function(){
var divZipCode = document.getElementById("_Zpd");
var zipCodeInput = document.getElementById("lc-input");
var zipCodeSubmit = divZipCode.getElementsByClassName("ksb")[0];
zipCodeInput.value = gZipCodes[0];
zipCodeSubmit.click();
}, 2000);
} else doSearchButtons();
}, 2000);
}
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(/&/,"%26");
else retText = retText.replace(/&/g,"&");
}
return retText;
};
function getSearchDomain() {
if (gSearchVersion===0) return;
var title = removeHTMLTags(document.getElementsByClassName("projectTitle")[0].innerHTML);
if (title.length>0) {
if (title!="Search: Ranking of a Url" && title.indexOf("Search: Loc & Keyword - Google Acct Required") == -1) {
title = title.replace("Search: Keywords on ","");
title = title.replace("Search: Ranking of a Url on ","");
title = title.replace("Search: Location and Keywords on ","");
title = title.replace("Search: Image URL on ","");
var splitTitle = title.split(' ');
gSearchDomain = splitTitle[0].toLowerCase();
}
}
}
function getYahooResultsPointer() {
var webResults = document.getElementById("web");
var results = webResults.getElementsByTagName("ol")[0].children;
var pointers=[];
if (results.length>0) {
for (var i = 0, len=results.length; i < len; i++) {
var theLink = results[i].getElementsByTagName("a")[0];
if (theLink.id == "link-" + (i+1)) {
pointers.push(results[i]);
}
}
}
return pointers;
}
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("st").length>0 &&
(results[i].getElementsByClassName("_YM").length===0 || results[i].getElementsByClassName("_Rm").length>0) &&
results[i].getElementsByClassName("kno-fb").length===0) {
pointers.push(results[i]);
}
}
}
return pointers;
}
function getBingResultsPointer() {
var results = document.getElementsByClassName("b_algo");
var i=0, pointers=[];
if (results.length>0) {
for (var i = 0, len=results.length; i < len; i++) {
pointers.push(results[i]);
}
}
return pointers
}
function getGoogleImagesPointer() {
var pointers=[];
var imageContainer = document.getElementById("rg");
if (imageContainer) {
var imageResults = imageContainer.getElementsByClassName("rg_di");
if (imageResults.length>0) {
for (var i = 0, len=imageResults.length; i < len; i++) {
var theLink = imageResults[i].getElementsByTagName("a")[0];
pointers.push(imageResults[i]);
}
}
}
return pointers;
}
function doSearchButtons() {
var urlPointers = [];
if (isYahoo()) urlPointers = getYahooResultsPointer();
else if (isBing()) urlPointers = getBingResultsPointer();
else if (gSearchVersion.isImageSearch()) {
var imageBlocks = document.getElementsByClassName("rg_fbl");
for (var i = 0, len=imageBlocks.length; i < len; i++) {
var blockUrl = imageBlocks[i].getAttribute("href");
imageBlocks[i].setAttribute("href",blockUrl + "&jrio=feetwalk&ttt=" + gTaskNumber);
}
urlPointers = getGoogleImagesPointer();
}
else urlPointers = getGoogleResultsPointer();
var theAnswer = "", url="", pageRankText="", totalResults = "", totalTime = "";
if (gSearchVersion.isSearch("google")) {
var resultStatsNode = document.getElementById("resultStats");
var resultStats = (resultStatsNode) ? resultStatsNode.innerHTML.split(" ") : [];
var resultStatsStart = 1;
if (resultStats.length > 0) {
if (resultStats[0] != "About") resultStatsStart = 0;
totalResults = resultStats[resultStatsStart] + " " + resultStats[resultStatsStart+1].replace("<nobr>","").trim();
totalTime = resultStats[resultStatsStart+2].substr(1) + " " + resultStats[resultStatsStart+3].split(")")[0];
}
}
if (gSearchVersion.isSearchQuestion()) {
var searchTitle = (gQuestions[0].toLowerCase().search("return the title of the") != -1) ? true : false;
var searchDescription = (gQuestions[0].toLowerCase().search("return the description of the") != -1) ? true : false;
var searchUrl = ( (gQuestions[0].toLowerCase().search("return the url of the") != -1) ||
(gQuestions[0].toLowerCase().search("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++) {
url = urlPointers[i].getElementsByTagName("a")[0];
if (gSearchVersion.isImageSearch()) {
var topDiv = createDiv("myDiv","imageDiv-" + i,"","","text-align:center;");
var imgurlText = url.getAttribute("href");
var imgNode = urlPointers[i].getElementsByTagName("img")[0];
var imgurlIndex = imgurlText.indexOf("imgurl=");
imgurlText = imgurlText.substring(imgurlIndex+7).split("&")[0];
matching = urlMatch( unescape(imgurlText), gSearchURLs[0] );
if ( matching == 1 ) {
theAnswer = "Exact Image";
topDiv.innerHTML = "Exact Image";
imgNode.parentNode.insertBefore(topDiv,imgNode);
url.click();
} else if ( matching == 2 ) {
topDiv.innerHTML = "Same Hostname";
imgNode.parentNode.insertBefore(topDiv,imgNode);
} else if ( matching == 3 ) {
topDiv.innerHTML = "Same Domain Name";
imgNode.parentNode.insertBefore(topDiv,imgNode);
}
} else {
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 + "," + (i+1);
matching = urlMatch( url.getAttribute("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="MediumOrchid";
btn.style.color="#FFFFFF";
}
btn.style.fontSize="small";
btn.onclick = function() {
var splitName = this.name.split(',');
var theIndex = parseInt(splitName[3])-1, results = [], theDescription = "", theTitle = "";
if (isYahoo()) {
results = getYahooResultsPointer();
theDescription = removeHTMLTags(results[theIndex].getElementsByClassName("abstr")[0].innerHTML);
} else if (isBing()) {
results = getBingResultsPointer();
theDescription = removeHTMLTags(results[theIndex].getElementsByTagName("p")[0].innerHTML);
} else {
results = getGoogleResultsPointer();
var theDescriptionNodes = results[theIndex].getElementsByClassName("st");
if (theDescriptionNodes.length>0) theDescription = removeHTMLTags(theDescriptionNodes[0].innerHTML);
}
var theUrl = results[theIndex].getElementsByTagName("a")[0];
theTitle = removeHTMLTags(theUrl.innerHTML);
var theData = null;
if (gSearchVersion.isQuestionVersion() && !gSearchVersion.isSearchQuestion()) {
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.getAttribute("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.getAttribute("href") );
parent.window.opener.postMessage(theData,"*");
}
};
if (gSearchVersion.isSearchQuestion() && pageNum>1) pageRankText = "Page: " + pageNum + "- Rank: " + rankNum + " ";
else if (gSearchVersion.isSearchQuestion()) pageRankText = "Rank: " + rankNum + " ";
url.parentNode.insertBefore(document.createTextNode(pageRankText),url);
url.parentNode.insertBefore(btn,url);
if (gSearchVersion.isSearchQuestion()) url.parentNode.insertBefore(createMyElement("br"),url);
rankNum++;
if ( rankNum>10 ) {
rankNum=1; pageNum++;
}
}
}
var myInstructions = "[ p to go back ]<br>";
if (gSearchVersion.isQuestionVersion() && !gSearchVersion.isSearchQuestion() && !gSearchVersion.isImageSearch())
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].toLowerCase().search("please return the number of results") != -1) theAnswer = totalResults;
else if (gQuestions[0].toLowerCase().search("return the time google took to complete the search") != -1) theAnswer = totalTime;
createInstructionsBox("search",myInstructions,gQuestions[0],theAnswer);
gMyInstructionsBox.focus();
}
function taskSearchButtons() {
if (gSearchVersion===0) return;
var tasks = document.getElementsByClassName("task cf"), keywordArea = "";
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>');
if (gSearchVersion.isDoubleKeyword()) keywordArea = splitTextRep[0];
else keywordArea = (splitTextRep[0].toLowerCase().indexOf("keyword:") != -1) ? splitTextRep[0] : splitTextRep[1];
gTheKeyword[i+1] = (gSearchVersion.isDoubleKeyword()) ? keywordArea.getTextAfter("keyword 1:"): keywordArea.getTextAfter("keyword:");
var btn = createButton("myButton","searchBut" + (i+1),"B," + (i+1),"Search");
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 {
var theKeyword = gTheKeyword[(i+1)].replace(/\s+/g,"+");
var showResults = 50, theSearchUrl = "";
if (gSearchVersion.isSearchQuestion()) showResults = 10;
var imageSearch = (gSearchVersion.isImageSearch()) ? "&tbm=isch" : "";
if (gSearchDomain == "yahoo.com") theSearchUrl = "https://search." + gSearchDomain + "/search?n=100&p=" + theKeyword +
"&jrio=feetwalk&ttt=" + (i+1)
else if (gSearchDomain == "bing.com") theSearchUrl = "http://www." + gSearchDomain + "/search?count=" + showResults + "&q=" + theKeyword + "&jrio=feetwalk&ttt=" + (i+1);
else theSearchUrl = "http://www." + gSearchDomain + "/search?ion=0&num=" + showResults + "&q=" + theKeyword +
imageSearch + "&jrio=feetwalk&ttt=" + (i+1);
btn.setAttribute("searchUrl", theSearchUrl);
btn.onclick = function() {
var splitName = this.name.split(',');
gSearchUrl = this.getAttribute("searchUrl");
gTaskNumber = splitName[1];
var theData = dataFill( "open page", gSearchUrl, true, JSON.stringify([gSearchVersion, gSearchURLs[gTaskNumber], gQuestions[gTaskNumber],
gZipCodes[gTaskNumber], gTheKeyword[gTaskNumber] ,gTaskNumber]) );
window.parent.postMessage(theData,"*");
};
}
if (gSearchVersion.isQuestionVersion()) { // Version 2, 3, 5 and 7 needs the URL and question.
var theZipCode="";
var theURL="";
var theQuestion="";
if (!gSearchVersion.isImageSearch() && splitTextRep.length>1) {
theURL = splitTextRep[1];
theQuestion = "Click Url and record one sentence on webpage that relates to the keyword: " + gTheKeyword[i+1];
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 if (!gSearchVersion.isImageSearch()) {
var x=1;
if (gSearchVersion.isZipCodeVersion()) {
theZipCode = theTextReps[x++].innerHTML;
theZipCode = theZipCode.getTextAfter("zipcode:");
theZipCode = theZipCode.getTextAfter("Location (Zipcode or City, State):");
}
if (!gSearchVersion.isSearchQuestion() && !gSearchVersion.isImageSearch()) theURL = theTextReps[x++].innerHTML;
if (!gSearchVersion.isImageSearch()) theQuestion = theTextReps[x++].innerHTML.replace("Instructions: ","").trim();
theTextReps[0].appendChild(btn);
} else {
var theImageNodes = tasks[i].getElementsByClassName("img cf");
var theQuestionNodes = tasks[i].getElementsByClassName("fld-textarea");
var theImages = theImageNodes[0].getElementsByTagName("img");
theURL = theImages[0].src;
theQuestion = (theQuestionNodes>0) ? theQuestionNodes[0].getElementsByTagName("label")[0].innerHTML : tasks[i].getElementsByClassName("fld-paragraph")[0].innerHTML;
theTextReps[0].appendChild(btn);
}
theURL = theURL.getTextAfter("url:",false);
gSearchURLs[i+1] = theURL;
gQuestions[i+1] = theQuestion;
gZipCodes[i+1] = theZipCode;
} else {
theTextReps[0].appendChild(btn);
gQuestions[i+1] = "Select the most relevant result for the keyword: " + gTheKeyword[i+1];
}
}
}
function initializeYahoo(theTaskNumber) {
var theData = dataFill( "find yahoo question", gSearchVersion, "", gQuestions[0],
gZipCodes[0], gTheKeyword[0] ,theTaskNumber );
gPopUpWindow.postMessage(theData,"*");
}
function initializeBing(theTaskNumber) {
var theData = dataFill( "find bing question", gSearchVersion, "", gQuestions[0],
gZipCodes[0], gTheKeyword[0] ,theTaskNumber );
gPopUpWindow.postMessage(theData,"*");
}
function initializeGoogle(theTaskNumber) {
var theData = null;
if (gSearchVersion.isSearchQuestion())
theData = dataFill( "find google question", gSearchVersion, "", gQuestions[0],
gZipCodes[0], gTheKeyword[0] ,theTaskNumber );
else if (gSearchVersion.isQuestionVersion())
theData = dataFill( "search url", gSearchVersion, gSearchURLs[0], gQuestions[0],
gZipCodes[0], gTheKeyword[0] ,theTaskNumber );
else theData = dataFill( "find best url", gSearchVersion, "", gQuestions[0], "", "", theTaskNumber );
gPopUpWindow.postMessage(theData,"*");
}
function initializeQuestion() {
var theData = dataFill( "answer question", gSearchVersion, gUrl, gQuestions[0], "",
gTheKeyword[0] ,gTaskNumber );
gPopUpWindow.postMessage(theData,"*");
}
function openPageData(theData) {
var taskData = JSON.parse(theData);
gSearchVersion = taskData[0];
gSearchURLs[0] = taskData[1];
gQuestions[0] = taskData[2];
gZipCodes[0] = taskData[3];
gTheKeyword[0] = taskData[4];
gTaskNumber = taskData[5];
}
// ********************* Start remote window listeners and functions *********************
function openPopWindow(theUrl,theTarget) { // Opens window with half the width of the screen and less than 200 pixels from the height on left side of screen.
var popupFound = false; // chrome doesn't work with try and catch as well as firefox when permissions are wrong.
try { // try to change the location of the popup window. If I can't then make a new popup.
if (!gPopUpWindow.closed) { // check to see if popup window is closed.
gPopUpWindow.location = theUrl; // Changes the url in the popup window. May work as long as window remembers popup reference.
popupFound = true; // Popup window is opened and location should have been changed.
}
}
catch(err) { // If can't change url in popup window because of permission failure then open another popup window.
popupFound = false; // Make sure to open window because of a permission error. Not really needed but needed something in the catch area.
}
if (!popupFound) { // This was needed for chrome because it didn't catch the permission error on location changing.
if (CLOSEPOPUPAFTER && gPopUpWindow) gPopUpWindow.close(); // Close the remote window if it's up because I can't use it.
var halfScreen = screen.width-400; // Make window 400 pixels less than the width of screen.
var windowHeight = screen.height - 200; // The height is just 200 pixels less than the regular height to make it stand out.
var specs = ",resizable=yes,scrollbars=yes,toolbar=yes,status=yes,menubar=0,titlebar=yes"; // Normal specifications for a window.
if (POPUPWINDOW) gPopUpWindow = window.open(theUrl,theTarget,'height=' + windowHeight + ',width=' + halfScreen + ', left=0,top=0' + specs,false); // open remote window on left side.
else gPopUpWindow = window.open(theUrl,theTarget); // open remote window in a tab.
}
}
function mainListener(e) {
// Used to send messages from the iframe to the remote window. Can also be used if their is no iframe.
// If no iframe then just call this function instead of sending a message to the top window.
gHitAccepted = searchInAllElements(document,"td","Finished with this HIT?"); // Checks for this text to find out if his has been accepted.
if (e.data.action == "open page") { // A message is sent to open a page in the remote window.
if (gDebugging && gLogging) console.log("..Main got Open Page: " + gTag + " hitAccepted: " + gHitAccepted + " url: " + e.data.data1);
if (e.data.data2 || gHitAccepted || ONPREVIEW) gUrl = e.data.data1; // save the url so it can be used when it gets a ping from the remote window.
else gUrl = gDefaultPage + "&action=notaccepted"; // Use the defaultpage if hit isn't accepted so it won't be confusing.
gTag = e.data.tag; // Sets the tag from the hit in the iframe.
openPageData(e.data.data3); // Sets up the global variables for the data passed so I can pass it on to the remote window.
// Don't go to url when it wasn't clicked and hit isn't accepted. e.data.data2 is true when a user clicks on links. So window
// won't open on a hit that isn't accepted yet but a user can still click links to try if the hit might be easy to do.
var theAction = (gHitAccepted) ? "accepted" : (e.data.data2) ? "clicked" : "notaccepted"; // Find out if link was clicked or not.
if (theAction != "notaccepted") openPopWindow(gUrl,"remotewindow"); // Open the url if it's accepted or clicked without going to default page first.
else openPopWindow(gDefaultPage + "&action=" + theAction,"remotewindow"); // Open remote window but if it's already opened it will leave it opened.
} else if (e.data.action == "what page") { // received a what page message from remote window.
if (gDebugging && gLogging) console.log("..Main got What Page: " + gTag + " gUrl: " + gUrl);
if (e.data.tag == gTag) { // Make sure this message is from a window with the same tag as the window that opened me first.
var theData = dataFill("go to page", gUrl); // Send the real Url to the remote window.
gPopUpWindow.postMessage(theData,"*"); // post the message to window opened.
}
} else if (e.data.action == "ping") { // received a ping from remote window.
if (isMturk()) { // check if this page is the mturk page which it should be anyway.
if (!gPingAccepted) { // If ping hasn't been seen then get the source pointer to remote window.
if (gDebugging && gLogging) console.log("..Main got Ping: " + gTag + " e.data.tag: " + e.data.tag + " gUrl: " + gUrl);
gPopUpWindow = e.source; // Grab the ping source for future use so I can change location of remote window.
gPingAccepted = true; // Ping is now accepted.
if (gTimeout) clearTimeout(gTimeout); // remove the timeout so it won't create a new remote window.
}
if (gUrl != gDefaultPage) { // make sure the url is not the default page.
var theData = dataFill("pong", gUrl); // Send a pong message back to start page change process.
gPopUpWindow.postMessage(theData,"*"); // post the message to window opened.
}
}
} else if (e.data.action == "initialize google") { // Got a message to initialize for a Google page.
if (gDebugging && gLogging) console.log("..Main got initialize Google: " + e.data.tag + " gUrl: " + gUrl); //Just for debugging
if (e.data.tag == -1) { // Check if tags match so no other windows can control me.
gPopUpWindow = e.source; // Grab the ping source for future use so I can send messages to remote window.
initializeGoogle(e.data.data1); // initialize stuff for the Google page in the remote window.
}
} else if (e.data.action == "initialize bing") { // Got a message to initialize for a Bing page.
if (gDebugging && gLogging) console.log("..Main got initialize Bing: " + e.data.tag + " gUrl: " + gUrl); //Just for debugging
if (e.data.tag == -1) { // Check if tags match so no other windows can control me.
gPopUpWindow = e.source; // Grab the ping source for future use so I can send messages to remote window.
initializeBing(e.data.data1); // initialize stuff for the Google page in the remote window.
}
} else if (e.data.action == "initialize yahoo") { // Got a message to initialize for a Yahoo page.
if (gDebugging && gLogging) console.log("..Main got initialize Yahoo: " + gTag + " gUrl: " + gUrl); //Just for debugging
if (e.data.tag == -1) { // Check if tags match so no other windows can control me.
initializeYahoo(e.data.data1); // initialize stuff for the Yahoo page in the remote window.
}
} else if (e.data.action == "initialize the question") { // Got a message to set up the question for remote window.
if (gDebugging && gLogging) console.log("..Main got initialize the question: " + gTag + " remoteUrl: " + gRemoteUrl); //Just for debugging
if (gRemoteUrl || gSearchVersion.isImageSearch()) { // Check if remote page is not on the search pages so I should send the question.
gRemoteUrl = true;
initializeQuestion(e.data.data1); // Initialize the question for the website in the remotw window.
}
} else if (e.data.action == "found page and rank") { // Got a message that page and rank was found so pass variables to iframe.
if (gDebugging && gLogging) console.log("..Main got found page and rank: " + gTag + " tag: " + e.data.tag); //Just for debugging
if (e.data.tag == gTag) { // Check if tags match so no other windows can control me.
gRemoteUrl = true; // The page and rank was found so remote window is on the second page.
var doc=document.getElementsByTagName("iframe")[0].contentWindow; // Grab the iframe window to send a message.
var theData = dataFill("found page and rank", e.data.data1, e.data.data2, e.data.data3, e.data.data4, e.data.data5, e.data.data6); // Pass variables to iframe
doc.postMessage(theData,"*"); // post the message to the hit page in the iframe.
if (e.data.data2 == "None") { // if nothing was found then close the remote window or go to default page.
if (CLOSEPOPUPAFTER) { gPopUpWindow.close(); gPopUpWindow = null; } // Close window if option says so.
else if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.location = gDefaultPage + "&action=" + gHitAccepted; // Go to default page.
}
else initializeQuestion();
}
} else if (e.data.action == "found answer") { // Got a message that answer was found so pass variables to iframe.
if (gDebugging && gLogging) console.log("..Main got found answer: " + gTag + " gUrl: " + gUrl); //Just for debugging
gRemoteUrl = false; // Found answer so we must reset everything for next task.
var doc=document.getElementsByTagName("iframe")[0].contentWindow; // Grab the iframe window to send a message.
var theData = dataFill("found answer", e.data.data1, e.data.data2, e.data.data3, e.data.data4, e.data.data5, e.data.data6); // Pass variables to iframe
doc.postMessage(theData,"*"); // post the message to the hit page in the iframe.
if (CLOSEPOPUPAFTER) { gPopUpWindow.close(); gPopUpWindow = null; }
else if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.location = gDefaultPage + "&action=" + gHitAccepted;
} else if (e.data.action == "found url") { // Got a message that url was found so pass variables to iframe.
if (gDebugging && gLogging) console.log("..Main got found url: " + gTag + " gUrl: " + gUrl); //Just for debugging
gRemoteUrl = false; // Found answer so we must reset everything for next task.
var doc=document.getElementsByTagName("iframe")[0].contentWindow; // Grab the iframe window to send a message.
var theData = dataFill("found url", e.data.data1, e.data.data2, e.data.data3, e.data.data4, e.data.data5, e.data.data6); // Pass variables to iframe
doc.postMessage(theData,"*"); // post the message to the hit page in the iframe.
if (CLOSEPOPUPAFTER) { gPopUpWindow.close(); gPopUpWindow = null; } // Close window if option says so.
else if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.location = gDefaultPage + "&action=" + gHitAccepted; // Go to default page.
}
}
function popUpListener(e) { // Remote window receiving messages
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") {
if (gDebugging && gLogging) console.log("..Remote got answer question: " + gTag + " : " + e.data.tag + " : " + e.data.data1);
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"
|| e.data.action == "find yahoo question" || e.data.action == "find bing question") {
if (gDebugging && gLogging) console.log("..Remote got find stuff: " + gTag + " : " + e.data.tag + " : " + e.data.data1);
if (gZipCodes[0]!=="") doZipCode();
else if (gSearchVersion.isDoubleKeyword() && !gQueryAssoc["2key"]) doSecondKeyword();
else doSearchButtons();
}
}
}
function hitPageListener(e) {
if (e.data.action == "initialize google") initializeGoogle(e.data.data1);
else if (e.data.action == "initialize bing") initializeBing(e.data.data1);
else if (e.data.action == "initialize yahoo") initializeYahoo(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 (gDebugging && gLogging) console.log("..Hit Page got found page and rank: " + gTag + " : " + e.data.tag + " : " + e.data.data1);
var theNumber = parseInt(e.data.data1);
if (!gSearchVersion.hasSelectNone() && (e.data.data2=="None" || e.data.data3=="None")) {
document.getElementById("PageNumber-"+theNumber).value = "";
document.getElementById("Ranking-"+theNumber).value = "";
document.getElementById("BeyondPage5-"+theNumber).click();
var idNode2 = document.getElementById("Sentence-"+theNumber);
if (idNode2) idNode2.value = "";
var idNode3 = document.getElementById("URL-"+theNumber);
if (idNode3) idNode3.value = e.data.data2;
} else {
document.getElementById("PageNumber-"+theNumber).value = e.data.data2;
document.getElementById("Ranking-"+theNumber).value = e.data.data3;
if (document.getElementById("BeyondPage5-"+theNumber)!==null) {
document.getElementById("BeyondPage5-"+theNumber).checked = false;
}
if (e.data.data4 !== "") document.getElementById("WorkerResponse-"+theNumber).value = e.data.data4;
}
if (GOTONEXTTASK && !gTasksFinished && e.data.data2=="None" && theNumber < gQuestions.length-1) {
document.getElementById("searchBut" + (theNumber+1)).focus();
document.getElementById("searchBut" + (theNumber+1)).click();
} else if (e.data.data2=="None" && theNumber >= gQuestions.length-1) gTasksFinished = true;
} else if (e.data.action == "found url" && e.data.tag == gTag) { // This is for version 1 of the keyword search
if (gDebugging && gLogging) console.log("..Hit Page got found url: " + gTag + " : " + e.data.tag + " : " + e.data.data1); //Just for debugging
var theNumber = parseInt(e.data.data1);
document.getElementById("URL-"+theNumber).value = e.data.data2;
if (GOTONEXTTASK && !gTasksFinished && theNumber < gQuestions.length-1) {
document.getElementById("searchBut" + (theNumber+1)).focus();
document.getElementById("searchBut" + (theNumber+1)).click();
} else if (theNumber >= gQuestions.length-1) gTasksFinished = true;
} else if (e.data.action == "found answer" && e.data.tag == gTag) {
if (gDebugging && gLogging) console.log("..Hit Page got found answer: " + gTag + " : " + e.data.tag + " : " + e.data.data1); //Just for debugging
var theNumber = parseInt(e.data.data1);
if (!gSearchVersion.hasSelectNone()) document.getElementById("Sentence-"+theNumber).value = e.data.data2;
else document.getElementById("WorkerResponse-"+theNumber).value = e.data.data2;
if (GOTONEXTTASK && !gTasksFinished && theNumber < gQuestions.length-1) {
document.getElementById("searchBut" + (theNumber+1)).focus();
document.getElementById("searchBut" + (theNumber+1)).click();
} else if (theNumber >= gQuestions.length-1) gTasksFinished = true;
}
}
// ******************************* End of remote windows listeners and functions ***************************
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();
}
function whichVersion(theHtml) {
var searchVersion = 0;
theHtml = theHtml.toLowerCase();
if (theHtml.indexOf(VERSION[1][0].toLowerCase()) != -1) searchVersion = 1;
else if (theHtml.indexOf(VERSION[2][0].toLowerCase()) != -1) {
searchVersion = 2;
if (theHtml.indexOf(VERSION[8][0].toLowerCase()) != -1) searchVersion = 8;
else if (theHtml.indexOf(VERSION[7][0].toLowerCase()) != -1) searchVersion = 7;
else if (theHtml.indexOf(VERSION[9][0].toLowerCase()) != -1) searchVersion = 9;
else if (theHtml.indexOf(VERSION[6][0].toLowerCase()) != -1) searchVersion = 6;
else if (theHtml.indexOf(VERSION[11][0].toLowerCase()) != -1) searchVersion = 11;
} else if (theHtml.indexOf(VERSION[3][0].toLowerCase()) != -1) searchVersion = 3;
else if (theHtml.indexOf(VERSION[4][0].toLowerCase()) != -1) searchVersion = 4;
else if (theHtml.indexOf(VERSION[6][0].toLowerCase()) != -1) {
searchVersion = 6;
if (theHtml.indexOf(VERSION[5][0].toLowerCase()) != -1) searchVersion = 5;
}
return searchVersion;
}
// ************************* Starting sorting of page location ********************************************
if ( isHitPage() || isJRIO() || isMturk() || 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 (isHitPage()){ // Make sure this is on the crowdsource site.
var inPreview = isPreviewMode();
withPages_jQuery(main0); //
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) hitPageListener(e); }, false);
gTag = new Date().getTime(); // A unique global tag used to pass messages only for this session.
var instructionsNode = document.getElementById("instructions")
var instructions = (instructionsNode) ? instructionsNode.innerHTML : "";
if (instructions !== "") gSearchVersion = whichVersion(instructions);
if (gSearchVersion!==0) {
if (gDebugging && gLogging) console.log("..Found crowdsource version " + gSearchVersion + ": " + VERSION[gSearchVersion][1]);
document.addEventListener("DOMContentLoaded", function(){
enableTextSelections("text-rep");
getSearchDomain();
taskSearchButtons();
if ((!inPreview && POPUPWINDOW)) document.getElementById("searchBut1").click();
}, false);
}
} else if (isBing() && isJRIO()) {
var gTaskNumber = gQueryAssoc["ttt"];
if (gTaskNumber) {
document.addEventListener("DOMContentLoaded", function(){
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) popUpListener(e); }, false);
var theData = dataFill( "initialize bing", gTaskNumber );
parent.window.opener.postMessage(theData,"*");
}, false);
}
} else if (isGoogle() && isJRIO()) {
var gTaskNumber = gQueryAssoc["ttt"];
if (gTaskNumber) {
document.addEventListener("DOMContentLoaded", function(){
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) popUpListener(e); }, false);
var theData = dataFill( "initialize google", gTaskNumber );
parent.window.opener.postMessage(theData,"*");
}, false);
}
} else if (isYahoo() && isJRIO()) {
var gTaskNumber = gQueryAssoc["ttt"];
if (gTaskNumber) {
document.addEventListener("DOMContentLoaded", function(){
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) popUpListener(e); }, false);
var theData = dataFill( "initialize yahoo", gTaskNumber );
parent.window.opener.postMessage(theData,"*");
}, false);
}
} else if (isStartPage()) {
// This is used for the remote window. JRnewpage is for recognition of this page.
// tag is the tag from the window that opened this remote window.
if (gQueryAssoc["ST"] && gQueryAssoc["ST"] == SCRIPTTAG) {
document.addEventListener("DOMContentLoaded", function(){ // chrome needs to use document.addEventListener with DOMContentLoaded
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) popUpListener(e); }, false); // set up remote window listener
theAction = gQueryAssoc["action"];
document.body.innerHTML = "<br><H1 style='text-align:center; font-size:25px; color:darkblue;'>Waiting for a command to go to a special place!</H1>";
if (theAction != "accepted") document.body.innerHTML += "<br><H2 style='text-align:center; color: blue;'><b>Hit hasn't been accepted. Remember to accept the hit if you want!</b></H2>";
gInterval = setInterval ( function() {
var theData = dataFill( "ping" );
if (window.opener) window.opener.postMessage(theData,"*");
}, 400 );
}, false);
}
} else if (isMturk()) {
var verifyPointers = setArrayPointersElement(document,[{"type":"className","tag":"capsule_field_title","search":"Requester:"}]); // Check in capsule_field_title classes for Requester text
var requesterName = (verifyPointers.length > 0) ?
verifyPointers[0].node.parentNode.getElementsByClassName("capsule_field_text")[verifyPointers[0].position].innerHTML : "";
if (requesterName.indexOf("CrowdSource") != -1) { // Check to see if it's Crowdsource requester.
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) mainListener(e); }, false);
document.addEventListener("DOMContentLoaded", function(){ // chrome needs to use document.addEventListener with DOMContentLoaded
window.onbeforeunload = function() {
if (CLOSEPOPUPAFTER) {
if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.close();
} else {
if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.location = gDefaultPage + "&action=notaccepted"; // Check if remote window is opened still and set it to default page.
}
};
}, false);
}
} else if (isCrowdsource()) {
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) mainListener(e); }, false);
document.addEventListener("DOMContentLoaded", function(){ // chrome needs to use document.addEventListener with DOMContentLoaded
window.onbeforeunload = function() {
if (CLOSEPOPUPAFTER) {
if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.close();
} else {
if (gPopUpWindow && !gPopUpWindow.closed) gPopUpWindow.location = gDefaultPage + "&action=notaccepted"; // Check if remote window is opened still and set it to default page.
}
};
}, false);
} else if (window.opener) {
document.addEventListener("DOMContentLoaded", function(){
window.addEventListener("message", function(e){ if ( verifyMessage(e) ) popUpListener(e); }, false);
var theData = dataFill( "initialize the question" );
window.opener.postMessage(theData,"*");
}, false);
}
}