// ==UserScript==
// @name JR Mturk Panda Crazy
// @version 0.3.12
// @description Collects panda's for you at a certain cycle instead of timers. Lot of organizing of panda's and grouping them together to start and stop them at once.
// @author (JohnnyRS on mturkgrind.com and mturkcrowd.com) johnnyrs@allbyjohn.com
// @include http*://www.mturk.com/mturk/welcome?pandacrazy=on*
// @require http://code.jquery.com/jquery-2.1.4.min.js
// @require http://code.jquery.com/ui/1.11.4/jquery-ui.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery-layout/1.3.0-rc-30.79/jquery.layout.min.js
// @resource jQueryUICSS http://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css
// @resource jQueryLayoutCSS https://cdnjs.cloudflare.com/ajax/libs/jquery-layout/1.3.0-rc-30.79/layout-default.css
// @connect allbyjohn.com
// @connect mturk.com
// @connect tiny.cc
// @connect ibotta.com
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant GM_getResourceText
// @grant GM_setClipboard
// @namespace https://greasyfork.org/users/6406
// @downloadURL none
// ==/UserScript==
var gScriptVersion = "0.3.12";
var gScriptName = "pandacrazy";
var gDatabaseVersion = "JRAPR16-1.1-1.1.1"; // JR[Date]-[requesters DB Reset].[Alarms DB reset]-[requesters DB Version].[Options DB Version].[Tabs DB Version]
var gResetDBVersion = gDatabaseVersion.split("-")[1];
var gLocation = window.location.href, gLastQueueCheck = null, gNumId=0, gQueueCheckinProgress=false, queueDelay=[], gNotifications = true;
var gSlowDownAuto = true, gResetAllData = false, gDelayedSave = false, gScriptStatus = "normal", gFullQueue = false, gFullQueueTimer = null;
var gSavedSearchArea = "", gSavedAddUrl = "", gMyLayout = null, gAcceptedLogTab = null, gStatusLogTab = null, gQueueWatchTab = null;
var gMainData = {"hitCollection":{},"displayInfo":"1","accepted":0,"skipped":0,"errors":0,"searched":0,"noHits":0,"fullQueue":0,"orphan":0,"tooFast":0,"savedCycleNum":1,
"hitsInQueue":0,"queueStatus":null,"notQual":0,"lastElapsed":0,"jobs":0,"payCounter":0.00,"totalEarnings":0.00,"projectedEarnings":0.00,"missed":0};
var gMainMenu = [{"name":"Main","theobject":null}];
var gHitBgColor="#AFEEEE", gFilteredHitBgColor="#D1E5E5", gSearchesHitBgColor="#AED2D2", gButtonOffBgColor="#FFFFF0", gButtonOnBgColor="#008000";
var gButtonDelayHamBgColor="#00A3CC", gButtonDisabledBgColor="#D3D3D3", gHitMutedColor="#8B4513", gBlockedBgColor="#3D3D3D";
var gTitleColor="#000080", gButtonOffColor="black", gButtonOnColor="white", gButtonDisabledColor="#808080", gNotQualedBgColor="#DDA0DD", gBlockedColor = "#FFF5EE";
var gHitMutedBorderStyle="dotted", gHitBorderStyle="solid", gHitTextColor="#000000", gHitShortIdColor = "#551A8B";
var gZingOptions = {
"0.01":{"SearchGroupAllowed":1,"TallyCountTotalAllowed":0,"MaxProductsSearch":0,"AcceptCodesSearching":false,"MaxReceiptImages":3},
"0.03":{"SearchGroupAllowed":2,"TallyCountTotalAllowed":0,"MaxProductsSearch":2,"AcceptCodesSearching":true,"MaxReceiptImages":3},
"0.05":{"SearchGroupAllowed":3,"TallyCountTotalAllowed":0,"MaxProductsSearch":4,"AcceptCodesSearching":true,"MaxReceiptImages":4},
"0.07":{"SearchGroupAllowed":7,"TallyCountTotalAllowed":0,"MaxProductsSearch":5,"AcceptCodesSearching":true,"MaxReceiptImages":8}
};
var gZingFuncOptions = {
"1":{"filterName":"Parse Zing Hit Page","functionName":parseZingHitPage}
};
var gAlarmSounds = {
"less2":{"nameVar":"JR_PANDA_Soundless2","default":"http://tiny.cc/c6c1ay","audio":null,"desc":"Hits paying less than |: ","payRate":"0.02","lessMinutes":"99","base64":null},
"less2Short":{"nameVar":"JR_PANDA_Soundless2Short","default":"http://tiny.cc/kyh1ay","audio":null,"desc":"Hits paying less than | with a short timer less than | minute(s): ","payRate":"0.02","lessMinutes":"2","base64":null},
"less5":{"nameVar":"JR_PANDA_Soundless5","default":"http://tiny.cc/g7h1ay","audio":null,"desc":"Hits paying less than |: ","payRate":"0.05","lessMinutes":"99","base64":null},
"less5Short":{"nameVar":"JR_PANDA_Soundless5Short","default":"http://tiny.cc/99h1ay","audio":null,"desc":"Hits paying less than | with a short timer less than | minute(s): ","payRate":"0.05","lessMinutes":"5","base64":null},
"less15":{"nameVar":"JR_PANDA_Soundless15","default":"http://tiny.cc/qai1ay","audio":null,"desc":"Hits paying less than |: ","payRate":"0.15","lessMinutes":"99","base64":null},
"less15Short":{"nameVar":"JR_PANDA_Soundless15Short","default":"http://tiny.cc/uai1ay","audio":null,"desc":"Hits paying less than | with a short timer less than | minute(s): ","payRate":"0.15","lessMinutes":"8","base64":null},
"less99":{"nameVar":"JR_PANDA_Soundless99","default":"http://tiny.cc/gbi1ay","audio":null,"desc":"Hits paying MORE than |: ","payRate":"0.15","lessMinutes":"99","base64":null},
"fullQueue":{"nameVar":"JR_PANDA_FullQueue","default":"http://tiny.cc/wietby","audio":null,"desc":"You have a full queue!","payRate":"","lessMinutes":"99","base64":null},
"queueAlert":{"nameVar":"JR_PANDA_QueueAlert","default":"http://tiny.cc/cnxyby","audio":null,"desc":"Lowest timed hit in queue is less than || minutes.","payRate":"","lessMinutes":"5","base64":null},
"hasToPause":{"nameVar":"JR_PANDA_hasToPause","default":"http://tiny.cc/w823by","audio":null,"desc":"Logged out or captcha alarm!","payRate":"","lessMinutes":"99","base64":null},
};
var gSoundOptions = null, gLastAlarm = "", gSoundFile = null, gTabIndex = 0, gMouseDownTimeoutId = null, gPressAndHold = false, gQueueData = [], gQueueCount = {};
var gMuteQueueWatch = false, gGroupings = {}, gGroupingsSort = [];
var gGroupingData = {"JR First":{"theNumber":"0","description":"First grouping by default.","grouping":[],"delayed":[]}};
var gDefaultGroupingData = {"JR First":{"theNumber":"0","description":"First grouping by default.","grouping":[],"delayed":[]}};
var gTabsInfo = {}, gTabsData = [], gMainOptions = {}, gExternalData = {};
var gDefaultExternalData = {"url":"url","numId":null,"mode":null,"sentPing":false,"gotPong":true};
var gSearchOptionsData = {"filterInclude":"","filterExclude":"",pay:"0","payHigher":true,"toCheck":3,"remember":false};
var gDefaultSearchOptions = {"exclude":"","include":"","minReward":"0.00"};
var gDefaultSearchHistory = {"groupId":"","pay":"","title":"","duration":"","theDate":null};
var gDefaultTabsInfo = {"nextTabNumber":"4","tabCount":"3"};
var gDefaultTabsData = [{"tabName":"Main","tabNumber":"1","positions":null},{"tabName":"Daily Hits","tabNumber":"2","positions":null},{"tabName":"Rare Hits","tabNumber":"3","positions":null}];
var gDefaultMainOptions = {"cycleNumber":980,"HamCycleNumber":700,"autoSlowDown":true,"cycleAutoIncrease":10,"alarmVolume":80,"cycleIncrease":10,"cycleDecrease":10,"cycleAdding":650,"queueTimer":40000,"hamDelayTimer":15,"showHelpTooltips":true,"cycleNumber2":1400,"cycleNumber3":2100,"disableCaptchaAlert":false,"disableQueueAlert":false,"disableNotifications":false,"debugger":0};
var gRequestersData = {};
var gJobDataDefault = {"requesterName":"","requesterId":"","groupId":"","pay":"","title":"","duration":"0","hitsAvailable":0,"timeLeft":"","totalSeconds":0,"hitId":"",
"continueURL":"","returnURL":"","durationParsed":null,"jobNumber":"-1","friendlyRName":"","friendlyTitle":"","assignedOn":"","description":"","qual":"","keywords":""};
var gDefaultRequestersData = {
"0":{"requesterName":gDatabaseVersion,"requesterId":28,"action":"","groupId":"","pay":"","qual":"","title":"","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"exclude":"","include":"","minReward":"0.00"},"searchHistory":{"groupId":"","pay":"","title":"","duration":"","theDate":null}}},
"4":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"38MNOT6KWI2RBQGVM0MBPUP6RVH0T8","pay":"0.01","qual":"ibotta","title":"Are these the same?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":15,"weight":0,"searchData":null},
"5":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3XLZDG4M7280UYEGHLXC92IBFQGZL0","pay":"0.01","qual":"","title":"Are these the same?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":15,"weight":0,"searchData":null},
"6":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3ZXRRTK2NDCB5NW5M24C9P2OWG41OF","pay":"0.01","qual":"ibotta","title":"Does this receipt contain the following products?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":null},
"7":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3NYGPW9OTYRQLJTE9DQJQJRQJ2IZPS","pay":"0.01","qual":"","title":"Does this receipt contain the following products?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":null},
"8":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3R35RPFD7JUTQN8612HRYP7E6LZ1PV","pay":"0.03","qual":"ibotta","title":"Does this receipt contain the following products?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":null},
"9":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3ZXRRTK2NDCB5NW5M24C9P2OVF61OE","pay":"0.03","qual":"","title":"Does this receipt contain the following products?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":null},
"10":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3CRC4NO2BIQQWQ3GX0HLFPTFOD30SA","pay":"0.05","qual":"ibotta","title":"Does this receipt contain the following products?","queueLimit":0,"duration":"60 minutes","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":12,"weight":0,"searchData":null},
"11":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3787DLY3Y49RIF1DIJQB3Z8BUNP1T2","pay":"0.05","qual":"","title":"Does this receipt contain the following products?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":12,"weight":0,"searchData":null},
"14":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"3EGCY5R6XY0PS57S4R2H1KZW7LSAYC","pay":"0.01","qual":"","title":"Identify Images with Mature Content","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"15":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"3USMLONC9E5D7T4TWRD6UWVBJLN85E","pay":"0.03","qual":"","title":"Identify Images with Mature Content","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"16":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"37G59K9AEU0BNMXNCLOH5POEZUC9YI","pay":"0.03","qual":"","title":"Identify Videos with Mature Content","queueLimit":0,"duration":"15 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"17":{"requesterName":"Steven Snow","requesterId":"A3GAVAUPTHM0B8","action":"Panda","groupId":"3X19M43Z4VULD73G1I2N3GGRYF10D8","pay":"0.06","qual":"","title":"steven snow search 3X..D8","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":3,"once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"18":{"requesterName":"Steven Snow","requesterId":"A3GAVAUPTHM0B8","action":"Panda","groupId":"3TJJ8HSJVIVGSMA3ZXVL0CV5EGV28D","pay":"0.05","qual":"","title":"steven snow url 3T..8D","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"3","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"19":{"requesterName":"Venue Quality","requesterId":"A14AT838CPSKA6","action":"Panda","groupId":"3EM4DVSA8U8J6KF08Q5EM8I2NYE308","pay":"0.01","qual":"","title":"locations same","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"20":{"requesterName":"Venue Quality","requesterId":"A14AT838CPSKA6","action":"Panda","groupId":"3D8O2NKTAGFJD90I499E0D26RON13W","pay":"0.01","qual":"","title":"locations adult","queueLimit":0,"duration":"5 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"21":{"requesterName":"Venue Quality","requesterId":"A14AT838CPSKA6","action":"Panda","groupId":"ZZAWVTYW3Z9ZTAX43ZD0","pay":"0.01","qual":"","title":"locations family","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null},
"23":{"requesterName":"Rob Grady","requesterId":"AM07BBZNC6UTQ","action":"Panda","groupId":"33X7UBO5WUFB78Y5WJ3MVC35LFMU05","pay":"0.03","qual":"","title":"Transcribe Waffle House Guest Check","queueLimit":0,"duration":"5 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":null}
};
var gExcludeIds = ["38FT9G80DL83PUCSQBVANJBIKGSLHM"];
var jqUI_CssSrc = GM_getResourceText("jQueryUICSS");
var jqLayout_CssSrc = GM_getResourceText("jQueryLayoutCSS");
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
};
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
};
function formatAMPM(theFormat,theDate,theTimeZone) {
var d = (theDate) ? theDate : new Date();
if (theTimeZone == "mturk") {
var mturkTZOffset = -8;
var today = new Date();
if (today.dst()) mturkTZOffset++;
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var MturkTime = utc + (3600000 * mturkTZOffset);
d = new Date(MturkTime);
}
var minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
if (theFormat=="short") return ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + '-' + d.getFullYear() + '(' + hours + ':' + minutes + ampm + ')';
else if (theFormat=="onlydate") return ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + '-' + d.getFullYear();
else return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}
function formatTimeZone(theFormat,theDate,theTimeZone) {
return formatAMPM(theFormat,theDate,theTimeZone);
}
function getTimeLeft(theTime) {
if (theTime!==null && theTime!=="") {
var tempArray = (theTime.indexOf("second") != -1) ? theTime.split("second")[0].trim().split(" ") : null;
var seconds = (tempArray) ? parseInt(tempArray[tempArray.length-1]) : 0;
tempArray = (theTime.indexOf("minute") != -1) ? theTime.split("minute")[0].trim().split(" ") : null;
var minutes = (tempArray) ? parseInt(tempArray[tempArray.length-1]) : 0;
tempArray = (theTime.indexOf("hour") != -1) ? theTime.split("hour")[0].trim().split(" ") : null;
var hours = (tempArray) ? parseInt(tempArray[tempArray.length-1]) : 0;
tempArray = (theTime.indexOf("day") != -1) ? theTime.split("day")[0].trim().split(" ") : null;
var days = (tempArray) ? parseInt(tempArray[tempArray.length-1]) : 0;
tempArray = (theTime.indexOf("week") != -1) ? theTime.split("week")[0].trim().split(" ") : null;
var weeks = (tempArray) ? parseInt(tempArray[tempArray.length-1]) : 0;
return( {"weeks":weeks,"days":days,"hours":hours,"minutes":minutes,"seconds":seconds} );
} else return null;
}
function formatTimeLeft(resetNow,thisDigit,timeString,lastDigit) {
formatTimeLeft.timeFill = formatTimeLeft.timeFill || 0;
if (resetNow) formatTimeLeft.timeFill = 0;
var missingDigit = (lastDigit && !thisDigit) ? true : false;
if ((thisDigit || missingDigit) && formatTimeLeft.timeFill<2) {
formatTimeLeft.timeFill++;
if (missingDigit) { return "00 " + timeString + "s"; }
else {
var addZero = (thisDigit<10) ? ((formatTimeLeft.timeFill==1) ? false : true) : false;
var plural = (thisDigit==1) ? false : true;
return ((addZero) ? "0" : "") + thisDigit + " " + ((plural) ? (timeString+"s") : timeString) + " ";
}
} else return "";
}
function convertToTimeString(timeData) {
var returnString = "";
returnString += formatTimeLeft(true,timeData.weeks,"week",false);
returnString += formatTimeLeft(false,timeData.days,"day",timeData.weeks);
returnString += formatTimeLeft(false,timeData.hours,"hour",timeData.days);
returnString += formatTimeLeft(false,timeData.minutes,"minute",timeData.hours);
returnString += formatTimeLeft(false,timeData.seconds,"second",timeData.minutes);
return returnString.trim();
}
function convertTimeToSeconds(timeData) {
var totalSeconds = timeData.seconds + ((timeData.minutes) ? (timeData.minutes*60) : 0) + ((timeData.hours) ? (timeData.hours*3600) : 0) +
((timeData.days) ? (timeData.days*86400) : 0) + ((timeData.weeks) ? (timeData.weeks*604800) : 0);
return totalSeconds;
}
function convertToSeconds(milliseconds,fixed) { fixed = fixed || 2; var seconds = parseFloat((milliseconds/1000.0 * 100) / 100).toFixed(fixed) + ""; return seconds.replace(/\.0*$/,""); }
function convertToMilliseconds(seconds) { if (seconds) return seconds*1000 + ""; else return "0"; }
function checkNotifications() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) return false;
else if (Notification.permission === "granted") return true;
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if (permission === "granted") return true;
});
}
return false;
}
function showNotification( title, message, tag, groupId ) {
if (gMainOptions.disableNotifications) return;
showNotification.tagNumber = showNotification.tagNumber || 0;
showNotification.lastGroupID = showNotification.lastGroupID || "0";
if (showNotification.lastGroupID != groupId) showNotification.tagNumber++;
showNotification.lastGroupID = groupId;
var n = new Notification(title, {
body: message,
icon: "http://www.allbyjohn.com/mturk/Messaging-Online-icon.png",
tag: tag+showNotification.tagNumber});
if (navigator.userAgent.search("Chrome") >= 0) n.onshow = function () { setTimeout(n.close.bind(n), 28000); };
}
// Database using setValue and getValue
function convertDatabase(theDataBase) {
var newDataBase = {};
$.each(theDataBase, function( index, value ) {
newDataBase[index] = value;
if (newDataBase[index].searchData===null) newDataBase[index].searchData=setSearchOptionsDefault();
if (newDataBase[index].searchData.searchOptions===null) newDataBase[index].searchData=setSearchOptionsDefault();
if (newDataBase[index].searchData.searchHistory===null ) newDataBase[index].searchData=setSearchOptionsDefault();
if (newDataBase[index].weight===null) newDataBase[index].weight=0;
if (newDataBase[index].duration===null) newDataBase[index].duration="";
if (newDataBase[index].groupId===null) newDataBase[index].groupId="";
if (newDataBase[index].hamTimer===null) newDataBase[index].hamTimer=gDefaultMainOptions.hamDelayTimer;
});
newDataBase[0].requesterName = gDatabaseVersion;
return newDataBase;
}
function convertTabDatabase() {
if (gTabsData[0].tabName == "Holder") { // temporary for testing computer
var newDataBase = [];
gTabInfo = {"nextTabNumber":"" + gTabsData[0].tabNumber,"tabCount":"" + gTabsData.length};
$.each(gTabsData, function( index, value ) {
if (index>0) newDataBase.push(value);
});
gTabsData = newDataBase;
}
}
function getBase64Audio(theData) {
var base64AudioData = new Uint8Array(theData);
var i = base64AudioData.length;
var binaryString = new Array(i);
while (i--) { binaryString[i] = String.fromCharCode(base64AudioData[i]); }
var data = binaryString.join('');
return(window.btoa(data));
}
function fillInSoundOptions(soundOptions) {
$.each(soundOptions, function( index, value ) {
gAlarmSounds[index].payRate = value.payRate;
gAlarmSounds[index].lessMinutes = value.lessMinutes;
if (value.base64!==null) {
gAlarmSounds[index].audio = new Audio("data:audio/wav;base64," + JSON.parse(value.base64));
GM_setValue(gAlarmSounds[index].nameVar,JSON.stringify(value.base64));
}
});
}
function loadSoundFiles(soundNumber,keyArray,resetMe) {
resetMe = resetMe || false;
var savedDBVersion = gRequestersData[0].requesterName;
var resetDBVersion = savedDBVersion.split("-")[1];
if (soundNumber < keyArray.length) {
if ((gResetDBVersion.split(".")[1] > resetDBVersion.split(".")[1]) || gResetAllData) GM_deleteValue(gAlarmSounds[keyArray[soundNumber]].nameVar);
var gotBase64 = (resetMe) ? null : GM_getValue(gAlarmSounds[keyArray[soundNumber]].nameVar,null);
this.firstTime = this.firstTime || false;
if (gotBase64 === null) {
if (!this.firstTime) addToWaitDialog("For your first time this might take a few seconds.
Loading Alarms ",false);
this.firstTime = true;
requestUrl(gAlarmSounds[keyArray[soundNumber]].default,0,function(theResult,theNumber,data1,data2) {
addToWaitDialog(" .",false);
var base64 = getBase64Audio(theResult.response);
GM_setValue(gAlarmSounds[keyArray[soundNumber]].nameVar,JSON.stringify(base64));
gAlarmSounds[keyArray[soundNumber]].audio = new Audio("data:audio/wav;base64," + base64);
loadSoundFiles(soundNumber+1,keyArray,resetMe);
},function() { errorRequest(); }, "", "", "arraybuffer");
} else {
gAlarmSounds[keyArray[soundNumber]].audio = new Audio("data:audio/wav;base64," + JSON.parse(gotBase64));
loadSoundFiles(soundNumber+1,keyArray,resetMe);
}
} else continueLoading();
}
function fillInGroupings() {
$.each(gGroupingData, function( index, value ) {
if (!value.grouping) value.grouping = [];
gGroupings[index] = {"data":value,"collecting":false};
gGroupingsSort.push(index);
defaultFillIn(value,gDefaultGroupingData["JR First"]);
});
}
function defaultFillIn(data,defaultData) {
$.each(defaultData, function( index, value ) {
if (!(index in data)) { data[index] = value; }
});
}
function loadInDBVersions(passedDatabase) {
var tempData = null;
if (passedDatabase) tempData = passedDatabase;
else tempData = JSON.parse(GM_getValue("JR_PANDA_RequestersData",JSON.stringify(gDefaultRequestersData)));
var savedDBVersion = tempData[0].requesterName;
var resetDBVersion = savedDBVersion.split("-")[1];
var defaultDBVersion = savedDBVersion.split("-")[2];
if (gResetDBVersion.split(".")[0] > resetDBVersion.split(".")[0]) {
GM_deleteValue("JR_PANDA_RequestersData");
tempData = JSON.parse(GM_getValue("JR_PANDA_RequestersData",JSON.stringify(gDefaultRequestersData)));
}
tempData = convertDatabase(tempData);
$.each(tempData, function( index, value ) { defaultFillIn(value,gDefaultRequestersData[0]); });
return tempData;
}
function changeOldSettings() {
if (gMainOptions.cycleIncrease==5) gMainOptions.cycleIncrease = 10;
if (gMainOptions.cycleDecrease==5) gMainOptions.cycleDecrease = 10;
if (gMainOptions.hamDelayTimer===null) gMainOptions.hamDelayTimer=gDefaultMainOptions.hamDelayTimer;
}
function setupSoundOptions(base64) {
base64 = base64 || false;
var soundOptions = {};
$.each(gAlarmSounds, function( index, value ) {
var theBase64 = (base64) ? GM_getValue(value.nameVar,null) : null;
soundOptions[index] = {"payRate":value.payRate,"lessMinutes":value.lessMinutes,"base64":theBase64};
});
return soundOptions;
}
function clearOldMessages() {
for (i = 0; i < localStorage.length; i++) {
if ( localStorage.key(i).substring(0,11) == 'JR_message_' && localStorage.key(i).substr(localStorage.key(i).length - gScriptName.length) == gScriptName ) {
localStorage.removeItem(localStorage.key(i));
}
}
}
function loadSettings() {
clearOldMessages();
var defaultSoundOptions = setupSoundOptions();
if (gResetAllData) GM_deleteValue("JR_PANDA_RequestersData");
gRequestersData = loadInDBVersions();
if (gResetAllData) GM_deleteValue("JR_PANDA_MainOptions");
gMainOptions = JSON.parse(GM_getValue("JR_PANDA_MainOptions",JSON.stringify(gDefaultMainOptions)));
defaultFillIn(gMainOptions,gDefaultMainOptions);
if (gResetAllData) GM_deleteValue("JR_PANDA_TabsData");
gTabsData = JSON.parse(GM_getValue("JR_PANDA_TabsData",JSON.stringify(gDefaultTabsData)));
gTabsInfo = JSON.parse(GM_getValue("JR_PANDA_TabsInfo",JSON.stringify(gDefaultTabsInfo)));
convertTabDatabase();
$.each(gTabsData, function( index, value ) { defaultFillIn(value,gDefaultTabsData[0]); });
if (gResetAllData) GM_deleteValue("JR_PANDA_GroupingData");
gGroupingData = JSON.parse(GM_getValue("JR_PANDA_GroupingData",JSON.stringify(gDefaultGroupingData)));
fillInGroupings();
gSoundOptions = JSON.parse(GM_getValue("JR_PANDA_SoundOptions",JSON.stringify(defaultSoundOptions)));
loadSoundFiles(0,Object.keys(gAlarmSounds));
fillInSoundOptions(gSoundOptions);
changeOldSettings();
}
function saveSettings(doAfter) {
var soundOptions = setupSoundOptions();
GM_setValue("JR_PANDA_RequestersData",JSON.stringify(gRequestersData));
GM_setValue("JR_PANDA_MainOptions",JSON.stringify(gMainOptions));
GM_setValue("JR_PANDA_TabsData",JSON.stringify(gTabsData));
GM_setValue("JR_PANDA_TabsInfo",JSON.stringify(gTabsInfo));
GM_setValue("JR_PANDA_GroupingData",JSON.stringify(gGroupingData));
GM_setValue("JR_PANDA_SoundOptions",JSON.stringify(soundOptions));
if (doAfter) setTimeout( function() { doAfter(); },200);
}
function checkDelayedSave() { if (gDelayedSave) saveSettings(); }
// Jquery Creating HTML elements Functions --------
function toggleButton(thisButton,doThisOn,doThisOff,mode,modeStatus) {
// dothison = status on function, dothisOff = status off function, mode = status mode to force change to, modestatus = force on or off function
var theStatus = $(thisButton).data("status"); // Get status of the button
var doStatus = (modeStatus) ? modeStatus : (theStatus != "on" && theStatus!=mode) ? "on" : "off";
if (mode && theStatus!=mode) $(thisButton).data("status",mode);
else $(thisButton).data("status",doStatus);
if (doStatus=="on" && doThisOn) doThisOn($(thisButton).data("theNumber"),thisButton,mode);
if (doStatus=="off" && doThisOff) doThisOff($(thisButton).data("theNumber"),thisButton,mode);
updateHitColors($(thisButton).data("theNumber"),thisButton);
}
function toggleButtonOff(thisButton,doThisOn,doThisOff,passedMode) {
$(thisButton).data("status","off");
updateHitColors($(thisButton).data("theNumber"),thisButton);
if (doThisOff) doThisOff($(thisButton).data("theNumber"),thisButton,passedMode);
}
function toggleButtonOn(thisButton,doThisOn,doThisOff) {
if ($(thisButton).data("status") == "off") {
$(thisButton).data("status","on");
updateHitColors($(thisButton).data("theNumber"),thisButton);
if (doThisOn) doThisOn($(thisButton).data("theNumber"),thisButton);
}
}
function checkButtonsStatus() {
if (gScriptStatus == "normal") return true;
else return false;
}
function createDiv(theHtml) { var inner = (theHtml) ? theHtml : ""; return $('
').html(inner); }
function createSpan(theHtml) { var inner = (theHtml) ? theHtml : ""; return $('
').html(inner); }
function createTextInput(theValue) { return $("").attr({ "type": "text", "value": theValue }); }
function createCheckbox(theValue) { return $("").attr({ "type": "checkbox", "value": theValue }); }
function createRadioButton(theName,theValue) { return $("").attr({ "type": "radio", "name": theName, "value": theValue }); }
function createLink(theText,theUrl,theTarget,theTitle) { return $('',{text: theText,target: theTarget,title: theTitle,href: theUrl}); }
function createSpanButton(toDo,theHtml,theBackgroundColor,theColor,theFontSize) {
var backgroundColor = (theBackgroundColor) ? theBackgroundColor : "initial";
var textColor = (theColor) ? theColor : "initial";
var fontSize = (theFontSize) ? theFontSize : "9px";
var theButton = createSpan(theHtml).data({"backgroundColor":backgroundColor,"status":"off","textColor":textColor,"htmlText":theHtml})
.disableSelection()
.dblclick(function(e) { e.stopPropagation(); })
.css({"font-size":fontSize,"padding":"0px 2px","background-color":backgroundColor,"color":textColor,"border":"2px groove red","cursor":"default","margin":"0px 1px"});
if (toDo) theButton.click( function(e) {
if (checkButtonsStatus()) {toDo(e);}
});
return theButton;
}
function createContainer() {
var containerDiv = createDiv();
containerDiv.css({"padding-left":"3px", "padding-right":"3px","padding-top":"0px","padding-bottom":"1px"});
return containerDiv;
}
function createPanels(goAppend) {
var panelContainer = createContainer()
.attr("id","panelContainer")
.appendTo(goAppend);
return panelContainer;
}
function createPanel(goAppend) {
var panel = createContainer().appendTo(goAppend);
return panel;
}
function createTabs(goAppend,isSortable,idName) {
var tabList = $("");
var tabsContainer = createContainer()
.attr("id",idName)
.css({"height":"99%"})
.appendTo(goAppend);
tabList.appendTo(tabsContainer);
tabsContainer.tabs().delegate( "span.ui-icon-close", "click", function(e) {
var currentTab = $(e.target).closest("li");
var currentIndex = $(currentTab).index();
$("#JRMainTabs").tabs("option", "active", currentIndex);
var returnValue = confirm("Are you sure you want to delete this Tab?\nAll hits inside the tab will be moved to the Main Tab.\nNo Hits will be lost.");
if (returnValue) {
var currentAriaTab = $("#" + (currentTab.attr("aria-controls")));
var mainAriaTab = $("#" + ($("#JRTab_1").attr("aria-controls")));
var currentData = $(currentTab).data("tabData");
if (currentData.positions.length>0) {
for (var i=0, len=currentData.positions.length; i").html("" + theTitle + "")
.attr({"id":theID,"class":theClasses})
.css({"font-size":"10px"})
.data({"tabData":tabData})
.appendTo( tabContainer.find("ul") );
if (appendClose) {
theTabLi.append(createSpan("Remove Tab").attr({"class":"ui-icon ui-icon-close","role":"presentation"}));
theTabLi.bind("contextmenu", function(e) {
if ($(e.target).closest("li").index() > 0) {
var returnName = prompt("Enter Tab Label : ", $(e.target).html());
if (returnName && returnName!=="") {
$(e.target).html(returnName);
$(e.target).closest("li").data("tabData").tabName = returnName;
saveSettings();
}
}
e.preventDefault();
return false;
});
}
theTabDiv.data({"tabData":tabData}).appendTo(tabContainer);
if (isSortable) {
theTabLi.click( function() { $(this).focus(); $("#" + $(this).attr("aria-controls")).find(".tabContents").focus(); })
.droppable({ tolerance: 'pointer', drop: moveToTab,
over: function( event, ui ) {
var inTabId = $(event.target).attr("aria-controls");
$("#JRMainTabs").tabs("option", "active", $(event.target).index());
$(event.target).focus(); $("#" + inTabId).find(".tabContents").focus();
ui.draggable.data("sameTab",false);
}
});
theTabDiv.html("
");
}
tabContainer.tabs("refresh");
return theTabDiv;
}
// Alarm function -----------
function playThisSound( keyName ) {
gLastAlarm = keyName;
gAlarmSounds[keyName].audio.pause();
gAlarmSounds[keyName].audio = gAlarmSounds[keyName].audio;
gAlarmSounds[keyName].audio.currentTime = 0;
gAlarmSounds[keyName].audio.volume = gMainOptions.alarmVolume/100;
gAlarmSounds[keyName].audio.play();
}
function playNewSound( AudioObject ) {
if (gSoundFile) gSoundFile.pause();
gSoundFile = AudioObject;
gSoundFile.currentTime = 0;
gSoundFile.volume = gMainOptions.alarmVolume/100;
gSoundFile.play();
}
// Main cycler class that handles all timers, queues, pauses, and hams
var theCycler = (function() {
var privateVars = {
_timers: [],
_theQueue: [],
_theFrontOfTheLineQueue: [],
_theFrontOfTheLineTimer: [],
_before: new Date(),
_lastRemoved: -1,
_theCycle: 500,
_realCycle: 500,
_theCycleElapsed: 0,
_theCycleSkipping: 0,
_paused: false,
_doHam: null,
_timeoutVar: null
};
var privateFunctions = {
_getInTimer: function(theNumber) {
for (var i=0, len=privateVars._timers.length; i -1) return [foundNumber,privateVars._theQueue.splice(foundNumber, 1)[0]];
else if (foundNumber == -86) { var returnData = privateVars._doHam; privateVars._doHam = null; return [foundNumber,returnData]; }
else return null;
},
_goFrontOfTheLineTimer: function() {
var frontOfTheLineNumber = privateVars._theFrontOfTheLineTimer.shift();
var frontOfTheLineItem = privateFunctions._getInTimer(frontOfTheLineNumber);
if (gMainOptions.debugger==2) console.log("Frontofthelinetimer: " + JSON.stringify(frontOfTheLineItem)); // debugger =2 for queue details.
if (frontOfTheLineItem) {
frontOfTheLineItem.runFunction.apply("frontoftheline",[frontOfTheLineItem.elapsed,frontOfTheLineItem.theNumber] );
frontOfTheLineItem.elapsed = 0;
return true;
} else return false;
},
_goFrontOfTheLine: function() {
var frontOfTheLineNumber = privateVars._theFrontOfTheLineQueue.shift(), thisItem = null, removeResult = null, frontOfTheLineQueue = null;
removeResult = privateFunctions._removeFromQueue(frontOfTheLineNumber);
if (!removeResult) return false;
frontOfTheLineQueue = removeResult[1];
if (frontOfTheLineQueue) {
if (gMainOptions.debugger==2) console.log("Frontofthelinequeue: " + JSON.stringify(frontOfTheLineQueue)); // debugger =2 for queue details.
for (var c=0, len=frontOfTheLineQueue.length; c= privateVars._timers[i].milliSeconds) {
returnStatus = privateVars._timers[i].runFunction.apply("timer",[privateVars._timers[i].elapsed,privateVars._timers[i].theNumber] );
privateVars._timers[i].elapsed = 0;
}
}
return returnStatus;
},
_doQueue: function() {
var skipThis = true, queueItem = null, counter=0, doOnce=false, weighted=false, weightedRan=false, removed=false;
if (gMainOptions.debugger==2) console.log("Queue: " + JSON.stringify(privateVars._theQueue)); // debugger =2 for queue details.
do {
queueItem = privateVars._theQueue[counter];
if (queueItem.length>1) weighted=true;
if (queueItem[0].weightStatus=="item") { // check to see if this item is not null for weighted items. Non weighted items will never have nulls.
try { skipThis = !queueItem[0].runFunction.apply("queue",[privateVars._theCycleElapsed,queueItem[0].theNumber] ); }
catch(e) { console.log('JRPanda: An error has occurred: '+e.message); }
doOnce = queueItem[0].doOnce;
if (privateVars._lastRemoved==queueItem[0].theNumber) removed=true; // Was this item removed already?
if (!removed) privateVars._theQueue.splice(counter,1); // remove from queue because item was either done or skipped.
weightedRan=true;
} else weightedRan=false;
if (weighted && !removed) queueItem.push(queueItem.shift()); // Take from top of item queue and place on bottom to keep null weight items.
if (weighted && !weightedRan && !removed) privateVars._theQueue.splice(counter,1,queueItem); // Replace item in same place if this was skipped because of null weight item.
if ( (!weighted && !doOnce && !removed) || (weighted && weightedRan && !removed) ) privateVars._theQueue.push(queueItem);
counter++; weighted=false;
} while (privateVars._theQueue.length > 0 && skipThis && counter < privateVars._theQueue.length);
privateVars._lastRemoved = -1; // Reset last removed so everything is fresh.
},
_theLoop: function() {
var continueCheck = true;
var elapsed = new Date().getTime() - privateVars._before.getTime();
if (elapsed >= privateVars._realCycle) {
privateVars._theCycleElapsed = elapsed;
privateVars._before = new Date();
if (privateVars._theFrontOfTheLineTimer.length > 0) continueCheck = !privateFunctions._goFrontOfTheLineTimer();
if (privateVars._theFrontOfTheLineQueue.length > 0) continueCheck = !privateFunctions._goFrontOfTheLine();
if (continueCheck && privateVars._timers.length>0) continueCheck = !privateFunctions._doTimers();
if (continueCheck && privateVars._doHam) { continueCheck = false; privateFunctions._goHam(); }
if (continueCheck && privateVars._theQueue.length>0) { privateFunctions._doQueue(); }
}
privateVars._timeoutVar = setTimeout(privateFunctions._theLoop, 5);
}
};
var output = {
addJob: function(func, theNumber, milliSeconds, doOnce, weight) {
if (typeof func === 'function' && !isNaN(milliSeconds)) {
doOnce = doOnce || false; weight = weight || 0;
if (privateFunctions._checkInQueue(theNumber)!=-1) return;
for(var i=0, len=privateVars._timers.length; i 0) privateVars._timers.unshift(jobData[0]);
}
if (privateVars._timeoutVar===null) { privateVars._before = new Date(); privateFunctions._theLoop(); }
},
removeJob: function(theNumber) {
var returnValue = false;
if (privateFunctions._removeFromQueue(theNumber)) privateVars._lastRemoved = theNumber;
for (var i=0, len=privateVars._timers.length; i0 || privateVars._theQueue.length>0)
privateVars._timeoutVar = setTimeout(privateFunctions._theLoop, 0);
},
frontOfTheLineTimer: function( theNumber ) { privateVars._theFrontOfTheLineTimer.push(theNumber); },
frontOfTheLine: function( theNumber ) { privateVars._theFrontOfTheLineQueue.push(theNumber); },
changeWeight: function( theNumber, newWeight ) {
var foundNumber = privateFunctions._checkInQueue(theNumber), thisItem=null, itemQueue=null;
if (foundNumber==-86) itemQueue = privateVars._doHam;
else if (foundNumber>-1) itemQueue = privateVars._theQueue.splice(foundNumber, 1)[0];
if (itemQueue) {
for (var c=0, len=itemQueue.length; c0) {
for (var i=gQueueData.length-1; i>=0; i--) {
theTimeLeft = getTimeLeft(gQueueData[i].timeLeft);
timeLeftString = convertToTimeString(theTimeLeft);
addToQueueWatchLog(createSpan("(" + gQueueData[i].requesterName + ") [$" + gQueueData[i].pay + "] - " +
timeLeftString + " - " + gQueueData[i].title + " :: ").data("thisData",gQueueData[i])
.append(createQueueLinks(gQueueData[i].returnURL,gQueueData[i].continueURL)));
if (queueAlertOK && !gMainOptions.disableQueueAlert) {
if (!lessThanAlarm && theTimeLeft.weeks < 1 && theTimeLeft.days < 1 && theTimeLeft.hours < 1 && theTimeLeft.minutes < parseInt(gAlarmSounds.queueAlert.lessMinutes)) {
lessThanAlarm = true;
if (!$("#muteQueueWatchAlarm").is(":checked")) {
playThisSound("queueAlert");
$("#JRQueueWatchLog").css({"background-color":"#8A0000"});
$("#JRQueueWatchLog").animate({"backgroundColor":"#000000"}, 10000, function() {
$("#JRQueueWatchLog").css({"background-color":"#8A0000"});
$("#JRQueueWatchLog").animate({"backgroundColor":"#000000"}, 10000);
});
}
}
}
}
} else {
addToQueueWatchLog(createDiv("You have no hits in your queue at this time. Click on the black background to refresh your queue.
" +
"An alarm will be heard if a hit has " + gAlarmSounds.queueAlert.lessMinutes + " minutes left. Mute the alarm to the right if not needed.
" +
"This window gets updated every " + convertToSeconds(gMainOptions.queueTimer) + " seconds.")
.css({"font-size":"15px","color":"#7FFFD4","margin-top":"12px","text-align":"center","line-height":"18px"}));
}
$("#JRStatusTab_2 .JRTabLabel:first").html("Queue Watch - " + ((gMainData.hitsInQueue <=25) ? gMainData.hitsInQueue : "25"));
}
function fullQueueTimer() { gFullQueue = false; }
function displayHitStatus( theNumber ) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitStatus = hitInfo.status;
var skippedStatus = (hitInfo.data.action.toLowerCase().indexOf("filter") != -1) ? "Skip: " + hitStatus.skipped + " | " : "";
var missedStatus = (hitInfo.data.action.toLowerCase().indexOf("pantha") != -1) ? "Miss: " + hitStatus.missed + " | " : "";
var statusText = "[ Acc: " + hitStatus.accepted + " | " + skippedStatus + missedStatus + "Srch: " + hitStatus.searched + " ]";
$("#JRCellStatus_" + theNumber).html( statusText );
displayMainStatus();
}
function processResults( theNumber, result, finalUrl ) {
var hitInfo = (theNumber>0) ? gMainData.hitCollection[theNumber] : null;
var hitData = (hitInfo) ? hitInfo.data : null;
var hitStatus = (hitInfo) ? hitInfo.status : null;
var hitDataActionSix = (hitData) ? hitData.action.toLowerCase().substring(0,6) : "";
switch(result) {
case "NOTQUALIFIED":
if (hitStatus) hitStatus.notQual++;
hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
updateHitCell(theNumber);
break;
case "BLOCKED": // stop collecting this job. Change background to error color.
if (hitStatus) hitStatus.blocked++;
hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
updateHitCell(theNumber);
break;
case "NOACCEPT": // Missed a hit because someone else took it. So mad.
if (hitDataActionSix == "search" || hitDataActionSix == "pantha") { hitStatus.missed++; hitStatus.noHits++; gMainData.missed++; }
break;
case "NOMORE":
if (hitStatus) hitStatus.noHits++;
gMainData.noHits++;
break;
case "TOOFAST":
if (hitStatus) hitStatus.tooFast++;
gMainData.tooFast++;
if (gSlowDownAuto) theCycler.cycleIncrease(gMainOptions.cycleAutoIncrease);
if (finalUrl) {
var acceptPage = (finalUrl.indexOf("mturk/accept") != -1);
var previewPage = (finalUrl.indexOf("mturk/preview") != -1);
if (acceptPage || previewPage) {
if (hitDataActionSix == "search" || (hitDataActionSix == "pantha" && acceptPage)) {
if (gMainOptions.debugger>0) console.log("got a PRE for a search or pantha on: " + finalUrl); // debugger >0 for pre on search or pantha
hitInfo.goToUrl.push({"url":finalUrl,"theNumber":theNumber});
}
}
}
break;
case "LOGGEDOFF":
if (!theCycler.isPaused()) {
var addText = createDiv("You are logged out of Amazon.
Can't accept hits so pausing.
Please log back in!")
.css({"margin-top":"30px","font-size":"17px","text-align":"center","color":"red"})
.append(createDiv(createLink("Go to Mturk Page","https://www.mturk.com/mturk/myhits","_blank","https://www.mturk.com/mturk/myhits")
.click( function() {
window.open("https://www.mturk.com/mturk/myhits","_blank","width=" + 1000 + ",height=" + 800 + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
return false;
})).css({"color":"blue","margin-top":"15px"}));
showWaitDialog("Logged Out!!","",function() {
theCycler.unpause();
$("#JRPauseButton").html("Pause").css({"background-color":"ivory","color":"black"});
theCycler.frontOfTheLineTimer(-1);
},null,addText,true);
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
playThisSound("hasToPause");
}
break;
case "DAILYLIMIT":
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
alert("Congratulations!! You have reached your daily limit. Wait for tomorrow.");
break;
case "NOTCOMPLETED":
case "ERROR":
if (hitStatus) hitStatus.error++;
gMainData.error++;
break;
case "QUEUEMAX":
if (hitStatus) hitStatus.fullQueue++;
if (!gFullQueue) {
playThisSound("fullQueue");
gFullQueueTimer = setTimeout( function() { fullQueueTimer(); }, 240000 );
}
gFullQueue = true;
gMainData.fullQueue++;
break;
case "SKIPPED":
if (hitStatus) hitStatus.skipped++;
gMainData.skipped++;
break;
case "ACCEPTED":
if (hitStatus) hitStatus.accepted++;
if (hitInfo.ham == "ontimed") hitInfo.lastAccept = new Date();
var newDate = new Date().setHours(0,0,0,0);
if (hitData.dailyLimit && hitData.dailyLimit>0) hitData.dailyDone = (newDate == hitData.day) ? hitData.dailyDone + 1 : 1;
if (hitData.once) hitData.dailyDone = 1;
hitData.day = newDate;
gMainData.accepted++;
gMainData.hitsInQueue++;
thisKey = hitData.requesterName + "::" + hitData.title + "::" + hitData.pay;
gQueueCount[thisKey] = (thisKey in gQueueCount) ? gQueueCount[thisKey]+1 : 1;
if (gQueueCheckinProgress) queueDelay.push(hitInfo);
else addToQueueWatch(hitInfo);
var hitPay = parseFloat(hitData.pay);
gMainData.payCounter = gMainData.payCounter + hitPay;
gMainData.totalEarnings = gMainData.projectedEarnings + gMainData.payCounter;
var theDuration = hitInfo.minutes;
if (theDuration===0 && hitData.duration!="0") {
theDuration = (hitData.duration.indexOf("weeks")!=-1) ? 5000 : (hitData.duration.indexOf("day")!=-1) ? 1500 : (hitData.duration.indexOf("hours")!=-1) ? 200 :
(hitData.duration.indexOf("hour")!=-1) ? 60 : (hitData.duration.indexOf("minutes")!=-1) ? parseInt(hitData.duration.split("minutes")[0]) : 1;
hitInfo.durationParsed = getTimeLeft(hitData.duration);
hitInfo.minutes = theDuration;
}
var theSoundFile = "less99";
var notificationTitle = "Accepted Hit From: " + hitData.requesterName;
var notificationMessage = "Pay: " + hitData.pay + "\nDuration: " + hitData.duration + "\nTitle: " + hitData.title;
if (!hitData.mute) {
if ( hitPay < parseFloat(gAlarmSounds.less2.payRate) ) {
theSoundFile = (theDuration !== 0 && theDuration<=parseInt(gAlarmSounds.less2Short.lessMinutes)) ? "less2Short" : "less2";
} else if ( hitPay <= parseFloat(gAlarmSounds.less5.payRate) ) {
theSoundFile = (theDuration !== 0 && theDuration<=parseInt(gAlarmSounds.less5Short.lessMinutes)) ? "less5Short" : "less5";
} else if ( hitPay <= parseFloat(gAlarmSounds.less15.payRate) ) {
theSoundFile = (theDuration !== 0 && theDuration<=parseInt(gAlarmSounds.less15Short.lessMinutes)) ? "less15Short" : "less15";
} else if ( hitPay < parseFloat(gAlarmSounds.less99.payRate) ) { theSoundFile = "less99"; }
if (hitData.audioforce !== "") theSoundFile = hitData.audioforce;
playThisSound(theSoundFile);
}
if (gScriptStatus == "normal") {
$("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":"yellow"});
$("#JRCellNum_" + theNumber).animate({"backgroundColor": $("#JRCellNum_" + theNumber).data("backgroundColor")}, 40000);
}
if (gNotifications) showNotification( notificationTitle, notificationMessage, "accepted", hitData.groupId);
if ( hitInfo.ham == "paused" ) { toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff); }
addToAcceptedLog( hitData.requesterName + " - " + hitData.groupId + " - " + hitData.title );
updateHitCell(theNumber);
break;
}
if (theNumber > 0) displayHitStatus(theNumber);
}
function requestUrl(theUrl, theNumber, theFunction, errorFunction, data1, data2, theResponseType) {
theResponseType = theResponseType || "";
if (gMainOptions.debugger>1) console.log("JR going to get: " + theUrl); // debugger >1 for request details
GM_xmlhttpRequest({
method: "GET",
url: theUrl,
responseType: theResponseType,
onload: function(response) { if (typeof theFunction == 'function') theFunction(response,theNumber,data1,data2); },
onerror: function(response) { errorRequest(response,theNumber); }
});
}
function errorRequest(response,theNumber) {
if (response && response.error) {
console.log("error " + theNumber + ": " + response.error);
if (response.error.indexOf("https://www.amazon.com/ap/signin?")!=-1) processResults( theNumber, "LOGGEDOFF" );
}
}
function pandaLink(theGroupId) { return "https://www.mturk.com/mturk/previewandaccept?groupId=" + theGroupId; }
function pandaLinkNew(theGroupId) { return "http://worker.mturk.com/projects/" + theGroupId + "/tasks/accept_random?ref=w_pl_prvw"; }
function previewLink(theGroupId) { return "https://www.mturk.com/mturk/preview?groupId=" + theGroupId; }
function previewLinkNew(theGroupId) { return "http://worker.mturk.com/projects/" + theGroupId + "/tasks?ref=w_pl_prvw"; }
function continueLink(theHitId) { return "https://www.mturk.com/mturk/continue?hitId=" + theHitId; }
function returnLink(theHitId) { return "https://www.mturk.com/mturk/return?hitId=" + theHitId + "&inPipeline=false"; }
function requesterSearch(theRequester,minReward) { return "https://www.mturk.com/mturk/searchbar?selectedSearchType=hitgroups&qualifiedFor=on&pageSize=10&minReward=" + minReward + "&sortType=Reward%3A1&requesterId=" + theRequester; }
function requesterSearchNew(theRequesterID) { return "http://worker.mturk.com/requesters/" + theRequesterID + "/projects?ref=w_pl_prvw"; }
function termSearchNew(theTerm,theSize,theSort,qualified) {
qualified = qualified || "true";
return "https://worker.mturk.com/?filters%5Bsearch_term%5D=" + theTerm + "&page_size=" + theSize + "&page_number=1&sort=" + theSort + "&filters%5Bqualified%5D=" + qualified;
}
function acceptLink(theHitData) { return "https://www.mturk.com/mturk/accept?hitId=" + theHitData.hitId + "&prevHitSubmitted=" + theHitData.prevHitSubmitted +
"&prevRequester=" + theHitData.prevRequester + "&prevReward=" + theHitData.prevReward + "&requesterId=" + theHitData.requesterId + "&groupId=" +
theHitData.groupId + "&signature=" + theHitData.signature;
}
function setSearchOptionsDefault() {
var searchOptions = jQuery.extend(true, {}, gDefaultSearchOptions), searchHistory = jQuery.extend(true, {}, gDefaultSearchHistory);
return {"searchOptions":searchOptions,"searchHistory":searchHistory};
}
function checkLimits(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var returnValue = false;
var thisKey = hitData.requesterName + "::" + hitData.title + "::" + hitData.pay;
if (hitData.queueLimit === 0 && hitData.queueHitLimit === 0 && hitData.dailyLimit === 0 && !hitData.once) returnValue = true;
else if (hitData.once && hitData.dailyDone>0) {
if (hitInfo.hitCell.data("status")=="on") hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
returnValue = false; }
else if (hitData.queueHitLimit > 0 && (gQueueCount[thisKey] === "undefined" || gQueueCount[thisKey] >= hitData.queueHitLimit)) returnValue = false;
else if (hitData.queueLimit > 0 && hitData.queueLimit <= gMainData.hitsInQueue) returnValue = false;
else if (hitData.dailyLimit > 0 && hitData.dailyLimit < gMainData.dailyDone) returnValue = false;
else returnValue = true;
return returnValue;
}
function searchRequestersInfo( theNumber, hitNumber, requestersInfo ) {
var hitInfo = gMainData.hitCollection[hitNumber];
var hitData = hitInfo.data;
if (hitInfo.collecting != "off") {
hitInfo.status.searched++;
displayHitStatus(hitNumber);
for (var i=0, len=requestersInfo.data.length; i tbody > tr").each(function(i, row) {
var jobData = jQuery.extend(true, {}, gJobDataDefault);
var titleElement = $(row).find("#capsule" + i + "-0");
if (titleElement.length) {
jobData.title = $(titleElement).text().trim();
var titleLink = $(titleElement).closest("tr").find(".capsulelink a:first");
jobData.groupId = (titleLink.length) ? $(titleLink).attr("href").split("groupId=")[1] : "";
var returnLink = $(titleElement).closest("tr").find("a:contains('Return this HIT'):first");
jobData.returnURL = (returnLink.length) ? "https://www.mturk.com" + $(returnLink).attr("href") : "";
var continueLink = $(titleElement).closest("tr").find("a:contains('Continue work on this HIT'):first");
jobData.continueURL = (continueLink.length) ? "https://www.mturk.com" + $(continueLink).attr("href") : "";
jobData.hitId = (jobData.continueURL!=="") ? jobData.continueURL.split("hitId=")[1] : "";
var requesterElement = $(row).find(".requesterIdentity:first");
jobData.requesterName = (requesterElement.length) ? $(requesterElement).text().trim() : "";
var contactRequesterUrl = $(row).find("#capsule" + i + "target").find("a:contains('Contact the Requester of this HIT'):first");
jobData.requesterId = (contactRequesterUrl.length) ? $(contactRequesterUrl).attr("href").split("requesterId=")[1].split("&")[0] : "";
var durationToComplete = $(row).find("#duration_to_complete\\.tooltip--" + i);
jobData.duration = (durationToComplete.length) ? $(durationToComplete).closest("tr").find(".capsule_field_text").text().trim() : "";
jobData.durationParsed = getTimeLeft(jobData.duration);
var assignedOn = $(row).find("#assigned_on\\.tooltip--" + i);
jobData.assignedOn = (assignedOn.length) ? $(assignedOn).closest("tr").find(".capsule_field_text").text().trim() : "";
var description = $(row).find("#description\\.tooltip--" + i);
jobData.description = (description.length) ? $(description).closest("tr").find(".capsule_field_text").text().trim() : "";
var qualifications = $(row).find("#qualifications\\.tooltip--" + i);
jobData.qual = (qualifications.length) ? $(qualifications).closest("tr").find(".capsule_field_text").text().trim() : "";
var keywords = $(row).find("#keywords\\.tooltip--" + i);
jobData.keywords = (keywords.length) ? $(keywords).closest("tr").find(".capsule_field_text").text().trim() : "";
var timeLeft = $(row).find("#time_left\\.tooltip--" + i);
jobData.timeLeft = (timeLeft.length) ? $(timeLeft).closest("tr").find(".capsule_field_text").text().trim() : "";
jobData.totalSeconds = (jobData.timeLeft!=="") ? convertTimeToSeconds(getTimeLeft(jobData.timeLeft)) : 0;
var hitsAvailable = $(row).find("#number_of_hits\\.tooltip--" + i);
jobData.hitsAvailable = (hitsAvailable.length) ? $(hitsAvailable).closest("tr").find(".capsule_field_text").text().trim() : "";
var rewardElement = $(row).find("#reward\\.tooltip--" + i);
jobData.pay = (rewardElement.length) ? $(rewardElement).closest("tr").find(".reward").text().replace("$","").trim() : "";
jobDatas.push(jobData);
}
});
return jobDatas;
}
function createHitRow(theData,buttons,fromWhere) {
var durationTime = (theData.duration != "Time") ? getTimeLeft(theData.duration) : theData.duration;
var durationText = (theData.duration != "Time") ? ((durationTime) ? durationTime.hours + ":" + ("0" + durationTime.minutes).slice(-2) : "0.00") : theData.duration;
var payText = (theData.pay == "Pay") ? theData.pay : "$" + theData.pay;
var dialogWidth = $("#JREditDialog").width();
var titleWidth = (fromWhere=="jobs") ? 500 : 450;
var hitInfo = (theData.jobNumber != "-1") ? gMainData.hitCollection[parseInt(theData.jobNumber)] : null;
var hitRow = createDiv().attr({"class":"hitRow"}).data("hitData",theData);
if (fromWhere=="jobs") hitRow.append(createCheckbox().css({"margin":"-15px 2px 0 0","padding":"0","display":"inline-block"}).data({"hitData":theData}));
hitRow.append(createSpan((theData.friendlyRName!=="") ? theData.friendlyRName : theData.requesterName).attr({"class":"aHitColumn"})
.css({"background-color":"#FBF5E6","width":"140px","text-align":"right","border":"1px solid black"}))
.append(createSpan((theData.friendlyTitle!=="") ? theData.friendlyTitle : theData.title).attr({"class":"aHitColumn"})
.css({"background-color":"#FCF6CF","width":(dialogWidth - titleWidth) + "px","text-decoration":"underline","cursor":"pointer"})
.click( function(e) {
var thisData = $(e.target).closest(".hitRow").data("hitData");
var theHeight=window.outerHeight-80; var theWidth=window.outerWidth-10;
window.open(previewLink(thisData.groupId),"_blank","width=" + theWidth + ",height=" + theHeight + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
}))
.append(createSpan(durationText).attr({"class":"aHitColumn"}).css({"background-color":"#F5F5DC","width":"35px"}));
if (fromWhere=="mturk") hitRow.append(createSpan(theData.hitsAvailable).attr({"class":"aHitColumn"}).css({"background-color":"#F0FFFF","width":"40px"}));
hitRow.append(createSpan(payText).attr({"class":"aHitColumn"}).css({"background-color":"#7FFFD4","width":"40px"}));
if (fromWhere=="jobs") {
if (theData.duration != "Time") {
var theStatus = hitInfo.hitCell.data("status");
var theCell = hitInfo.hitCell;
var thisBgColor = $(theCell).find(".JRCollectButton").css("background-color");
var thisColor = $(theCell).find(".JRCollectButton").css("color");
hitRow.append(createSpanButton(function(e) {
hitInfo.hitCell.find(".JRCollectButton").click();
var theClone = $(e.target).data("clone");
$(e.target).css({"background-color":theClone.css("background-color"),"color":theClone.css("color")});
},"Collect",$(theCell).find(".JRCollectButton").css("background-color"),$(theCell).find(".JRCollectButton").css("color"),"10px")
.css({"white-space":"nowrap","overflow":"hidden","display":"inline-block"}).data({"status":theStatus,"clone":$(theCell).find(".JRCollectButton")}));
hitRow.append(createSpanButton(function(e) {
showEditHitDialog(theData.jobNumber,$(e.target),function() { showSearchingDialog($("#JREditDialog").data("savedButton"),"jobs"); });
},"Details",gButtonOffBgColor,gButtonOffColor,"10px").css({"white-space":"nowrap","overflow":"hidden","display":"inline-block"}).data({"status":theStatus}));
} else {
}
}
if (buttons) hitRow.append(createSpanButton( function(e) {
var thisData = $(e.target).closest(".hitRow").data("hitData");
var newNumber = fillNewHitData(thisData.requesterName, thisData.requesterId, thisData.groupId, thisData.pay,
thisData.title, thisData.duration, false, true, true);
gMainData.hitCollection[newNumber].numberHits = thisData.hitsAvailable;
},"Panda",gButtonOffBgColor,gButtonOffColor,"10px").css({"white-space":"nowrap","overflow":"hidden","display":"inline-block"}))
.append(createSpanButton( function(e) {
var thisData = $(e.target).closest(".hitRow").data("hitData");
var newNumber = fillNewHitData(thisData.requesterName, thisData.requesterId, thisData.groupId, thisData.pay,
thisData.title, thisData.duration, true, true, true);
gMainData.hitCollection[newNumber].numberHits = thisData.hitsAvailable;
},"Once",gButtonOffBgColor,gButtonOffColor,"10px").css({"white-space":"nowrap","overflow":"hidden","display":"inline-block"}));
if (theData.duration == "Time") $(hitRow).find("input").click( function(e) {
$(e.target).closest(".searchingResultsArea").find("input").prop("checked",$(e.target).prop("checked"));
});
return hitRow;
}
function parseHitSearchPage(theResult,theNumber,searchWhere) {
var hitInfo = (theNumber>0) ? gMainData.hitCollection[theNumber] : null;
var hitData = (hitInfo) ? hitInfo.data : null;
var finalUrl = theResult.finalUrl;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(theResult.responseText,"text/html");
var errorTitle_Array = xmlDoc.getElementsByClassName("error_title");
var errorTitle = (errorTitle_Array.length) ? errorTitle_Array[0] : null;
var searchArea = (searchWhere=="mturk") ? $("#JRSavedMturkArea") : $("#JRSavedJobsArea");
if (errorTitle && errorTitle.innerHTML.indexOf("You have exceeded the maximum allowed page request rate") != -1) {
processResults( theNumber, "TOOFAST", finalUrl );
return;
} else if (errorTitle && errorTitle.innerHTML.indexOf("Your search did not match any HITs") != -1) {
if (theNumber<=0) {
$(searchArea).find(".searchingResultsArea").html("");
$(searchArea).find(".searchingResultsArea").append(createDiv("Nothing Found! Sorry.").css({"font-size":"25px","margin-top":"200px","text-align":"center"}));
gSavedSearchArea = "";
}
return;
} else {
var requestersInfo = doSortResultsTable(xmlDoc);
if (requestersInfo.length > 0) {
if (gMainOptions.debugger>1) console.log("JR HitsearchPage : I found some hits: " + requestersInfo.length); // debugger >1 for SearchPage details
var goUrl = "";
if (theNumber<=0) {
$(searchArea).find(".searchingResultsArea").html("");
var captions = {"requesterName":"Requester Name","title":"Hit Title","duration":"Time","hitsAvailable":"# Hits","pay":"Pay","collect":"caption"};
var dialogWidth = $("#JREditDialog").width();
$(searchArea).find(".searchingResultsArea").append(createHitRow(captions,false,searchWhere));
$(searchArea).find(".searchingResultsArea").append(createDiv()
.css({"margin-left":"5px","margin-top":"0px","background-color":"black","height":"6px","width":(dialogWidth - 145) + "px"}));
for (var ii=0, len1=requestersInfo.length; iiPausing.")
.css({"margin-top":"30px","font-size":"17px","text-align":"center","color":"red"})
.append(createDiv(createLink("Go to Mturk Page",hitInfo.pandaUrl,"_blank",hitInfo.pandaUrl)
.click( function(e) {
window.open($(e.target).attr("href"),"_blank","width=" + 1200 + ",height=" + 900 + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
return false;
})).css({"color":"blue","margin-top":"15px"}));
showWaitDialog("Captcha Alert!!","",function() {
theCycler.unpause();
$("#JRPauseButton").html("Pause").css({"background-color":"ivory","color":"black"});
},null,addText,true);
if (!theCycler.isPaused()) {
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
playThisSound("hasToPause");
}
}
return;
}
var hitAccepted = $(xmlDoc).find("img[src$='/media/return_hit.gif']");
var notAccepted = $(xmlDoc).find("input[src$='/media/accept_hit.gif']");
if (errorTitle && errorTitle.innerHTML.indexOf("Your request was not completed successfully") != -1) {
processResults( theNumber, "NOTCOMPLETED", finalUrl );
} else if (dailyLimit) {
processResults( theNumber, "DAILYLIMIT", finalUrl );
} else if (hitAccepted.length) {
var updated = false;
var hitGroupId = ($(xmlDoc).find("form[name='hitForm']").length) ? $(xmlDoc).find("form[name='hitForm']").eq(0).find("input[name='groupId']").eq(0).val() : "";
hitData.groupId = hitGroupId;
hitInfo.pandaUrl = pandaLink(hitData.groupId);
hitInfo.previewUrl = previewLink(hitData.groupId);
hitInfo.hitId = ($(xmlDoc).find("form[name='hitForm']").length) ? $(xmlDoc).find("form[name='hitForm']").eq(0).find("input[name='hitId']").eq(0).val() : "";
var capsuleNode = $(xmlDoc).find("td.capsulelink_bold:first div").eq(0);
var theTitle = (capsuleNode.length) ? $(capsuleNode).html().trim() : hitData.title;
if (hitData.title != theTitle) { hitData.title = theTitle; updated=true; }
var timeLeft = $(xmlDoc).find("a#time_left\\.tooltip");
var theDuration = (timeLeft.length) ? timeLeft.parent().next().html().trim() : hitData.duration;
if (hitData.duration != theDuration) { hitData.duration = theDuration; updated=true; }
var requesterTip = $(xmlDoc).find("#requester\\.tooltip");
var requesterNameNode = (requesterTip.length) ? $(requesterTip).parent().next() : null;
var theRequesterName = (requesterNameNode.length) ? ( ($(requesterNameNode).find("a").length) ? $(requesterNameNode).find("a").html().trim() : $(requesterNameNode).html().trim() ) : "";
theRequesterName = (theRequesterName) ? theRequesterName : hitData.requesterName;
if (hitData.requesterName != theRequesterName) { hitData.requesterName = theRequesterName; updated=true; }
var numberHitsTip = $(xmlDoc).find("#number_of_hits\\.tooltip");
var theNumberHits = (numberHitsTip.length) ? numberHitsTip.parent().next().html().trim() : hitInfo.numberHits;
hitInfo.numberHits = theNumberHits;
var rewardTip = $(xmlDoc).find("#reward\\.tooltip");
var theReward = (rewardTip.length) ? rewardTip.parent().next().find("span").html().replace("$","").trim() : hitData.pay;
if (hitData.pay != theReward) { hitData.pay = theReward; updated=true; }
processResults( theNumber, "ACCEPTED", finalUrl );
if (updated) gDelayedSave = true;
if (gMainOptions.debugger>1) console.log("accepted: " + theNumber + " | updated: " + updated + " | groupId: " + hitGroupId); // debugger >1 for accepting stats
} else if (notAccepted.length) {
var formData = {};
formData.hitId = $(xmlDoc).find("input[name='hitId']").eq(0).val();
formData.prevHitSubmitted = $(xmlDoc).find("input[name='prevHitSubmitted']").eq(0).val();
formData.prevRequester = $(xmlDoc).find("input[name='prevRequester']").eq(0).val();
formData.requesterId = $(xmlDoc).find("input[name='requesterId']").eq(0).val();
formData.prevReward = $(xmlDoc).find("input[name='prevReward']").eq(0).val();
formData.groupId = $(xmlDoc).find("input[name='groupId']").eq(0).val();
formData.signature = $(xmlDoc).find("input[name='signature']").eq(0).val();
var iframeSrc = $(xmlDoc).find("iframe").attr("src");
var acceptHitURL = acceptLink(formData);
var useAcceptHit = false;
if (iframeSrc && formData.requesterId=="AGVV5AWLJY7H2") {
if (hitData.filterMode>0 && hitData.filterMode <= Object.keys(gZingFuncOptions).length) {
requestUrl(iframeSrc, theNumber, gZingFuncOptions[hitData.filterMode].functionName, errorRequest, formData, "");
} else { useAcceptHit = true;}
}
if (hitData.action.toLowerCase().indexOf("pantha")!=-1 || useAcceptHit) {
hitInfo.goToUrl.push({"url":acceptHitURL,"theNumber":theNumber});
if ( hitInfo.ham == "paused" ) toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff);
else theCycler.frontOfTheLine(theNumber);
}
} else { processResults( theNumber, "ERROR", finalUrl ); }
}
function makeStatus() { return {"accepted":0,"skipped":0,"errors":0,"tooFast":0,"noHits":0,"fullQueue":0,"hitsStreak":0,
"noHitsStreak":0,"searched":0,"orphan":0,"hitsResults":0,"notQual":0,"missed":0,"blocked":0}; }
function makeCollection(pandaUrl,previewUrl,theNumber,theData,addStatus,filterFuncData,tabIndex) { return {"collecting":"off","pandaUrl":pandaUrl,"previewUrl":previewUrl,
"goToUrl":[],"theNumber":theNumber,"data":theData,"status":(addStatus) ? makeStatus(): null,"specialOptions":null,"hitCell":null,"ham":"off","minutes":0,
"newTitle":"","numberHits":"0","once":false,"filterFuncData":filterFuncData,"searching":"off","lastAccept":null,
"tabIndex":tabIndex,"hitId":"","durationParsed":null,"dateDone":null,"elapsedSeconds":0};
}
function addHitCollection(theData,theNumber,tabIndex) {
var pandaUrl = pandaLink(theData.groupId);
var previewUrl = previewLink(theData.groupId);
var filterFuncData = (theData.action.toLowerCase().indexOf("filter") != -1) ? ((theData.requesterId=="AGVV5AWLJY7H2") ? gZingFuncOptions : null) : null;
gMainData.hitCollection[theNumber] = makeCollection(pandaUrl,previewUrl,theNumber,theData,true,filterFuncData,tabIndex);
return theNumber;
}
function addQueueCheck() {
theCycler.addJob( function( elapsed, theNumber ) {
gQueueCheckinProgress=true;
gMainData.queueStatus.searched++;
requestUrl("https://www.mturk.com/mturk/sortmyhits?searchSpec=HITSearch%23T%231%2310%23-1%23T%23!Status!0!rO0ABXQACEFzc2lnbmVk!%23!Deadline!0!%23!&selectedSearchType=hitgroups&searchWords=&sortType=Deadline%3A0&pageSize=25",1,function(theResult,theNumber,data1,data2) {
displayMainStatus();
return parseQueuePage(theResult);
},function() { errorRequest(); } );
return true;
}, -1, gMainOptions.queueTimer);
}
function addExternalScriptCheck() {
setInterval( function() {
var sendQueue=null,sendPE=null;
$.each(gExternalData, function( index, value ) {
if (!value.gotPong) delete gExternalData[index];
value.setPing=true; value.gotPong=false;
if (value.mode=="needQueue") { sendQueue=gQueueData; sendPE=gMainData.projectedEarnings; }
});
sendPingMessage("",{"queue":sendQueue,"queueChanged":false,"PE":sendPE},null);
return true;
}, 1000);
}
function startCollecting(theNumber,thisButton) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
if (hitData.once) hitData.dailyDone = 0;
hitInfo.collecting = "on";
theCycler.addJob( function( elapsed, theNumber ) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var hitStatus = hitInfo.status;
var thisNewDate = new Date();
if (hitInfo.ham == "ontimed") {
if (hitData.hamTimer > 0 && hitInfo.lastAccept!==null) {
var accElapsedTime = thisNewDate - hitInfo.lastAccept;
var theSeconds = accElapsedTime / 1000;
var offHamMode = (hitInfo.ham == "ontimed") ? "paused" : "off";
if (theSeconds >= hitData.hamTimer) {
toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff,offHamMode);
hitInfo.lastAccept = null;
}
}
}
if ( checkLimits(theNumber) ) {
var theUrl = "";
var hitDataAction = hitData.action.toLowerCase();
hitInfo.elapsedSeconds = (hitInfo.dateDone) ? (Math.round( ((thisNewDate - hitInfo.dateDone)/1000) * 10 ) / 10) : 0;
hitInfo.dateDone = thisNewDate;
hitStatus.searched++;
if (hitDataAction.substring(0,6) == "search" && hitData.searchData===null) hitData.searchData = setSearchOptionsDefault();
var searchOptions = hitData.searchData.searchOptions;
if (hitInfo.goToUrl.length) {
if ( (hitDataAction.substring(0,6) == "search" || hitDataAction == "filterpanda" || hitDataAction == "pantha") && !hitInfo.hitCell.data("saveSearchGroupId") )
theUrl = (hitInfo.goToUrl.shift()).url;
else theUrl = (hitInfo.goToUrl[0]).url;
} else {
theUrl = ( hitDataAction == "panda" ) ? hitInfo.pandaUrl : (hitDataAction.substring(0,6) == "search") ?
requesterSearch(hitData.requesterId,searchOptions.minReward) : hitInfo.previewUrl;
}
gMainData.searched++;
gMainData.lastElapsed = elapsed;
if (gMainOptions.debugger>1) console.log("Doing Number: " + theNumber + " | going to: " + theUrl); // debugger >1 for doing details
if (theUrl.indexOf("selectedSearchType=hitgroups")!=-1) requestUrl(theUrl,theNumber,parseHitSearchPage,
errorRequest, hitStatus.searched, "");
else requestUrl(theUrl,theNumber,parseMturkHitPage, errorRequest, hitStatus.searched, "");
displayHitStatus(theNumber);
addToStatusLog(theNumber);
return true;
} else if (gScriptStatus == "normal") {
$("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":"#FF9999"});
$("#JRCellNum_" + theNumber).animate({"backgroundColor": $("#JRCellNum_" + theNumber).data("backgroundColor")}, 40000);
return false;
}
}, theNumber, 0, false, hitData.weight);
gMainData.jobs++;
//addQueueCheck();
}
function stopCollecting(theNumber,thisButton) {
if (gMainOptions.debugger>1) console.log("turning off " + theNumber); // debugger >1 for collecting info
if (gMainData.hitCollection[theNumber].collecting == "on") {
setTimeout( function() { if (!gMainData.hitCollection[theNumber] || gMainData.hitCollection[theNumber].collecting == "off") removeFromStatusLog(theNumber); },9000);
gMainData.hitCollection[theNumber].collecting = "off";
gMainData.hitCollection[theNumber].goToUrl.splice(0,gMainData.hitCollection[theNumber].goToUrl.length);
theCycler.removeJob(theNumber);
gMainData.jobs--;
}
displayHitStatus(theNumber);
}
function stopAll() {
$.each(gMainData.hitCollection, function( index, value ) {
if (value.collecting == "on") {
toggleButton( $("#JRCollectB_" + index),startCollecting,stopCollecting);
if (value.collecting=="off" && value.ham != "off") toggleButtonOff($("#JRHamB_" + index),hamOn,hamOff);
}
});
}
function hamOn(theNumber,thisButton) {
var onMode = "on";
var hitInfo = gMainData.hitCollection[theNumber];
$(".JRHamButton").each( function() {
if ( $(this).data("theNumber") != theNumber ) $(this).data("disabled",true);
updateHitColors($(this).data("theNumber"));
});
if (hitInfo.ham == "paused") {
onMode = "ontimed";
if (hitInfo.data.hamTimer > 0) hitInfo.lastAccept = new Date();
}
hitInfo.ham = onMode;
theCycler.hamOn(theNumber);
theCycler.skippingReset();
theCycler.cycleResetChange(gMainOptions.HamCycleNumber);
}
function hamOff(theNumber,thisButton,theMode) {
var passedMode = theMode || "";
var hitInfo = gMainData.hitCollection[theNumber];
if (hitInfo.ham.substring(0,2) == "on") {
$(".JRHamButton").each( function() {
if ( $(this).data("disabled") ) $(this).data("disabled",false);
updateHitColors($(this).data("theNumber"));
});
cycleButtonSelect(gMainOptions.savedCycleNum);
theCycler.hamOff();
theCycler.skippingReset();
}
hitInfo.lastAccept = null;
if (passedMode === "" && hitInfo.ham == "ontimed" && hitInfo.collecting != "off") passedMode = "paused";
gMainData.hitCollection[theNumber].ham = (passedMode==="") ? "off" : passedMode;
saveGroupIdSearching(hitInfo,false);
}
function muteJob(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber];
hitInfo.data.mute = !hitInfo.data.mute;
hitInfo.hitCell.data("mute",hitInfo.data.mute);
updateHitColors( theNumber );
saveSettings();
}
function helpToolTips() {
if (gMainOptions.showHelpTooltips) $(".hasHelptip").tooltip( "option", "disabled", false );
else $(".hasHelptip:not(.keepHelptip)").tooltip( "option", "disabled", true );
}
function createBlankDiv() {
return createDiv(" ").attr("class","JRHitCell JRHitBlank").css({"border":"3px solid black", "margin":"2px 4px", "float":"left", "width":"206px", "height":"76px"});
}
function addTab(tabContainer,theTitle,isSortable,theID,tabData,appendClose) {
var theTab = createTab(tabContainer,theTitle,isSortable,theID,tabData,appendClose)
.data({"tabData":tabData});
createDiv().insertBefore(theTab.find("br.cleartab"))
.data({"tabData":tabData})
.attr({"class":"tabContents connectedSortable"})
.css({"overflow":"auto"})
.droppable({ tolerance: 'pointer', drop: moveToTab })
.sortable({dropOnEmpty: true,delay:400,tolerance: "pointer","items":".JRHitCell:not(.ui-not-sortable)",
helper:"clone",opacity: 0.9,appendTo:"body",
start: function( event, ui ) {
ui.item.addClass('noclick');
ui.item.data("oldPosition",ui.item.index());
ui.item.data("sameTab",true);
},
stop: function( event, ui ) {
if (ui.item.data("hitInfo") && !ui.item.data("received")) {
var thePositions = gTabsData[ui.item.data("hitInfo").tabIndex].positions;
thePositions.splice(ui.item.index(), 0, thePositions.splice(ui.item.data("oldPosition"), 1)[0]);
saveSettings();
}
}
});
return theTab;
}
function fillNewHitData(requesterName, requesterId, groupId, pay, title, duration, onlyOnce, toMain, collectNow) {
var active = (toMain) ? 0 : $( "#JRMainTabs" ).tabs( "option", "active" );
var newHitData = jQuery.extend(true, {}, gDefaultRequestersData[0]);
newHitData.action = "panda"; newHitData.qual = ""; newHitData.queueLimit = 0; newHitData.audioforce = ""; newHitData.hitlimit = ""; newHitData.mute = false;
newHitData.position = null; newHitData.tabNumber = gTabsData[active].tabNumber; newHitData.hamTimer = (gMainOptions.hamDelayTimer) || gDefaultMainOptions.hamDelayTimer;
newHitData.once = onlyOnce; newHitData.requesterName = (requesterName) || ""; newHitData.requesterId = (requesterId) || ""; newHitData.groupId = groupId;
newHitData.searchData = setSearchOptionsDefault();
newHitData.pay = (pay) || "0.00"; newHitData.title = (title) || groupId; newHitData.duration = (duration) || "";
var newCell = addHitData(newHitData,active);
if (collectNow) {
newCell.data("status","on");
toggleButton( newCell.find(".JRCollectButton"),startCollecting,stopCollecting );
}
if (theCycler.isHamOn()) newCell.find(".JRHamButton").data("disabled",true);
updateHitCell(newCell.data("theNumber"));
updateHitColors(newCell.data("theNumber"));
return newCell.data("theNumber");
}
function changeToEdited(idName) { $("#"+idName).data("edited",true); $("div[aria-describedby=" + idName+ "] .ui-dialog-buttonpane button:contains('Save')").button().show(); }
function inputNumMS(thisOne,isMS) {
if (isMS) $(thisOne).parent().find(".theInputEdit").val(convertToSeconds(parseInt(thisOne.value),3));
else $(thisOne).parent().find(".theInputEdit2").val(convertToMilliseconds(parseFloat(thisOne.value)));
}
function dataEdited(idName,thisArea,theValue,extraValue) {
extraValue = extraValue || null;
var inputEdit1 = null, inputEdit2 = null, input1Label="", setValue=theValue;
changeToEdited(idName);
$(thisArea).off("click");
if (extraValue) setValue = (extraValue=="seconds") ? setValue : convertToSeconds(parseInt(theValue),3);
inputEdit1 = createTextInput(setValue).attr("class","theInputEdit").css({"width":"300px"});
if ($(thisArea).data("seconds2ms")) {
input1Label = " Seconds: ";
$(inputEdit1).css({"width":"50px"});
inputEdit2 = createTextInput(convertToMilliseconds(parseFloat(theValue))).attr("class","theInputEdit2").css({"width":"50px"});
}
var inputEditSpan = createSpan(input1Label).append(inputEdit1);
if (inputEdit2) inputEditSpan.append(createSpan(" Milliseconds: ")).append(inputEdit2);
if ($(thisArea).data("doClick")) $(inputEdit1).click( function(e) { $(thisArea).data("doClick")(e); });
$(inputEdit1).focus( function(e) {
if ($(e.target).closest(".editLine").data("doFocus") && !$(e.target).closest(".editLine").data("focusOff")) $(e.target).closest(".editLine").data("doFocus")(e);
$(e.target).select();
});
if (inputEdit2) {
$(inputEdit2).focus( function(e) { $(e.target).select(); });
$(inputEdit1).on( "input", function() { if (this.value==="") { this.value=0; $(this).select(); } inputNumMS(this,false); });
$(inputEdit2).on( "input", function() { if (this.value==="") { this.value=0; $(this).select(); } inputNumMS(this,true); });
} else {
if ($(thisArea).closest(".editLine").data("doInput")) $(inputEdit1).on( "input", function() { $(this).closest(".editLine").data("doInput")(); });
}
$(thisArea).find("span:not(.errorEditLine):not(.defaultEdit):not(.optionButton)").replaceWith(inputEditSpan);
$(inputEdit1).focus();
}
function dataIncDecNumber(idName,currentNumber,limitNumber) {
return createSpan().append(createSpanButton( function(e) {
var numberIncDec = $(e.target).parent().find(".numberIncDec");
var theNumber = parseInt(numberIncDec.html());
theNumber = (theNumber>0) ? theNumber-1 : 0;
numberIncDec.html(theNumber);
changeToEdited(idName);
},"<",gButtonOffBgColor,gButtonOffColor,"9px"))
.append(createSpan(currentNumber.toString()).attr({"class":"numberIncDec"})).append(createSpanButton( function(e) {
var limitNumber = $(e.target).data("limitNumber");
var numberIncDec = $(e.target).parent().find(".numberIncDec");
var theNumber = parseInt(numberIncDec.html());
theNumber = (theNumber",gButtonOffBgColor,gButtonOffColor,"9px").data({"limitNumber":limitNumber}));
}
function dataTrueFalse(idName,thisArea,theValue) {
changeToEdited(idName);
if (theValue) returnValue=false;
else returnValue=true;
$(thisArea).find("span").html(returnValue.toString());
return returnValue;
}
function dataRadioButtons(idName,theName,theValues,theValue,theChangeFunction) {
var radioButtons = createSpan().data("changeFunction",theChangeFunction);
$.each(theValues, function(index, value) {
var valueID = value.toLowerCase();
var aRadio = createRadioButton(theName,valueID).attr({"id":valueID + "_radio_" + index}).css({"width":"20px"});
if (valueID == theValue) aRadio.prop("checked",true);
else aRadio.prop("checked",false);
createSpan().append(aRadio).append($("