// ==UserScript==
// @name JR Mturk Panda Crazy
// @version 0.5.1
// @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 mturkcrowd.com and mturkgrind.com) johnnyrs@allbyjohn.com
// @include http*://www.mturk.com/mturk/welcome?pandacrazy=on*
// @include http*://worker.mturk.com/?filters[search_term]=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-modal/0.8.0/jquery.modal.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 jQueryModalCSS https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.8.0/jquery.modal.min.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
// @connect ns4t.net
// @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.5.1";
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 gLocation = window.location.href, gLastQueueCheck = null, gNumId=0, gQueueCheckinProgress=false, queueDelay=[], gNotifications = true, gExtInterval = null;
var gSlowDownAuto = true, gDelayedSave = false, gScriptStatus = "normal", gFullQueue = false, gFullQueueTimer = null, gTemplateHitCell = null, gNewSite = false;
var gSavedSearchArea = "", gSavedAddUrl = "", gMyLayout = null, gAcceptedLogTab = null, gStatusLogTab = null, gQueueWatchTab = null, gTemplateHitRow = null;
var gQueueHelperVersion = "", gQueueHelperFormat2 = false, gSendQueue=false, gMturkDate = "", gJRPOP = null;
var gMainData = {"hitCollection":{},"displayInfo":"1","accepted":0,"skipped":0,"errors":0,"searched":0,"noHits":0,"fullQueue":0,"orphan":0,"tooFast":0,"tooFastHam":0,"tooFastNormal":0,
"savedCycleNum":1,"hitsInQueue":0,"queueStatus":null,"notQual":0,"lastElapsed":0,"jobs":0,"payCounter":0.00,"totalEarnings":0.00,"projectedEarnings":0.00,
"missed":0,"captchaCounter":0};
var gMainMenu = [{"name":"Main","theobject":null}], gNewOldSite = false;
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":"4","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,"timeCount":0,"extName":"","extVersion":""};
var gSearchOptionsData = {"filterInclude":"","filterExclude":"",pay:"0","payHigher":true,"toCheck":3,"remember":false};
var gDefaultSearchOptions = {"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"};
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,"captchaCountText":true,"captchaAt":35,"fastPantha":false,"showAlertNotify":true,"fastSearch":false,"stopAutoSlow":false};
var gRequestersData = {}, gRequestersKeys = [];
var gJobDataDefault = {"requesterName":"","requesterId":"","groupId":"","pay":"","title":"","duration":"0","hitsAvailable":0,"timeLeft":"","totalSeconds":0,"hitId":"","qual":"",
"continueURL":"","returnURL":"","durationParsed":{},"jobNumber":"-1","friendlyRName":"","friendlyTitle":"","assignedOn":"","description":"","keywords":"","timeData":{}};
var gDefaultRequestersData = {
"0":{"requesterName":gDatabaseVersion,"requesterId":28,"action":gScriptVersion,"groupId":"","pay":"","qual":"","title":"","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[]},"theHistory":{},"excludeGID":[],"maxReward":"0.00"},"dateAdded":null,"stickyDelayedHam":false},
"4":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3YVLYSYEBF5EJAO35WSGKPFABSF0QM","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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":15,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"5":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3BH1IVA3VJXE20OLEULG3K8PC6Q1RU","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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":15,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"6":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3ZXRRTK2NDCB5NW5M24C9P2OWG41OF","pay":"0.01","qual":"ibotta","title":"Does this receipt contain the following?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"7":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3NYGPW9OTYRQLJTE9DQJQJRQJ2IZPS","pay":"0.01","qual":"","title":"Does this receipt contain the following?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"8":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3R35RPFD7JUTQN8612HRYP7E6LZ1PV","pay":"0.03","qual":"ibotta","title":"Does this receipt contain the following?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"9":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3ZXRRTK2NDCB5NW5M24C9P2OVF61OE","pay":"0.03","qual":"","title":"Does this receipt contain the following?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":8,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"10":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3CRC4NO2BIQQWQ3GX0HLFPTFOD30SA","pay":"0.05","qual":"ibotta","title":"Does this receipt contain the","queueLimit":0,"duration":"60 minutes","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":12,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"11":{"requesterName":"Ibotta","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3787DLY3Y49RIF1DIJQB3Z8BUNP1T2","pay":"0.05","qual":"","title":"Does this receipt contain the following?","queueLimit":0,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":12,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"14":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"3YS67JKWJAZLQB11QU6O537NDYZ4X9","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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false},
"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,"oneDone":0,"day":"","filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0,"weight":0,"searchData":{"searchOptions":{"excludeTerm":[],"includeTerm":[],"minReward":"0.00","historyArray":[],"excludeGID":[],"maxReward":"0.00"},"theHistory":{}},"dateAdded":null,"stickyDelayedHam":false}
};
var gExcludeIds = ["38FT9G80DL83PUCSQBVANJBIKGSLHM"], jqUI_CssSrc = GM_getResourceText("jQueryUICSS");
var jqUI_ModalSrc = GM_getResourceText("jQueryModalCSS"), jqLayout_CssSrc = GM_getResourceText("jQueryLayoutCSS");
function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1), jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
};
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
};
function tooltipCreateFix(theElement,theDelay) {
$(theElement).tooltip({ show: {delay:theDelay}, close: function () { $(this).tooltip("destroy"); tooltipCreateFix($(this),theDelay); helpToolTips(); } });
}
function formatAMPM(theFormat,theDate,theTimeZone) {
var d = (theDate) ? theDate : new Date();
if (theTimeZone == "mturk") {
var mturkTZOffset = -8, today = new Date(); if (today.dst()) mturkTZOffset++;
var utc = d.getTime() + (d.getTimezoneOffset() * 60000), MturkTime = utc + (3600000 * mturkTZOffset);
d = new Date(MturkTime);
}
var minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours(), ampm = hours >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
hours = (hours>= 12) ? (hours-12) : hours;
hours = (hours.toString().length == 1) ? '0'+hours : hours;
if (theFormat=="short") return ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + '-' + d.getFullYear() + '(' + hours + ':' + minutes + ampm + ')';
else if (theFormat=="dayandtime") return days[d.getDay()] + ' ' + 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, 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 convertSecondsToTimeData(seconds) {
var timeData = {};
timeData.weeks = Math.floor(seconds/604800); seconds = seconds - (timeData.weeks*604800);
timeData.days = Math.floor(seconds/86400); seconds = seconds - (timeData.days*86400);
timeData.hours = Math.floor(seconds/3600); seconds = seconds - (timeData.hours*3600);
timeData.minutes = Math.floor(seconds/60); seconds = seconds - (timeData.minutes*60);
timeData.seconds = seconds;
return timeData;
}
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, alertIcon ) {
if (gMainOptions.disableNotifications) return;
showNotification.tagNumber = showNotification.tagNumber || 0; showNotification.lastGroupID = showNotification.lastGroupID || "0";
if (showNotification.lastGroupID != groupId) showNotification.tagNumber++;
showNotification.lastGroupID = groupId;
if (alertIcon) iconUrl = "https://pandacrazy.allbyjohn.com/mturk/Messaging-Alert-Icon.png";
else iconUrl = "https://pandacrazy.allbyjohn.com/mturk/Messaging-Online-icon.png";
var n = new Notification(title, {
body: message, icon: iconUrl,
tag: tag+showNotification.tagNumber});
if (navigator.userAgent.search("Chrome") >= 0) n.onshow = function () { setTimeout(n.close.bind(n), 21000); };
}
function parseVersionString (str) {
var x = str.split('.');
var maj = parseInt(x[0]) || 0; var min = parseInt(x[1]) || 0; var pat = parseInt(x[2]) || 0;
return {"major": maj, "minor": min, "patch": pat};
}
function checkVersion(greaterThanVersion,newVersion) { // Check if newVersion is GREATER than the greaterThanVersion
var greaterThanVersionObj = parseVersionString(greaterThanVersion), newVersionObj = parseVersionString(newVersion);
if (newVersionObj.major > greaterThanVersionObj.major ) return true;
else if (greaterThanVersionObj.major==newVersionObj.major) {
if (newVersionObj.minor > greaterThanVersionObj.minor) return true;
else if (greaterThanVersionObj.minor==newVersionObj.minor && newVersionObj.patch > greaterThanVersionObj.patch) return true;
}
return false;
}
// Database using setValue and getValue
function defaultFillIn(data,defaultData) { if (!data) return null; for (var key in defaultData) { if (!(key in data)) data[key] = defaultData[key]; } }
function convertDatabase(theObject,key) {
if (theObject[key].searchData) {
if (theObject[key].searchData===null) theObject[key].searchData=setSearchOptionsDefault();
if (!theObject[key].searchData.searchOptions) theObject[key].searchData.searchOptions = JSON.parse(JSON.stringify(gDefaultSearchOptions));
if (!theObject[key].searchData.theHistory ) theObject[key].searchData.theHistory = {};
theObject[key].searchData.searchHistory = null;
}
if (theObject[key].action===null) theObject[key].action="Panda";
if (isNumeric(theObject[key].day)) theObject[key].day="";
if (theObject[key].groupId.indexOf("&isSelectedBySearchExperiment=")!=-1) { theObject[key].groupId = theObject[key].groupId.split("&")[0]; }
if (theObject[key].hamTimer===null) theObject[key].hamTimer=gDefaultMainOptions.hamDelayTimer;
}
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), i = base64AudioData.length, binaryString = new Array(i);
while (i--) { binaryString[i] = String.fromCharCode(base64AudioData[i]); }
return(window.btoa(binaryString.join('')));
}
function fillInSoundOptions(soundOptions) {
for (var key in soundOptions) {
gAlarmSounds[key].payRate = soundOptions[key].payRate; gAlarmSounds[key].lessMinutes = soundOptions[key].lessMinutes;
if (soundOptions[key].base64!==null) {
gAlarmSounds[key].audio = new Audio("data:audio/wav;base64," + JSON.parse(soundOptions[key].base64));
GM_setValue(gAlarmSounds[key].nameVar,soundOptions[key].base64);
}
}
}
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 loadSoundFiles(soundNumber,keyArray,resetMe) {
resetMe = (typeof resetMe != 'undefined') ? resetMe : false;
var savedDBVersion = gRequestersData[0].requesterName, resetDBVersion = savedDBVersion.split("-")[1];
if (soundNumber < keyArray.length) {
var gotBase64 = (resetMe) ? null : GM_getValue(gAlarmSounds[keyArray[soundNumber]].nameVar,null);
loadSoundFiles.firstTime = loadSoundFiles.firstTime || false;
if (gotBase64 === null) {
if (!loadSoundFiles.firstTime) addToWaitDialog($("#JRjqModalDialog-waiting"),"For your first time this might take a few seconds.
Loading Alarms ",false,"16px");
loadSoundFiles.firstTime = true;
requestUrl(gAlarmSounds[keyArray[soundNumber]].default,0,function(theResult) {
addToWaitDialog($("#JRjqModalDialog-waiting")," .",false,"16px");
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 { fillInSoundOptions(gSoundOptions); changeOldSettings(); continueLoading(); }
}
function fillInGroupings() {
for (var key in gGroupingData) {
if (!gGroupingData[key].grouping) gGroupingData[key].grouping = [];
gGroupings[key] = {"data":gGroupingData[key],"collecting":false};
gGroupingsSort.push(key);
defaultFillIn(gGroupingData[key],gDefaultGroupingData["JR First"]);
}
}
function createKeysArray(theObject) {
if (!theObject) return null;
gRequestersKeys = [];
for (var key in theObject) { gRequestersKeys.push(key); }
}
function loadInDBVersions(passedDatabase) {
var tempData = null;
if (passedDatabase) tempData = passedDatabase;
else {
tempData = JSON.parse(GM_getValue("JR_PANDA_RequestersData",JSON.stringify(gDefaultRequestersData)));
createKeysArray(tempData);
}
var savedDBVersion = tempData[0].requesterName, resetDBVersion = savedDBVersion.split("-")[1], defaultDBVersion = savedDBVersion.split("-")[2];
gRequestersKeys = [];
for (var key in tempData) {
gRequestersKeys.push(key); convertDatabase(tempData,key); tempData["0"].requesterName = gDatabaseVersion;
defaultFillIn(tempData[key],gDefaultRequestersData[0]); defaultFillIn(tempData[key].searchData.searchOptions,JSON.parse(JSON.stringify(gDefaultSearchOptions)));
}
return tempData;
}
function setupSoundOptions(base64) {
base64 = (typeof base64 != 'undefined') ? base64 : false;
var soundOptions = {};
for (var key in gAlarmSounds) {
var theBase64 = (base64) ? GM_getValue(gAlarmSounds[key].nameVar,null) : null;
soundOptions[key] = {"payRate":gAlarmSounds[key].payRate,"lessMinutes":gAlarmSounds[key].lessMinutes,"base64":theBase64};
}
return soundOptions;
}
function clearOldMessages() {
var storageKeys = Object.keys(localStorage);
for (i = 0; i < storageKeys.length; i++) {
if ( (storageKeys[i].substring(0,11) == 'JR_message_' && storageKeys[i].substr(storageKeys[i].length - gScriptName.length) == gScriptName) ||
storageKeys[i].substring(0,14) == 'JR_queueOrder_') {
localStorage.removeItem(storageKeys[i]);
}
}
}
function loadSettings() {
clearOldMessages();
var defaultSoundOptions = setupSoundOptions();
gRequestersData = loadInDBVersions();
gMainOptions = JSON.parse(GM_getValue("JR_PANDA_MainOptions",JSON.stringify(gDefaultMainOptions)));
defaultFillIn(gMainOptions,gDefaultMainOptions);
gTabsData = JSON.parse(GM_getValue("JR_PANDA_TabsData",JSON.stringify(gDefaultTabsData)));
gTabsInfo = JSON.parse(GM_getValue("JR_PANDA_TabsInfo",JSON.stringify(gDefaultTabsInfo)));
convertTabDatabase();
for (var key in gTabsData) { defaultFillIn(gTabsData[key],gDefaultTabsData[0]); }
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));
}
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);
gDelayedSave = false;
}
function resetSettings() {
GM_deleteValue("JR_PANDA_RequestersData"); GM_deleteValue("JR_PANDA_MainOptions"); GM_deleteValue("JR_PANDA_TabsData"); GM_deleteValue("JR_PANDA_TabsInfo");
GM_deleteValue("JR_PANDA_GroupingData"); GM_deleteValue("JR_PANDA_SoundOptions");
$.each(gAlarmSounds, function( index, value ) { GM_deleteValue(value.nameVar); });
}
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"), doStatus = (typeof modeStatus != 'undefined') ? 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 setAttributes(el, attrs) { for (var key in attrs) { el.setAttribute(key, attrs[key]); } }
function elementInit(theElement,theClass,theText,theStyle) {
if (theClass) theElement.className = theClass; if (theText) theElement.textContent = theText; if (theStyle) theElement.style = theStyle; return theElement;
}
function createDiv(theHtml) { var inner = (theHtml) ? theHtml : ""; return $('
').html(inner); }
function createDiv2(theClass,theText,theStyle) { var div = document.createElement("div"); return elementInit(div,theClass,theText,theStyle); }
function createSpan(theHtml) { var inner = (theHtml) ? theHtml : ""; return $('
').html(inner); }
function createSpan2(theClass,theText,theStyle) { var span = document.createElement("span"); return elementInit(span,theClass,theText,theStyle); }
function createTextInput(theValue) { return $("").attr({ "type": "text", "value": theValue }); }
function createCheckbox(theValue) { return $("").attr({ "type": "checkbox", "value": theValue }); }
function createCheckbox2(theClass,theValue,theStyle) {
var cb = document.createElement('input'); cb.type = "checkbox";
if (theValue) cb.value = theValue; return elementInit(cb,theClass,null,theStyle);
}
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 createLink2(theText,theUrl,theTarget,theTitle) {
var aLink = document.createElement("a"); var linkText = aLink.textContent = theText;
aLink.title = theTitle; aLink.href = theUrl; aLink.target = theTarget; aLink.style.color = "#00FFFF"; return aLink;
}
function createSpanButton(toDo,theClass,theText,theBackgroundColor,theColor,theFontSize,addStyle) {
var backgroundColor = (typeof theBackgroundColor != 'undefined') ? theBackgroundColor : "initial";
var textColor = (typeof theColor != 'undefined') ? theColor : "initial", fontSize = (typeof theFontSize != 'undefined') ? theFontSize : "9px";
var theButton = createSpan2("nonselectable " + theClass,theText,"font-size:" + fontSize + "; padding:0px 2px; background-color:" + backgroundColor + "; color:" + textColor +
"; border:2px groove red; cursor:default; margin:0px 1px;" + addStyle);
setAttributes(theButton,{"data-backgroundColor":backgroundColor,"data-status":"off","data-textColor":textColor,"data-htmltext":theText});
theButton.addEventListener("dblclick", function (e) { e.stopPropagation(); });
if (toDo) theButton.addEventListener("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"); return panelContainer; }
function createPanel(goAppend) { var panel = createContainer(); return panel; }
function createTabs(goAppend,isSortable,idName) {
var tabList = $(""), tabsContainer = createContainer().attr("id",idName).css({"height":"99%"});
tabList.appendTo(tabsContainer);
tabsContainer.tabs().delegate( "span.ui-icon-close", "click", function(e) {
var currentTab = $(e.target).closest("li"), 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"))), 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);
}
});
}
if (needBr) 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;
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._before = new Date();
}
privateVars._timeoutVar = setTimeout(privateFunctions._theLoop, 5);
}
};
var output = {
addJob: function(func, theNumber, milliSeconds, doOnce, weight) {
if (typeof func === 'function' && !isNaN(milliSeconds)) {
doOnce = (typeof doOnce != 'undefined') ? doOnce : false; weight = (typeof weight != 'undefined') ? 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; c gMainOptions.captchaAt+5)) ? "" : "Captcha Count: " + gMainData.captchaCounter);
}
function createQueueLinks(returnUrl,continueUrl) {
var theLinks = createSpan2(), returnLink = (returnUrl!=="") ? createLink2("Return",returnUrl,"_blank","Return") : null;
if (returnLink) {
returnLink.classList.add("JRQueueReturn");
returnLink.addEventListener('click', function(e) {
gAlarmSounds.queueAlert.audio.pause();
showYesNoDialog("Are you sure you want to return this hit?",function() {
var theHeight=window.outerHeight-80, theWidth=window.outerWidth-10;
window.open($(e.target).attr("href"),"_blank","width=" + theWidth + ",height=" + theHeight + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
});
return false;
});
theLinks.appendChild(returnLink); theLinks.appendChild(document.createTextNode(" :: "));
}
var continueLinkURL = createLink2("Continue Work",continueUrl,"_blank","Continue Work");
continueLinkURL.classList.add("JRQueueContinue");
continueLinkURL.addEventListener('click', function(e) {
gAlarmSounds.queueAlert.audio.pause();
var theHeight=window.outerHeight-80, theWidth=window.outerWidth-10;
window.open($(e.target).attr("href"),"_blank","width=" + theWidth + ",height=" + theHeight + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
return false;
});
theLinks.appendChild(continueLinkURL);
return theLinks;
}
function displayQueueStatus(queueAlertOK) {
var lessThanAlarm = false, theTimeLeft = null, timeLeftString="";
addToQueueWatchLog(createSpan(""),true);
gMainData.hitsInQueue = gQueueData.length;
if (gQueueData.length>0) {
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( container,theNumber ) {
if (!window.jQuery) return;
var hitInfo = gMainData.hitCollection[theNumber], 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 foundHits = (hitInfo.data.action.toLowerCase().indexOf("search") != -1) ? "/" + hitStatus.foundHits : "";
var statusText = "[ Acc: " + hitStatus.accepted + foundHits + " | " + skippedStatus + missedStatus + "Srch: " + hitStatus.searched + " ]";
if (container) $(container).html(statusText);
else $("#JRCellStatus_" + theNumber).html( statusText );
displayMainStatus();
}
function processResults( theNumber, result, finalUrl, pageRWQ, jobData ) {
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 (theCycler.isHamOn()) gMainData.tooFastHam++; else gMainData.tooFastNormal++;
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"});
if (finalUrl.indexOf("www.mturk.com") != -1) {
$(addText).append(createDiv(createLink("Log in to Mturk","https://www.mturk.com/mturk/myhits","_blank","https://www.mturk.com/mturk/myhits")
.click( function() {
gJRPOP = 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"}));
} else {
$(addText).append(createDiv(createLink("Log in to NEW Mturk Page","http://worker.mturk.com/","_blank","http://worker.mturk.com/")
.click( function() {
gJRPOP = window.open("http://worker.mturk.com/","_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"});
if (gNotifications) showNotification( "ALERT: Logged Off!", "You are logged off of mturk so need to log back in as soon as possible",
"loggedoff", "3ALERT3", true);
playThisSound("hasToPause");
}
break;
case "DAILYLIMIT":
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
checkDelayedSave(); stopAll();
showWaitDialog("Daily Limit Reached","",function() {},null,
createDiv("ALERT: CONGRATS!
You have reached your mturk daily limit!! You must wait for tomorrow. Go outside and see the sun!")
.css({"font-size":"18px","text-align":"center","margin":"20px 10px","line-height":"22px"}),false,240,510);
if (gNotifications) showNotification( "ALERT: CONGRATS!", "You have reached your daily limit!! You must wait for tomorrow. Go outside and see the sun!",
"loggedoff", "3ALERT3", true);
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":
gMainData.captchaCounter++;
if (hitStatus) hitStatus.accepted++;
if (hitInfo.ham == "ontimed") hitInfo.lastAccept = new Date();
var collectedDate = new Date(), newDateString = formatAMPM("onlydate",collectedDate); hitData.day = newDateString;
if (hitData.dailyLimit && hitData.dailyLimit>0) hitData.dailyDone = (gMturkDate == hitData.day) ? hitData.dailyDone+1 : 1;
if (hitData.once) hitData.oneDone = 1;
gMainData.accepted++; gMainData.hitsInQueue++;
if (pageRWQ) queueDelay.push(jobData);
else addToQueueWatch(jobData);
gSendQueue = true;
var hitPay = parseFloat(hitData.pay), theDuration = hitInfo.minutes;
gMainData.payCounter = gMainData.payCounter + hitPay; gMainData.totalEarnings = gMainData.projectedEarnings + gMainData.payCounter;
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", 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") {
var noLimits = checkLimits(theNumber);
$("#JRCellNum_" + theNumber).stop(true,true);
if (!noLimits && !hitData.once) { $("#JRCellNum_" + theNumber).css({"background-color":"#FFA691"}); }
else {
$("#JRCellNum_" + theNumber).css({"background-color":"yellow"});
$("#JRCellNum_" + theNumber).animate({"backgroundColor": $("#JRCellNum_" + theNumber).data("backgroundColor")}, 30000);
}
}
if (gNotifications) showNotification( notificationTitle, notificationMessage, "accepted", hitData.groupId);
if ( hitInfo.ham == "paused" ) { toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff); }
addToAcceptedLog( hitData.requesterName + " - " + hitData.groupId +
" [" + formatAMPM("dayandtime",collectedDate) + "] - " + hitData.title );
updateHitCell(theNumber);
gDelayedSave = true;
break;
}
if (theNumber > 0) displayHitStatus(null,theNumber);
}
function requestUrl(theUrl, theNumber, theFunction, errorFunction, data1, data2, theResponseType, acceptText) {
theResponseType = theResponseType || ""; acceptText = acceptText || "text/html";
if (gMainOptions.debugger>1) console.log("JR going to get: " + theUrl); // debugger >1 for request details
GM_xmlhttpRequest({
method: "GET",
url: theUrl,
headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": "Mozilla/5.0", "Accept": acceptText },
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", response.error );
}
}
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,minReward) { return "https://worker.mturk.com/requesters/" + theRequesterID + "/projects?page_size=30&filters%5B" +
"qualified%5D=true&filters%5Bmasters%5D=false&sort=num_hits_desc&filters%5Bmin_reward%5D=" + minReward; }
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 acceptLinkNew(theGroupId,theHitId) { return "https://worker.mturk.com/projects/" + theGroupId + "/tasks/" + theHitId + "/accept?ref=w_wp_acpt_top"; }
function setSearchOptionsDefault() {
var searchOptions = JSON.parse(JSON.stringify(gDefaultSearchOptions)), theHistory = {};
return {"searchOptions":searchOptions,"theHistory":theHistory};
}
function checkLimits(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, 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.oneDone>0) || (hitData.dailyLimit > 0 && parseInt(hitData.dailyLimit) <= parseInt(hitData.dailyDone)) ) {
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 returnValue = true;
return returnValue;
}
function checkJobMode(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, returnValue = true;
if (hitData.action.toLowerCase().indexOf("panda")!=-1 && hitData.groupId==="") {
if (hitInfo.hitCell.data("status")=="on") hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
returnValue=false;
}
return returnValue;
}
function searchRequestersInfo( theNumber, hitNumber, requestersInfo ) {
var hitInfo = gMainData.hitCollection[hitNumber], hitData = hitInfo.data;
if (hitInfo.collecting != "off") {
hitInfo.status.searched++;
displayHitStatus(null,hitNumber);
for (var i=0, len=requestersInfo.data.length; i tbody > tr").each(function(i, row) { var returnData = grabJobData(row,i); jobDatas.push(returnData); jobData = null; });
return jobDatas;
}
function createCloneButton(thetext,bgColor,theStyle,className) {
var cloneButton = createSpanButton(function(e) {},className,thetext,bgColor,null,null,theStyle); return cloneButton;
}
function initCloneButton(hitRow,hitInfo,theData,className,hitNumber,theFunction) {
var cloneButton = hitRow.getElementsByClassName(className)[0]; cloneButton.style.display = "inline-block";
if (hitInfo) cloneButton.style.backgroundColor = hitInfo.hitCell.find("." + className).css("background-color");
if (hitInfo) cloneButton.style.color = hitInfo.hitCell.find("." + className).css("color");
cloneButton.setAttribute("data-hitNumber",hitNumber); cloneButton.setAttribute("data-theData",JSON.stringify(theData));
$(cloneButton).on("click", function(e) { theFunction(e); });
}
function addAJob(e,thisData,once,collectNow,disableButtons) {
thisData = (thisData) || JSON.parse(e.target.getAttribute("data-theData"));
var newNumber = fillNewHitData(thisData.requesterName, thisData.requesterId, thisData.groupId, thisData.pay,
thisData.title, thisData.duration, once, true, collectNow);
gMainData.hitCollection[newNumber].numberHits = thisData.hitsAvailable; theCycler.frontOfTheLine(newNumber);
if (disableButtons && e) $(e.target).closest(".hitRow").find(".JRPandaButton,.JROnceButton,.JRAddJobButton").addClass("ui-state-disabled").off("click");
}
function createHitRow(theData,buttons,dialogWidth,titleWidth,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) ? ((theData.pay == "Pay") ? theData.pay : "$" + theData.pay) : "0";
var spanWidth = dialogWidth - titleWidth, hitRow = null;
if (!gTemplateHitRow) {
gTemplateHitRow = document.createElement('div');
var commonSpanStyle = " border:1px solid black; display:inline-block; overflow:hidden; white-space: nowrap;";
gTemplateHitRow.className = "hitRow";
if (fromWhere=="jobs") gTemplateHitRow.appendChild(createCheckbox2("JRCheckbox",null,"margin:-15px 2px 0 0; padding:0; display:inline-block;"));
gTemplateHitRow.appendChild(createSpan2("column1","First","background-color:#FBF5E6; width:140px; text-align:right;" + commonSpanStyle));
gTemplateHitRow.appendChild(createSpan2("column2","Second","background-color:#FCF6CF; width:" + spanWidth + "px; text-decoration:underline; cursor:pointer;" + commonSpanStyle));
gTemplateHitRow.appendChild(createSpan2("column3","Third","background-color:#F0FFFF; width:35px;" + commonSpanStyle));
if (fromWhere=="mturk") gTemplateHitRow.appendChild(createSpan2("column3.1","4th","background-color:#F5F5DC; width:40px;" + commonSpanStyle));
gTemplateHitRow.appendChild(createSpan2("column4","5th","background-color:#7FFFD4; width:40px;" + commonSpanStyle));
gTemplateHitRow.appendChild(createCloneButton("Collect",gButtonOffBgColor," overflow:hidden; display:none; height:12px; line-height:12px;","JRCollectButton"));
gTemplateHitRow.appendChild(createCloneButton("Details",gButtonOffBgColor," overflow:hidden; display:none; height:12px; line-height:12px;","JRDetailsButton"));
gTemplateHitRow.appendChild(createCloneButton("Panda",gButtonOffBgColor," overflow:hidden; display:none; height:12px; line-height:12px;","JRPandaButton"));
gTemplateHitRow.appendChild(createCloneButton("Once",gButtonOffBgColor," overflow:hidden; display:none; height:12px; line-height:12px;","JROnceButton"));
gTemplateHitRow.appendChild(createCloneButton("Add",gButtonOffBgColor," overflow:hidden; display:none; height:12px; line-height:12px;","JRAddJobButton"));
}
if (gTemplateHitRow) {
if (fromWhere=="mturk" || theData.duration == "Time" || (fromWhere=="jobs" && parseInt(theData.jobNumber) in gMainData.hitCollection)) {
hitRow = gTemplateHitRow.cloneNode(true);
hitRow.getElementsByClassName("column1")[0].textContent = (theData.friendlyRName && theData.friendlyRName!=="") ? theData.friendlyRName : theData.requesterName;
hitRow.getElementsByClassName("column2")[0].textContent = (theData.friendlyTitle && theData.friendlyTitle!=="") ? theData.friendlyTitle : theData.title;
hitRow.getElementsByClassName("column3")[0].textContent = durationText;
if (fromWhere=="mturk") hitRow.getElementsByClassName("column3.1")[0].textContent = theData.hitsAvailable;
hitRow.getElementsByClassName("column4")[0].textContent = payText;
if (fromWhere=="jobs" && theData.jobNumber != "-1" && theData.duration != "Time") {
var hitInfo = gMainData.hitCollection[parseInt(theData.jobNumber)];
initCloneButton(hitRow,hitInfo,theData,"JRCollectButton",theData.jobNumber,function(e) {
var theClone = gMainData.hitCollection[e.target.getAttribute("data-hitNumber")].hitCell.find(".JRCollectButton")[0];
$(theClone).click(); $(e.target).css({"background-color":$(theClone).css("background-color"),"color":$(theClone).css("color")});
});
initCloneButton(hitRow,hitInfo,theData,"JRDetailsButton",theData.jobNumber,function(e) {
var hitNumber = e.target.getAttribute("data-hitNumber");
showEditHitDialog(hitNumber,$(e.target),function() { $("#JREditDialog").dialog( "close"); });
});
var theCheckbox = hitRow.getElementsByClassName("JRCheckbox")[0];
theCheckbox.setAttribute("data-hitNumber",theData.jobNumber);
} else if (fromWhere=="jobs" && theData.duration == "Time") {
hitRow.getElementsByTagName("input")[0].addEventListener("click", function(e) {
$(e.target).closest(".searchingResultsArea").find("input").prop("checked",$(e.target).prop("checked"));
});
} else if (fromWhere=="mturk" && theData.duration != "Time") {
initCloneButton(hitRow,null,theData,"JRPandaButton",theData.jobNumber,function(e) { addAJob(e,null,false,true,true); });
initCloneButton(hitRow,null,theData,"JROnceButton",theData.jobNumber,function(e) { addAJob(e,null,true,true,true); });
initCloneButton(hitRow,null,theData,"JRAddJobButton",theData.jobNumber,function(e) { addAJob(e,null,false,false,true); });
}
} else { delete gRequestersData[parseInt(theData.jobNumber)]; gDelayedSave=true; }
}
return hitRow;
}
function historyUnique(searchData,requestersInfo,historyLimit) {
var searchHistory = searchData.theHistory, historyArray = searchData.searchOptions.historyArray, returnValue = false;
if (searchHistory[requestersInfo.groupId]) { searchHistory[requestersInfo.groupId].date = new Date(); returnValue = false; }
else { searchHistory[requestersInfo.groupId] = {"info":requestersInfo,"date":new Date()}; historyArray.push(requestersInfo.groupId); returnValue = true; }
if (historyArray.length>historyLimit) {
var removeThese = historyArray.splice(0, historyArray.length-historyLimit);
for (var i=0, len=removeThese.length; i parseFloat(searchOptions.maxReward)) return false;
if (searchOptions.excludeTerm.length && searchOptions.excludeTerm[0] != "" && requestersData.title.toLowerCase().indexOf(searchOptions.excludeTerm[0].toLowerCase()) != -1)
return false;
if (searchOptions.includeTerm.length && searchOptions.includeTerm[0] != "" && requestersData.title.toLowerCase().indexOf(searchOptions.includeTerm[0].toLowerCase()) == -1)
return false;
return true;
}
function parseHitSearchPage(theResult,theNumber,searchWhere) {
var theData = null, searchArea = null, jsonReceived = (theResult.responseHeaders.indexOf("application/json") != -1) ? true : false;
var hitInfo = (theNumber>0) ? gMainData.hitCollection[theNumber] : null, hitData = (hitInfo) ? hitInfo.data : null, finalUrl = theResult.finalUrl;
var parser = new DOMParser(), xmlDoc = (!jsonReceived) ? parser.parseFromString(theResult.responseText,"text/html") : null;
if (!jsonReceived) {
var errorTitle_Array = xmlDoc.getElementsByClassName("error_title"), errorTitle = (errorTitle_Array.length) ? errorTitle_Array[0] : null;
searchArea = (searchWhere=="mturk") ? $("#JRSavedMturkArea1") : $("#JRSavedJobsArea1");
if (errorTitle && errorTitle.innerHTML.indexOf("You have exceeded the maximum allowed page request rate") != -1) {
processResults( theNumber, "TOOFAST", finalUrl );
parser = null; xmlDoc = null; errorTitle_Array = null; errorTitle = null; searchArea = null;
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 = "";
}
parser = null; xmlDoc = null; errorTitle_Array = null; errorTitle = null; searchArea = null;
return;
}
} else { theData = JSON.parse(theResult.response); }
if (theData && "error" in theData) { processResults( theNumber, "TOOFAST", finalUrl ); return; }
var requestersInfo = (jsonReceived) ? doResultsJSON(theData) : doSortResultsTable(xmlDoc), goUrl = "";
if (requestersInfo.length > 0) {
if (gMainOptions.debugger>1) console.log("JR HitsearchPage : I found some hits: " + requestersInfo.length); // debugger >1 for SearchPage details
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 = $("#JRjqModalDialog-Search").width();
$(searchArea).find(".searchingResultsArea").append(createHitRow(captions,false,dialogWidth,450,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; iitrying to get " + hitInfo.data.requesterName + "
Pausing script.")
.css({"margin-top":"30px","line-height":"20px","font-size":"18px","text-align":"center","color":"red"})
.append(createDiv(createLink("Try panda link to fill in panda.",pandaLink,"_blank",pandaLink)
.click( function(e) {
gJRPOP = 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"});
if (gNotifications) showNotification( "ALERT: Captcha ALERT!", "Just found a captcha so you better go fill it in as soon as possible!",
"captcha", "3ALERT3", true);
playThisSound("hasToPause");
}
}
parser = null; htmlDoc = null; return;
}
var hitAccepted = $(htmlDoc).find("img[src$='/media/return_hit.gif']"), notAccepted = $(htmlDoc).find("input[src$='/media/accept_hit.gif']"), hitData = hitInfo.data;
if (errorTitle && errorTitle.innerHTML.indexOf("Your request was not completed successfully") != -1) {
processResults( theNumber, "NOTCOMPLETED", finalUrl );
} else if (mturkLimit) {
processResults( theNumber, "DAILYLIMIT", finalUrl );
} else if (hitAccepted.length) {
requestersInfo = grabJobData(htmlDoc); checkUpdateData(theNumber,requestersInfo);
processResults( theNumber, "ACCEPTED", finalUrl, pageRWQ, requestersInfo );
if (gMainOptions.debugger>1) console.log("accepted: " + theNumber + " | updated: " + updated + " | groupId: " + hitData.groupId); // debugger >1 for accepting stats
} else if (projectDetailBar.length) {
requestersInfo = parseNewHitPageRequesters(projectDetailBar,finalUrl); checkUpdateData(theNumber,requestersInfo);
processResults( theNumber, "ACCEPTED", finalUrl, pageRWQ, requestersInfo );
if (gMainOptions.debugger>1) console.log("accepted: " + theNumber + " | updated: " + updated + " | groupId: " + hitData.groupId); // debugger >1 for accepting stats
} else if (notAccepted.length) {
var formData = {};
formData.hitId = htmlDoc.getElementsByName("hitId")[0].value; formData.prevHitSubmitted = htmlDoc.getElementsByName("prevHitSubmitted")[0].value;
formData.prevRequester = htmlDoc.getElementsByName("prevRequester")[0].value; formData.requesterId = htmlDoc.getElementsByName("requesterId")[0].value;
formData.prevReward = htmlDoc.getElementsByName("prevReward")[0].value; formData.groupId = htmlDoc.getElementsByName("groupId")[0].value;
formData.signature = htmlDoc.getElementsByName("signature")[0].value;
var iframeSrc = $(htmlDoc).find("iframe").attr("src"), acceptHitURL = acceptLink(formData), 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) {
if (gMainOptions.fastPantha) requestUrl(acceptHitURL,theNumber,parseMturkHitPage, errorRequest);
else { hitInfo.goToUrl.push({"url":acceptHitURL,"theNumber":theNumber}); theCycler.frontOfTheLine(theNumber); }
if ( hitInfo.ham == "paused" ) toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff);
}
} else { console.log("I have no idea what that was"); processResults( theNumber, "ERROR", finalUrl ); }
parser = null; htmlDoc = null; hitAccepted = null; errorTitle = null; notAccepted = null;
}
function makeStatus() { return {"accepted":0,"skipped":0,"errors":0,"tooFast":0,"noHits":0,"fullQueue":0,"hitsStreak":0,"foundHits":0,
"noHitsStreak":0,"searched":0,"orphan":0,"hitsResults":0,"notQual":0,"missed":0,"blocked":0,"reachedLimit":false}; }
function makeCollection(pandaUrl,previewUrl,theNumber,theData,addStatus,filterFuncData,tabIndex,pandaNewUrl) { 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,"newHitsFound":false,
"tabIndex":tabIndex,"hitId":"","durationParsed":null,"dateDone":null,"elapsedSeconds":0,"pandaNewUrl":pandaNewUrl};
}
function addHitCollection(theData,theNumber,tabIndex) {
var pandaNewUrl = pandaLinkNew(theData.groupId), pandaUrl = pandaLink(theData.groupId), 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,pandaNewUrl);
return theNumber;
}
function addQueueCheck() {
theCycler.addJob( function( elapsed, theNumber ) {
gQueueCheckinProgress=true; gMainData.queueStatus.searched++; var acceptText = null;
var searchUrl = "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";
if (gNewSite) { searchUrl = "https://worker.mturk.com/tasks"; acceptText = "application/json"; }
requestUrl(searchUrl,1,function(theResult) { displayMainStatus(); return parseQueuePage(theResult); },function() { errorRequest(); }, null, null, null, acceptText );
return true;
}, -1, gMainOptions.queueTimer);
}
function popupClosed() {
gJRPOP = null;
if ($("#JRWaitDialog").dialog('isOpen') === true) { $("div[aria-describedby='JRWaitDialog'] .ui-dialog-buttonpane button:contains('Unpause')").click(); }
}
function addExternalScriptCheck() {
gExtInterval = setInterval( function() {
var sendQueue=null, sendPE=null, needQueue=false, sStr='JR_message_', eStr='_pandacrazy', numId=0;
if ((Object.keys(gExternalData)).length) {
for (var key in gExternalData) {
if (!gExternalData[key].gotPong) {
if (gExternalData[key].timeCount>20) {
numId = gExternalData[key].numId; gExternalData[key].timeCount=0; delete gExternalData[key];
localStorage.removeItem(sStr+'D_'+numId+eStr); localStorage.removeItem(sStr+'S_'+numId+eStr);
localStorage.removeItem(sStr+'pong_'+numId+eStr); localStorage.removeItem(sStr+'send_'+numId+eStr);
}
else gExternalData[key].timeCount++;
} else { gExternalData[key].gotPong=false; gExternalData[key].timeCount=0; }
}
if (needQueue || gSendQueue) { sendQueue=gQueueData; sendPE=gMainData.projectedEarnings; gSendQueue=false; }
sendPingMessage("",{"queue":sendQueue,"queueChanged":false,"PE":sendPE},null);
}
try { if (gJRPOP !== null && gJRPOP.closed) popupClosed(); } catch (e) { popupClosed(); }
}, 800);
}
function startCollecting(theNumber,thisButton) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data; hitInfo.collecting = "on";
if (hitData.dailyLimit && hitData.dailyLimit>0) hitData.dailyDone = (gMturkDate == hitData.day) ? hitData.dailyDone : 0;
if (hitData.once) hitData.oneDone = 0;
theCycler.addJob( function( elapsed, theNumber ) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, hitStatus = hitInfo.status, thisNewDate = new Date();
var newDateString = formatAMPM("onlydate",new Date()); hitData.day = newDateString;
if (hitInfo.ham == "ontimed") {
if (hitData.hamTimer > 0 && hitInfo.lastAccept!==null) {
var accElapsedTime = thisNewDate - hitInfo.lastAccept, theSeconds = accElapsedTime / 1000, offHamMode = (hitInfo.ham == "ontimed") ? "paused" : "off";
if (theSeconds >= hitData.hamTimer) { toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff,offHamMode); hitInfo.lastAccept = null; }
}
}
var checkJob = checkJobMode(theNumber);
if ( checkLimits(theNumber) && checkJob ) {
if (hitStatus.reachedLimit) {
hitStatus.reachedLimit = false; $("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":$("#JRCellNum_" + theNumber).data("backgroundColor")});
} else $("#JRCellNum_" + theNumber).css({"background-color":$("#JRCellNum_" + theNumber).data("backgroundColor")});
var theUrl = "", 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, useSearch = (hitDataAction.substring(0,6) == "search") ? true : false;
var acceptText = (gNewSite) ? "application/json" : null;
if (hitInfo.goToUrl.length) {
useSearch = false;
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" ) ? ( (gNewSite) ? hitInfo.pandaNewUrl : hitInfo.pandaUrl) :
(useSearch && !gNewSite) ? requesterSearch(hitData.requesterId,searchOptions.minReward) :
(useSearch && gNewSite) ? requesterSearchNew(hitData.requesterId,searchOptions.minReward) : (gNewSite) ? hitInfo.pandaNewUrl : 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 (useSearch) requestUrl(theUrl,theNumber,parseHitSearchPage, errorRequest, hitStatus.searched, null, null, acceptText);
else requestUrl(theUrl,theNumber,parseMturkHitPage, errorRequest, hitStatus.searched);
if (gNewOldSite) requestUrl(hitInfo.pandaNewUrl,theNumber,parseMturkHitPage, errorRequest, hitStatus.searched); // gNewOldSite for both new and old site panda.
displayHitStatus(null,theNumber);
addToStatusLog(theNumber);
return true;
} else if (gScriptStatus == "normal" && checkJob) {
hitStatus.reachedLimit = true;
$("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":"#FFA691"});
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].status.reachedLimit = false;
gMainData.hitCollection[theNumber].goToUrl.splice(0,gMainData.hitCollection[theNumber].goToUrl.length);
$("#JRCellNum_" + theNumber).css({"background-color":$("#JRCellNum_" + theNumber).data("backgroundColor")});
theCycler.removeJob(theNumber);
gMainData.jobs--;
}
displayHitStatus(null,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", 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,tabContents,theTitle,isSortable,theID,tabData,appendClose,needBr) {
tabContents = tabContents || createDiv(); needBr = (typeof needBr != 'undefined') ? needBr : true;
var theTab = createTab(tabContainer,theTitle,isSortable,theID,tabData,appendClose,needBr).data({"tabData":tabData});
tabContents.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();
}
}
});
if (needBr) tabContents.insertBefore(theTab.find("br.cleartab")); else tabContents.appendTo(theTab);
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) || false; newHitData.requesterName = (requesterName) || ""; newHitData.requesterId = (requesterId) || ""; newHitData.groupId = (groupId) || "";
newHitData.searchData = setSearchOptionsDefault(); newHitData.dateAdded = new Date();
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 backToDefault(thisButton,inputClass,thisValue,doubleDigit) {
var idName = $(thisButton).data("idName"), editing = $("#"+idName).data("editing"), dataKey = $(thisButton).closest(".editLine").data("dataKey");
var theDefaultObject = (editing=="searchoptions") ? gDefaultSearchOptions : (editing=="job") ? gDefaultRequestersData[0] : (editing=="timers") ? gDefaultMainOptions :
(editing=="alarms") ? gAlarmSounds : (editing=="options") ? gDefaultMainOptions : null;
if (theDefaultObject && dataKey in theDefaultObject) {
var defaultValue = theDefaultObject[dataKey];
if (editing=="job" && dataKey=="requesterName") defaultValue="";
if (editing=="job" && dataKey=="requesterId") defaultValue="";
if (editing=="job" && dataKey=="action") defaultValue="panda";
if (thisValue) $(thisButton).html((doubleDigit) ? ("0" + defaultValue).slice(-2) : defaultValue);
else {
var thisArea = $(thisButton).closest(".editLine");
var inputNode = $(thisArea).find("."+inputClass+":first").val(defaultValue);
if ($(thisArea).data("seconds2ms")) $(thisArea).find(".theInputEdit2").val(convertToMilliseconds(parseFloat(defaultValue)));
}
changeToEdited(idName);
}
}
function dataEdited(idName,thisArea,theValue,extraValue) {
extraValue = extraValue || null;
var inputEdit1 = null, inputEdit2 = null, input1Label="", setValue=theValue;
if ( $(thisArea).find(".theInputEdit").length > 0 ) return;
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); });
if ($(thisArea).data("idToo")) {
var secondArea = $(thisArea).data("idToo"), secondKey = $("#"+secondArea).data("dataKey");
if (secondKey) {
var theNumber = $("#"+idName).data("theNumber"), secondValue = gMainData.hitCollection[theNumber].data[secondKey];
var secondInputEdit = createTextInput(secondValue).attr("class","theInputEdit").css({"width":"300px"});
var secondInputEditSpan = createSpan().append(secondInputEdit);
$(secondInputEdit).after($(createSpanButton(function(e) { backToDefault(e.target,"theInputEdit",false,false); },"","D",
gButtonOffBgColor,gButtonOffColor,"8px")).css({"margin-left":"5px"}).data("idName",idName));
$("#" + secondArea).find("span:not(.errorEditLine):not(.defaultEdit):not(.editButton)").replaceWith(secondInputEditSpan);
$("#" + secondArea).off("click");
}
}
$(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();
});
$(inputEdit1).after($(createSpanButton(function(e) { backToDefault(e.target,"theInputEdit",false,false); },"defaultButton","D",
gButtonOffBgColor,gButtonOffColor,"8px")).css({"margin-left":"5px"}).data("idName",idName));
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) {
var formatNumber = (limitNumber>9) ? ("0" + currentNumber).slice(-2) : currentNumber;
return createSpan().append($(createSpanButton( function(e) {
var limitNumber = $(e.target).data("limitNumber"), numberIncDec = $(e.target).parent().find(".numberIncDec"), theNumber = parseInt(numberIncDec.html());
theNumber = (theNumber>0) ? theNumber-1 : 0;
numberIncDec.html((limitNumber>9) ? ("0" + theNumber).slice(-2) : theNumber);
changeToEdited(idName);
},"","<",gButtonOffBgColor,gButtonOffColor,"9px")).data({"limitNumber":limitNumber}))
.append(createSpan(formatNumber.toString()).attr({"class":"numberIncDec nonselectable"}).data("idName",idName))
.dblclick( function(e) { backToDefault(e.target,"numberIncDec",true,(limitNumber>9)); } )
.append($(createSpanButton( function(e) {
var limitNumber = $(e.target).data("limitNumber"), numberIncDec = $(e.target).parent().find(".numberIncDec"), theNumber = parseInt(numberIncDec.html());
theNumber = (theNumber9) ? ("0" + theNumber).slice(-2) : theNumber);
changeToEdited(idName);
},"",">",gButtonOffBgColor,gButtonOffColor,"9px")).data({"limitNumber":limitNumber}));
}
function dataTrueFalse(idName,thisArea,theValue) {
changeToEdited(idName);
var newValue=false, theSpan = $(thisArea).closest("div").find("span");
if (theSpan.html()=="true") newValue=false; else newValue=true;
$(theSpan).html(newValue.toString());
}
function dataRadioButtons(idName,theName,theValues,theValue,theChangeFunction) {
var radioButtons = createSpan().data("changeFunction",theChangeFunction);
$.each(theValues, function(index, value) {
var valueID = value.toLowerCase(), 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($("