// ==UserScript==
// @name JR Mturk Panda Crazy
// @version 0.1.7
// @description My own Panda master for mturk with zing and queue smart
// @include http*://www.allbyjohn.com/mturk/pandacrazy.html
// @include http*://www.mturk.com/mturk/welcome?pandacrazy=on*
// @require http://code.jquery.com/jquery-2.1.4.min.js
// @require http://code.jquery.com/ui/1.11.4/jquery-ui.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery-layout/1.3.0-rc-30.79/jquery.layout.min.js
// @resource jQueryUICSS http://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css
// @resource jQueryLayoutCSS https://cdnjs.cloudflare.com/ajax/libs/jquery-layout/1.3.0-rc-30.79/layout-default.css
// @connect allbyjohn.com
// @connect mturk.com
// @connect tiny.cc
// @connect ibotta.com
// @connect *
// @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.1.7";
var gDatabaseVersion = "JRAPR16-1.1-1.1.1"; // JR[Date]-[requesters DB Reset].[Alarms DB reset]-[requesters DB Version].[Options DB Version].[Tabs DB Version]
var gResetDBVersion = gDatabaseVersion.split("-")[1];
var gDefaultDBVersion = gDatabaseVersion.split("-")[2];
var gLocation = window.location.href;
var gSlowDownAuto = true;
var gResetAllData = false;
var gDelayedSave = false;
var gScriptStatus = "normal";
var gNotification = true;
var gFullQueue = false;
var gMyLayout = null, gAcceptedLogTab = null, gStatusLogTab = null, mCoinSound = [];
var gMainData = {"hitCollection":{},"displayInfo":"1",
"accepted":0,"skipped":0,"errors":0,"searched":0,"noHits":0,"fullQueue":0,"orphan":0,"tooFast":0,
"hitsInQueue":0,"queueStatus":null,"notQual":0,"lastElapsed":0,"jobs":0,"payCounter":0};
var gMainMenu = [{"name":"Main","theobject":null}];
var gDefaultRequestersOptions = {};
var gDefaultLayout = {};
var gDefaultSounds = {};
var gHitBgColor="#AFEEEE", gFilteredHitBgColor="#D1E5E5", gSearchesHitBgColor="#AED2D2", gButtonOffBgColor="#FFFFF0", gButtonOnBgColor="#008000";
var gButtonDelayHamBgColor="#00A3CC", gButtonDisabledBgColor="#D3D3D3", gHitMutedColor="#8B4513";
var gTitleColor="#000080", gButtonOffColor="black", gButtonOnColor="white", gButtonDisabledColor="#808080";
var gHitMutedBorderStyle="dotted", gHitBorderStyle="solid";
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"},
"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"},
"less5":{"nameVar":"JR_PANDA_Soundless5","default":"http://tiny.cc/g7h1ay","audio":null,"desc":"Hits paying less than |: ","payRate":"0.05","lessMinutes":"99"},
"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"},
"less15":{"nameVar":"JR_PANDA_Soundless15","default":"http://tiny.cc/qai1ay","audio":null,"desc":"Hits paying less than |: ","payRate":"0.15"},
"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"},
"less99":{"nameVar":"JR_PANDA_Soundless99","default":"http://tiny.cc/gbi1ay","audio":null,"desc":"Hits paying MORE than |: ","payRate":"0.15"},
"fullQueue":{"nameVar":"JR_PANDA_FullQueue","default":"http://tiny.cc/wietby","audio":null,"desc":"You have a full queue!","payRate":""},
};
var gSoundFile = null;
var gTabIndex = 0;
var gMouseDownTimeoutId = null;
var gPressAndHold = false;
var gGroupings = {};
var 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 = {};
var gDefaultTabsInfo = {"nextTabNumber":"4","tabCount":"3"};
var gTabsData = [];
var gDefaultTabsData = [{"tabName":"Main","tabNumber":"1","positions":null},{"tabName":"Daily Hits","tabNumber":"2","positions":null},{"tabName":"Rare Hits","tabNumber":"3","positions":null}];
var gMainOptions = {};
var gDefaultMainOptions = {"cycleNumber":970,"HamCycleNumber":700,"autoSlowDown":true,"cycleAutoIncrease":5,"alarmVolume":80,"cycleIncrease":5,"cycleDecrease":5,"cycleAdding":650,"queueTimer":60000,"hamDelayTimer":20,"showHelpTooltips":true};
var gRequestersData = {};
var gDefaultRequestersData = {
"0":{"requesterName":gDatabaseVersion,"requesterId":28,"action":"","groupId":"","pay":"","qual":"","title":"","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"4":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"30B721SJLR5BYYBNQJ0CVKJESN00OC","pay":"0.01","qual":"ibotta","title":"Are these the same?","queueLimit":15,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"5":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"30B721SJLR5BYYBNQJ0CVKJEQOZ0OB","pay":"0.01","qual":"","title":"Are these the same?","queueLimit":15,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"6":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3ZXRRTK2NDCB5NW5M24C9P2OWG41OF","pay":"0.01","qual":"ibotta","title":"Does this receipt contain the following products?","queueLimit":4,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"7":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3NYGPW9OTYRQLJTE9DQJQJRQJ2IZPS","pay":"0.01","qual":"","title":"Does this receipt contain the following products?","queueLimit":4,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"8":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3R35RPFD7JUTQN8612HRYP7E6LZ1PV","pay":"0.03","qual":"ibotta","title":"Does this receipt contain the following products?","queueLimit":6,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"9":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3ZXRRTK2NDCB5NW5M24C9P2OVF61OE","pay":"0.03","qual":"","title":"Does this receipt contain the following products?","queueLimit":6,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"10":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3CRC4NO2BIQQWQ3GX0HLFPTFOD30SA","pay":"0.05","qual":"ibotta","title":"Does this receipt contain the following products?","queueLimit":12,"duration":"60 minutes","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"11":{"requesterName":"Zing","requesterId":"AGVV5AWLJY7H2","action":"Panda","groupId":"3787DLY3Y49RIF1DIJQB3Z8BUNP1T2","pay":"0.05","qual":"","title":"Does this receipt contain the following products?","queueLimit":12,"duration":"0","audioforce":"less2","dailyLimit":0,"mute":false,"position":null,"tabNumber":"2","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"13":{"requesterName":"Viral Mturk","requesterId":"A2UFLDVZ75JD9M","action":"Panda","groupId":"3ZXEP6UEGGA75UPGRQ2UPK3XA4YO8B","pay":"0.25","qual":"","title":"Rate the quality of ads on YouTube","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"14":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"3EGCY5R6XY0PS57S4R2H1KZW7LSAYC","pay":"0.01","qual":"","title":"Identify Images with Mature Content","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"15":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"3USMLONC9E5D7T4TWRD6UWVBJLN85E","pay":"0.03","qual":"","title":"Identify Images with Mature Content","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"16":{"requesterName":"MyLikes","requesterId":"A239M0XNXTKQZ7","action":"Panda","groupId":"37G59K9AEU0BNMXNCLOH5POEZUC9YI","pay":"0.03","qual":"","title":"Identify Videos with Mature Content","queueLimit":0,"duration":"15 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"17":{"requesterName":"Steven Snow","requesterId":"A3GAVAUPTHM0B8","action":"Panda","groupId":"3X19M43Z4VULD73G1I2N3GGRYF10D8","pay":"0.06","qual":"","title":"steven snow search 3X..D8","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":3,"once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"18":{"requesterName":"Steven Snow","requesterId":"A3GAVAUPTHM0B8","action":"Panda","groupId":"3TJJ8HSJVIVGSMA3ZXVL0CV5EGV28D","pay":"0.05","qual":"","title":"steven snow url 3T..8D","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"3","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"19":{"requesterName":"Venue Quality","requesterId":"A14AT838CPSKA6","action":"Panda","groupId":"3EM4DVSA8U8J6KF08Q5EM8I2NYE308","pay":"0.01","qual":"","title":"locations same","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"20":{"requesterName":"Venue Quality","requesterId":"A14AT838CPSKA6","action":"Panda","groupId":"3D8O2NKTAGFJD90I499E0D26RON13W","pay":"0.01","qual":"","title":"locations adult","queueLimit":0,"duration":"5 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"21":{"requesterName":"Venue Quality","requesterId":"A14AT838CPSKA6","action":"Panda","groupId":"ZZAWVTYW3Z9ZTAX43ZD0","pay":"0.01","qual":"","title":"locations family","queueLimit":0,"duration":"0","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"22":{"requesterName":"Annabel","requesterId":"A3HB3KPJ2RZ2K8","action":"Panda","groupId":"3CVHT3IKTXQR8KSLQHD2N8KOQZPR06","pay":"0.50","qual":"","title":"Comparing two statements with each other","queueLimit":0,"duration":"60 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"23":{"requesterName":"Rob Grady","requesterId":"AM07BBZNC6UTQ","action":"Panda","groupId":"33X7UBO5WUFB78Y5WJ3MVC35LFMU05","pay":"0.03","qual":"","title":"Transcribe Waffle House Guest Check","queueLimit":0,"duration":"5 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":false,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0},
"24":{"requesterName":"PredictWallStreet.com","requesterId":"A17T7LCJF0818V","action":"Search","groupId":"329HSLC9WDXX9F2DN54ARF87CMFHGG","pay":"0.80","qual":"","title":"Predict 100 Stocks - Up or Down?","queueLimit":0,"duration":"60 minutes","audioforce":"","dailyLimit":0,"mute":false,"position":null,"tabNumber":"1","once":true,"dailyDone":0,"day":0,"filterMode":0,"hamTimer":20,"friendlyRName":"","friendlyTitle":"","queueHitLimit":0}
};
var gExcludeIds = ["38FT9G80DL83PUCSQBVANJBIKGSLHM"];
var jqUI_CssSrc = GM_getResourceText("jQueryUICSS");
var jqLayout_CssSrc = GM_getResourceText("jQueryLayoutCSS");
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
function formatAMPM(theFormat,theDate,theTimeZone) {
var d = (theDate) ? theDate : new Date();
if (theTimeZone == "mturk") {
var mturkTZOffset = -8;
var today = new Date();
if (today.dst()) mturkTZOffset++;
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var MturkTime = utc + (3600000 * mturkTZOffset);
d = new Date(MturkTime);
}
var minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
if (theFormat=="short") return ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + '-' + d.getFullYear() + '(' + hours + ':' + minutes + ampm + ')';
else if (theFormat=="onlydate") return ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + '-' + d.getFullYear();
else return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}
function formatTimeZone(theFormat,theDate,theTimeZone) {
return formatAMPM(theFormat,theDate,theTimeZone);
}
function 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 ) {
var n = new Notification(title, {
body: message,
icon: "http://www.allbyjohn.com/mturk/Messaging-Online-icon.png",
tag: tag});
if (navigator.userAgent.search("Chrome") >= 0) n.onshow = function () { setTimeout(n.close.bind(n), 20000); }
}
// Database using setValue and getValue
function convertDatabase(theDataBase) {
var newDataBase = {};
$.each(theDataBase, function( index, value ) {
newDataBase[index] = value;
});
newDataBase[0].requesterName = gDatabaseVersion;
return newDataBase;
}
function convertTabDatabase() {
if (gTabsData[0].tabName == "Holder") { // temporary for testing computer
var newDataBase = [];
gTabInfo = {"nextTabNumber":"" + gTabsData[0].tabNumber,"tabCount":"" + gTabsData.length}
$.each(gTabsData, function( index, value ) {
if (index>0) newDataBase.push(value);
});
gTabsData = newDataBase;
};
}
function getBase64Audio(theData) {
var base64AudioData = new Uint8Array(theData);
var i = base64AudioData.length;
var binaryString = new Array(i);
while (i--) { binaryString[i] = String.fromCharCode(base64AudioData[i]); }
var data = binaryString.join('');
return(window.btoa(data));
}
function loadSoundFiles(soundNumber,keyArray) {
var savedDBVersion = gRequestersData[0].requesterName;
var resetDBVersion = savedDBVersion.split("-")[1];
if (soundNumber < keyArray.length) {
if ((gResetDBVersion.split(".")[1] > resetDBVersion.split(".")[1]) || gResetAllData) GM_deleteValue(gAlarmSounds[keyArray[soundNumber]].nameVar);
console.log("JR reset version: " + resetDBVersion + " | new reset version: " + gResetDBVersion);
var gotBase64 = GM_getValue(gAlarmSounds[keyArray[soundNumber]].nameVar,null);
this.firstTime = this.firstTime || false;
if (gotBase64 === null) {
if (!this.firstTime) $("#JRWaitDialog").append(createDiv("For your first time this might take a few seconds. Loading Alarms ").attr({"class":"alarmsLoad"}));
this.firstTime = true;
requestUrl(gAlarmSounds[keyArray[soundNumber]].default,0,function(theResult,theNumber,data1,data2) {
$("#JRWaitDialog .alarmsLoad").append(createSpan(" ."));
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);
},function() { errorRequest(); }, "", "", "arraybuffer");
} else {
gAlarmSounds[keyArray[soundNumber]].audio = new Audio("data:audio/wav;base64," + JSON.parse(gotBase64));
loadSoundFiles(soundNumber+1,keyArray);
}
} else continueLoading();
}
function fillInGroupings() {
$.each(gGroupingData, function( index, value ) {
if (!value.grouping) value.grouping = [];
gGroupings[index] = {"data":value,"collecting":false};
gGroupingsSort.push(index);
defaultFillIn(value,gDefaultGroupingData["JR First"]);
});
}
function defaultFillIn(data,defaultData) {
$.each(defaultData, function( index, value ) {
if (!(index in data)) { data[index] = value; }
});
}
function loadInDBVersions(passedDatabase) {
var tempData = null;
if (passedDatabase) tempData = passedDatabase;
else tempData = JSON.parse(GM_getValue("JR_PANDA_RequestersData",JSON.stringify(gDefaultRequestersData)));
var savedDBVersion = tempData[0].requesterName;
var resetDBVersion = savedDBVersion.split("-")[1];
var defaultDBVersion = savedDBVersion.split("-")[2];
if (gResetDBVersion.split(".")[0] > resetDBVersion.split(".")[0]) {
GM_deleteValue("JR_PANDA_RequestersData");
tempData = JSON.parse(GM_getValue("JR_PANDA_RequestersData",JSON.stringify(gDefaultRequestersData)));
}
tempData = convertDatabase(tempData);
$.each(tempData, function( index, value ) { defaultFillIn(value,gDefaultRequestersData[0]); });
return tempData;
}
function loadSettings() {
if (gResetAllData) GM_deleteValue("JR_PANDA_RequestersData");
gRequestersData = loadInDBVersions();
if (gResetAllData) GM_deleteValue("JR_PANDA_MainOptions");
gMainOptions = JSON.parse(GM_getValue("JR_PANDA_MainOptions",JSON.stringify(gDefaultMainOptions)));
defaultFillIn(gMainOptions,gDefaultMainOptions);
if (gResetAllData) GM_deleteValue("JR_PANDA_TabsData");
gTabsData = JSON.parse(GM_getValue("JR_PANDA_TabsData",JSON.stringify(gDefaultTabsData)));
gTabsInfo = JSON.parse(GM_getValue("JR_PANDA_TabsInfo",JSON.stringify(gDefaultTabsInfo)));
convertTabDatabase();
$.each(gTabsData, function( index, value ) { defaultFillIn(value,gDefaultTabsData[0]); });
if (gResetAllData) GM_deleteValue("JR_PANDA_GroupingData");
gGroupingData = JSON.parse(GM_getValue("JR_PANDA_GroupingData",JSON.stringify(gDefaultGroupingData)));
fillInGroupings();
loadSoundFiles(0,Object.keys(gAlarmSounds));
}
function fillInSoundOptions(soundOptions) {
$.each(soundOptions, function( index, value ) {
gAlarmSounds[index].payRate = value.payRate;
gAlarmSounds[index].lessMinutes = value.lessMinutes;
});
}
function setupSoundOptions() {
var soundOptions = {};
$.each(gAlarmSounds, function( index, value ) {
soundOptions[index] = {"payRate":value.payRate,"lessMinutes":value.lessMinutes};
});
return soundOptions;
}
function saveSettings(doAfter) {
var soundOptions = setupSoundOptions();
GM_setValue("JR_PANDA_RequestersData",JSON.stringify(gRequestersData));
GM_setValue("JR_PANDA_MainOptions",JSON.stringify(gMainOptions));
GM_setValue("JR_PANDA_TabsData",JSON.stringify(gTabsData));
GM_setValue("JR_PANDA_TabsInfo",JSON.stringify(gTabsInfo));
GM_setValue("JR_PANDA_GroupingData",JSON.stringify(gGroupingData));
GM_setValue("JR_PANDA_SoundOptions",JSON.stringify(soundOptions));
if (doAfter) setTimeout( function() { doAfter(); },200);
}
function checkDelayedSave() { if (gDelayedSave) saveSettings(); }
function toggleButton(thisButton,doThisOn,doThisOff,mode,modeStatus) {
var theStatus = $(thisButton).data("status");
var doStatus = (modeStatus) ? modeStatus : (theStatus != "on" && theStatus!=mode) ? "on" : "off";
if (mode && theStatus!=mode) $(thisButton).data("status",mode);
else $(thisButton).data("status",doStatus);
if (doStatus=="on" && doThisOn) doThisOn($(thisButton).data("theNumber"),thisButton,mode);
if (doStatus=="off" && doThisOff) doThisOff($(thisButton).data("theNumber"),thisButton,mode);
updateHitColors($(thisButton).data("theNumber"),thisButton);
}
function toggleButtonOff(thisButton,doThisOn,doThisOff) {
$(thisButton).data("status","off");
updateHitColors($(thisButton).data("theNumber"),thisButton);
if (doThisOff) doThisOff($(thisButton).data("theNumber"),thisButton);
}
function toggleButtonOn(thisButton,doThisOn,doThisOff) {
$(thisButton).data("status","on");
updateHitColors($(thisButton).data("theNumber"),thisButton);
if (doThisOn) doThisOn($(thisButton).data("theNumber"),thisButton);
}
function checkButtonsStatus() {
if (gScriptStatus == "normal") return true;
else return false;
}
function createDiv(theHtml) { var inner = (theHtml) ? theHtml : ""; return $('
");
var tabsContainer = createContainer()
.attr("id",idName)
.css({"height":"99%"})
.appendTo(goAppend);
tabList.appendTo(tabsContainer);
tabsContainer.tabs().delegate( "span.ui-icon-close", "click", function(e) {
var currentTab = $(e.target).closest("li");
var currentIndex = $(currentTab).index();
$("#JRMainTabs").tabs("option", "active", currentIndex);
var returnValue = confirm("Are you sure you want to delete this Tab?\nAll hits inside the tab will be moved to the Main Tab.\nNo Hits will be lost.");
if (returnValue) {
var currentAriaTab = $("#" + (currentTab.attr("aria-controls")));
var mainAriaTab = $("#" + ($("#JRTab_1").attr("aria-controls")));
var currentData = $(currentTab).data("tabData");
$(currentTab).find(".JRHitDummy").remove();
$(mainAriaTab).find(".JRHitDummy").remove();
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})
.bind("contextmenu", function(e) {
if ($(e.target).closest("li").index() > 0) {
var returnName = prompt("Enter Tab Label : ", $(e.target).html());
if (returnName) {
$(e.target).html(returnName);
$(e.target).closest("li").data("tabData").tabName = returnName;
saveSettings();
}
}
e.preventDefault();
return false;
})
.appendTo( tabContainer.find("ul") );
if (appendClose) theTabLi.append(createSpan("Remove Tab").attr({"class":"ui-icon ui-icon-close","role":"presentation"}));
theTabDiv.data({"tabData":tabData}).appendTo(tabContainer);
if (isSortable) {
theTabLi.click( function() { $(this).focus(); $(this).find(".tabContents").focus(); })
.droppable({
tolerance: 'pointer',
over: function( event, ui ) {
$("#JRMainTabs").tabs("option", "active", $(event.target).index());
$(event.target).focus(); $(event.target).find(".tabContents").focus();
}
});
theTabDiv.html(" ");
}
tabContainer.tabs("refresh");
return theTabDiv;
}
function playThisSound( 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();
}
var theCycler = (function() {
var privateVars = {
_timers: [],
_theQueue: [],
_theFrontOfTheLineQueue: [],
_theFrontOfTheLineTimer: [],
_before: new Date(),
_theCycle: 500,
_realCycle: 500,
_theCycleElapsed: 0,
_theCycleSkipping: 0,
_paused: false,
_hamNumber: 0,
_timeoutVar: null
}
var privateFunctions = {
_getInTimer: function(theNumber) {
for (var i=0, len=privateVars._timers.length; i= privateVars._timers[i].miliSeconds) {
var returnStatus = privateVars._timers[i].runFunction.apply("timer",[privateVars._timers[i].elapsed,privateVars._timers[i].theNumber] );
privateVars._timers[i].elapsed = 0;
if (returnStatus && privateVars._timers[i].cycleTimer) timerCalled = true;
}
}
return timerCalled;
},
_doQueue: function() {
var skipThis = true;
var firstTime = true;
var firstNumber = privateVars._theQueue[0].theNumber;
do {
var queueItem = privateVars._theQueue.shift();
privateVars._theQueue.push(queueItem);
skipThis = !queueItem.runFunction.apply("queue",[privateVars._theCycleElapsed,queueItem.theNumber] );
} while (privateVars._theQueue.length > 0 && skipThis && firstNumber != privateVars._theQueue[0].theNumber);
},
_theLoop: function() {
var continueCheck = true;
var elapsed = new Date().getTime() - privateVars._before.getTime();
if (elapsed >= privateVars._realCycle) {
privateVars._theCycleElapsed = elapsed;
privateVars._before = new Date();
if (privateVars._theFrontOfTheLineTimer.length > 0) continueCheck = !privateFunctions._goFrontOfTheLineTimer();
if (privateVars._theFrontOfTheLineQueue.length > 0) continueCheck = !privateFunctions._goFrontOfTheLine();
if (continueCheck && privateVars._timers.length>0) continueCheck = !privateFunctions._doTimers();
if (continueCheck && privateVars._hamNumber != 0) { continueCheck = false; privateFunctions._goHam(); }
if (continueCheck && privateVars._theQueue.length>0) {
privateFunctions._doQueue();
}
}
privateVars._timeoutVar = setTimeout(privateFunctions._theLoop, 0);
}
}
var output = {
addJob: function(func, theNumber, miliSeconds, cycleTimer) {
if (typeof func === 'function' && !isNaN(miliSeconds)) {
if (privateFunctions._checkInQueue(theNumber)!=-1) return;
for(var i=0, len=privateVars._timers.length; i 0) privateVars._timers.push(jobData);
}
if (privateVars._timeoutVar===null) privateFunctions._theLoop();
},
removeJob: function(theNumber) {
var returnValue = false;
privateFunctions._removeFromQueue(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); },
hamOn: function( theNumber ) { privateVars._hamNumber = theNumber; },
hamOff: function() { privateVars._hamNumber = 0; },
isHamOn: function() { return (privateVars._hamNumber>0) ? true : false; },
jobs: function() { return privateVars._theQueue.length; },
skippingReset: function() { privateVars._theCycleSkipping = 0; privateVars._realCycle = privateVars._theCycle; },
cycleIncrease: function(increaseNumber) {
increaseNumber = increaseNumber || gMainOptions.cycleIncrease;
privateVars._theCycleSkipping += increaseNumber;
privateVars._realCycle += increaseNumber;
},
cycleDecrease: function() {
privateVars._theCycleSkipping = (privateVars._theCycleSkipping > 0)
? privateVars._theCycleSkipping -= gMainOptions.cycleDecrease : 0;
privateVars._realCycle = privateVars._theCycle + privateVars._theCycleSkipping;
},
cycle: function() { return privateVars._theCycle; },
cycleSkipping: function() { return privateVars._theCycleSkipping; },
cycleChange: function(newSkipping) {
privateVars._theCycleSkipping = newSkipping; privateVars._realCycle = privateVars._theCycle + privateVars._theCycleSkipping;
},
cycleAdd: function(newSkipping) {
privateVars._theCycleSkipping += newSkipping; privateVars._realCycle = privateVars._theCycle + privateVars._theCycleSkipping;
},
cycleResetChange: function(newCycle) {
privateVars._theCycle = newCycle; privateVars._theCycleSkipping = 0; privateVars._realCycle = newCycle;
}
};
return output;
})();
function displayMainStatus() {
var statusText = "", theMode="";
var theJobs = (gMainData.jobs==0) ? "-- No Jobs to Search. " : "-- Running: " + gMainData.jobs + " jobs ";
$("#JRJobsArea").html(theJobs);
theMode = $("#JRCycleInfoArea").data("mode");
var theCycle = (theMode=="Elapsed") ? "[ Elapsed Time: " + gMainData.lastElapsed + "ms | " :
(theMode=="Cycle") ? "[ Cycling every: " + theCycler.cycle() + "ms | " :
(theMode=="CycleSkipping") ? "[ Cycling Slowed: " + theCycler.cycleSkipping() + "ms | " :
(theMode=="Hamcycle") ? "[ Min Ham Cycle: " + gMainOptions.HamCycleNumber + "ms | " : "";
if (isActiveMenu(gMainMenu,"Cycle")) {
theCycle = "[ Elapsed Time: " + gMainData.lastElapsed + "ms | Cycling every: " + theCycler.cycle() + "ms | Cycling Slowed: " +
theCycler.cycleSkipping() + "ms | Min Ham Cycle: " + gMainOptions.HamCycleNumber + "ms ]";
$("#JRCycleInfoArea").html(theCycle);
$("#JRResultAccSkipArea").html("");
$("#JRErrorArea").html("");
$("#JRMturkQueueArea").html("");
$("#JRSearchedArea").html("");
$("#JRPayArea").html("");
} else {
$("#JRCycleInfoArea").html(theCycle);
theMode = $("#JRResultAccSkipArea").data("mode");
var theAccSkip = (theMode=="Accepted") ? "Accepted: " + gMainData.accepted + " | " :
(theMode=="Skipped") ? "Skipped: " + gMainData.skipped + " | " : "";
$("#JRResultAccSkipArea").html(theAccSkip);
theMode = $("#JRErrorArea").data("mode");
var theErrors = (theMode=="Errors") ? "Errors: " + gMainData.errors + " | " :
(theMode=="TooFast") ? "Too Fast: " + gMainData.tooFast + " | " : "";
$("#JRErrorArea").html(theErrors);
$("#JRMturkQueueArea").html("Mturk Queue: " + gMainData.hitsInQueue + " | ");
$("#JRSearchedArea").html("Searched: " + gMainData.searched + " | ");
$("#JRPayArea").html("Pay Accepted: " + gMainData.payCounter.toFixed(2) + " ]");
}
}
function displayControlsStatus() {
}
function displayHitStatus( theNumber ) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitStatus = hitInfo.status;
var statusText = "";
statusText += "[ Acc: " + hitStatus.accepted + " | Skip: " + hitStatus.skipped + " | Srch: " + hitStatus.searched + " ] ";
$("#JRCellStatus_" + theNumber).html( statusText );
displayMainStatus();
}
function processResults( theNumber, result ) {
var hitInfo = (theNumber>0) ? gMainData.hitCollection[theNumber] : null;
var hitData = (hitInfo) ? hitInfo.data : null;
var hitStatus = (hitInfo) ? hitInfo.status : null;
switch(result) {
case "NOTQUALIFIED":
if (hitStatus) hitStatus.notQual++;
gMainData.notQual++;
break;
case "NOMORE":
case "NOACCEPT":
if (hitStatus) hitStatus.noHits++;
gMainData.noHits++;
break;
case "TOOFAST":
if (hitStatus) hitStatus.tooFast++;
gMainData.tooFast++;
if (gSlowDownAuto) theCycler.cycleIncrease(gMainOptions.cycleAutoIncrease);
break;
case "LOGGEDOFF":
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
if (!theCycler.isPaused()) alert("You are logged out of Amazon. Can't accept hits. Please log back in");
break;
case "DAILYLIMIT":
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
alert("Congratulations!! You have reached your daily limit. Wait for tomorrow.");
break;
case "NOTCOMPLETED":
case "ERROR":
if (hitStatus) hitStatus.error++;
gMainData.error++;
break;
case "QUEUEMAX":
if (hitStatus) hitStatus.fullQueue++;
playThisSound("fullQueue");
gMainData.fullQueue++;
break;
case "SKIPPED":
if (hitStatus) hitStatus.skipped++;
gMainData.skipped++;
break;
case "ACCEPTED":
if (hitStatus) hitStatus.accepted++;
if (hitData.hamTimer > 0) hitInfo.lastAccept = new Date();
var newDate = new Date().setHours(0,0,0,0);
if (hitData.dailyLimit && hitData.dailyLimit>0) hitData.dailyDone = (newDate == hitData.day) ? hitData.dailyDone + 1 : 1;
if (hitData.once) hitData.dailyDone = 1;
hitData.day = newDate;
gMainData.accepted++;
gMainData.hitsInQueue++;
var hitPay = parseFloat(hitData.pay);
gMainData.payCounter = Math.round( (gMainData.payCounter + hitPay) * 100) / 100;
var theDuration = hitInfo.minutes;
if (theDuration==0 && hitData.duration!="0") {
theDuration = (hitData.duration.indexOf("weeks")!=-1) ? 5000 : (hitData.duration.indexOf("day")!=-1) ? 1500 : (hitData.duration.indexOf("hours")!=-1) ? 200 :
(hitData.duration.indexOf("hour")!=-1) ? 60 : (hitData.duration.indexOf("minutes")!=-1) ? parseInt(hitData.duration.split("minutes")[0]) : 1;
hitInfo.minutes = theDuration;
}
var theSoundFile = "less99";
var notificationTitle = "Accepted Hit From: " + hitData.requesterName;
var notificationMessage = "Pay: " + hitData.pay + "\nDuration: " + hitData.duration + "\nTitle: " + hitData.title;
if (!hitData.mute) { hitPay = 0.10; theDuration = 5;
if ( hitPay < parseFloat(gAlarmSounds["less2"].payRate) ) {
theSoundFile = (theDuration != 0 && theDuration<=parseInt(gAlarmSounds["less2Short"].lessMinutes)) ? "less2Short" : "less2";
} else if ( hitPay <= parseFloat(gAlarmSounds["less5"].payRate) ) {
theSoundFile = (theDuration != 0 && theDuration<=parseInt(gAlarmSounds["less5Short"].lessMinutes)) ? "less5Short" : "less5";
} else if ( hitPay <= parseFloat(gAlarmSounds["less15"].payRate) ) {
theSoundFile = (theDuration != 0 && theDuration<=parseInt(gAlarmSounds["less15Short"].lessMinutes)) ? "less15Short" : "less15";
} else if ( hitPay < parseFloat(gAlarmSounds["less99"].payRate) ) { theSoundFile = "less99"; }
if (hitData.audioforce != "") theSoundFile = hitData.audioforce;
playThisSound(theSoundFile);
}
if (gScriptStatus == "normal") {
$("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":"yellow"});
$("#JRCellNum_" + theNumber).animate({backgroundColor: $("#JRCellNum_" + theNumber).data("backgroundColor")}, 40000);
}
if (gNotifications) showNotification( notificationTitle, notificationMessage, "accepted");
if ( hitInfo.ham == "paused" ) toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff);
addToAcceptedLog( hitData.requesterName + " - " + hitData.groupId + " - " + hitData.title );
updateHitCell(theNumber);
break;
}
if (theNumber > 0) displayHitStatus(theNumber);
}
function requestUrl(theUrl, theNumber, theFunction, errorFunction, data1, data2, theResponseType) {
var theResponseType = theResponseType || "";
//console.log("JR going to get: " + theUrl);
GM_xmlhttpRequest({
method: "GET",
url: theUrl,
responseType: theResponseType,
onload: function(response) { if (typeof theFunction == 'function') theFunction(response,theNumber,data1,data2); },
onerror: function(response) { if (typeof errorFunction == 'function') errorFunction(response,theNumber); }
});
}
function pandaLink(thegroupId) { return "https://www.mturk.com/mturk/previewandaccept?groupId=" + thegroupId; }
function previewLink(thegroupId) { return "https://www.mturk.com/mturk/preview?groupId=" + thegroupId; }
function requesterSearch(theRequester) { return "https://www.mturk.com/mturk/searchbar?selectedSearchType=hitgroups&qualifiedFor=on&sortType=Reward%3A1&requesterId=" + theRequester; }
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 checkLimits(theNumber) {
//console.log("JR checking " + theNumber + " for their limits.");
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var returnValue = false;
if (hitData.queueLimit == 0 && hitData.dailyLimit == 0 && !hitData.once) returnValue = true;
else if (hitData.once && hitData.dailyDone>0) {
if (hitInfo.hitCell.data("status")=="on") hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
returnValue = false;
} else if (hitData.dailyLimit > 0 && hitData.dailyLimit < gMainData.dailyDone) returnValue = false;
else if (hitData.queueLimit > 0 && hitData.queueLimit <= gMainData.hitsInQueue) returnValue = false;
else returnValue = true;
return returnValue;
}
function searchRequestersInfo( theNumber, hitNumber, requestersInfo ) {
var hitInfo = gMainData.hitCollection[hitNumber];
var hitData = hitInfo.data;
if (hitInfo.collecting != "off") {
hitInfo.status.searched++;
displayHitStatus(hitNumber);
for (var i=0, len=requestersInfo.data.length; i0) ? gMainData.hitCollection[theNumber] : null;
var hitData = (hitInfo) ? hitInfo.data : null;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(theResult.responseText,"text/html");
var errorTitle_Array = xmlDoc.getElementsByClassName("error_title");
var errorTitle = (errorTitle_Array.length) ? errorTitle_Array[0] : null;
if (errorTitle && errorTitle.innerHTML.indexOf("You have exceeded the maximum allowed page request rate") != -1) {
processResults( theNumber, "TOOFAST" );
return;
} else if (errorTitle && errorTitle.innerHTML.indexOf("Your search did not match any HITs") != -1) {
return;
} else {
var tempNode = $(xmlDoc).find("#sortresults_form");
if ($(tempNode).length) {
var requestersInfo = {"counter":0,"data":[]};
$(tempNode).next("table").find("tbody:first").children("tr").each( function() {
requestersInfo.data[requestersInfo.counter] = {};
var capsuleNode = $(this).find("a#capsule" + requestersInfo.counter + "-0");
if (capsuleNode) {
var title = $(capsuleNode).html().split(" 0) {
console.log("JR HitsearchPage : I found some hits: " + requestersInfo.data.length);
var goUrl = "";
if (theNumber<=0) {
$.each(gMainData.hitCollection, function( index, value ) {
foundTheNumber = searchRequestersInfo(index, index, requestersInfo);
if (foundTheNumber != -1) {
console.log("HitsearchPage : I found a matching hit for a panda: " + requestersInfo.data[foundTheNumber].groupId);
goUrl = (value.data.action=="SearchAndFilter") ? previewLink(requestersInfo.data[foundTheNumber].groupId) : pandaLink(requestersInfo.data[foundTheNumber].groupId);
gMainData.hitCollection[0].goToUrl.push({"url":goUrl,"theNumber":i});
}
});
} else {
for (var i=0, len=requestersInfo.data.length; i 0) {
gMainData.hitsInQueue = 0;
} else {
var numberQueueText = $(xmlDoc).find("td.title_orange_text").html();
if (numberQueueText) {
var words = numberQueueText.trim().split(' ');
if ($.isNumeric(words[words.length - 2])) gMainData.hitsInQueue = parseInt(words[words.length - 2]);
}
}
}
function errorRequest(res,theNumber) {
console.log("error: " + res.statusText);
if (res.statusText == "Forbidden") processResults( theNumber, "LOGGEDOFF" );
//setStatusText(theNumber,"...... Searching - Error .....","errors");
}
function parseZingHitPage(theResult,theNumber,formData) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(theResult.responseText,"text/html");
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var thisZingOptions = gZingOptions[hitData.pay];
thisZingOptions = (gZingOptions[hitData.pay]) ? gZingOptions[hitData.pay] : gZingOptions["0.01"];
var goAccept = false;
var theSearching = $(xmlDoc).find(".row-fluid .span6").eq(0);
var receiptItemsCount = $(theSearching).find(".receipt_items .fieldswrapper").length;
var inputCount = $(theSearching).find("input[type=text]").length;
var multipleQuantityCount = $(theSearching).find("input[type=text].multiple_quantity").length;
var codesCount = inputCount - 1 - multipleQuantityCount;
var thePicturesCount = $(xmlDoc).find(".receipt_images").eq(0).find("img").length;
var limitReceptItems = thisZingOptions.SearchGroupAllowed;
var limitTallyCount = thisZingOptions.TallyCountTotalAllowed;
var limitCodes = (thisZingOptions.AcceptCodesSearching) ? 10 : 0;
var limitImages = thisZingOptions.MaxReceiptImages;
if (receiptItemsCount <= limitReceptItems && multipleQuantityCount <= limitTallyCount && codesCount <= limitCodes && thePicturesCount <= limitImages) goAccept = true;
if ( goAccept ) {
if (checkLimits(theNumber)) {
var acceptHitURL = acceptLink(formData);
hitInfo.goToUrl.push({"url":acceptHitURL,"theNumber":theNumber});
theCycler.frontOfTheLine(theNumber);
} else if (gScriptStatus == "normal") {
$("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":"#FF9999"});
$("#JRCellNum_" + theNumber).animate({backgroundColor: $("#JRCellNum_" + theNumber).data("backgroundColor")}, 40000);
}
} else processResults( theNumber, "SKIPPED" );
}
function parseMturkHitPage(theResult,theNumber) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(theResult.responseText,"text/html");
var alertBoxHeader = xmlDoc.getElementById("alertboxHeader");
var dailyLimit = false;
if (alertBoxHeader) {
var alertHeaderHTML = alertBoxHeader.innerHTML;
if (alertHeaderHTML.indexOf("There are no more available HITs") != -1 || alertHeaderHTML.indexOf("There are no HITs in this group") != -1) {
processResults( theNumber, "NOMORE" );
return;
} else if (alertHeaderHTML.indexOf("You have accepted the maximum number of HITs allowed") != -1) {
processResults( theNumber, "QUEUEMAX" );
return;
} else if (alertHeaderHTML.indexOf("The HIT you were viewing could not be accepted") != -1) {
processResults( theNumber, "NOACCEPT" );
return;
} else if (alertHeaderHTML.indexOf("You are not qualified to accept") != -1 || alertHeaderHTML.indexOf("Your Qualifications do not meet the") != -1) {
processResults( theNumber, "NOTQUALIFIED" );
return;
}
dailyLimit = (alertHeaderHTML.indexOf("There are no HITs available for you at this time") != -1);
}
if (xmlDoc.getElementsByName("userCaptchaResponse").length > 0) {
if (!theCycler.isPaused()) {
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
alert("Captcha Received");
}
return;
}
var loggedOff1 = xmlDoc.getElementById("ap_signin_custom_message");
var loggedOff3 = xmlDoc.getElementById("signin-slot");
if (loggedOff1 || loggedOff3) {
processResults( theNumber, "LOGGEDOFF" );
return;
}
var errorTitle = $(xmlDoc).find("td.error_title").eq(0);
var hitAccepted = $(xmlDoc).find("img[src$='/media/return_hit.gif']");
var notAccepted = $(xmlDoc).find("input[src$='/media/accept_hit.gif']");
if (errorTitle.length && errorTitle.html().indexOf("You have exceeded the maximum allowed page request rate") != -1) {
processResults( theNumber, "TOOFAST" );
} else if (errorTitle.length && errorTitle.html().indexOf("Your request was not completed successfully") != -1) {
processResults( theNumber, "NOTCOMPLETED" );
} else if (dailyLimit) {
processResults( theNumber, "DAILYLIMIT" );
} else if (hitAccepted.length) {
var updated = false;
var hitGroupId = ($(xmlDoc).find("form[name='hitForm']").length) ? $(xmlDoc).find("form[name='hitForm']").eq(0).find("input[name='groupId']").eq(0).val() : "";
hitData.groupId = hitGroupId;
var capsuleNode = $(xmlDoc).find("td.capsulelink_bold:first div").eq(0);
var theTitle = (capsuleNode.length) ? $(capsuleNode).html().trim() : hitData.title;
if (hitData.title != theTitle) { hitData.title = theTitle; updated=true; }
var timeLeft = $(xmlDoc).find("a#time_left\\.tooltip");
var theDuration = (timeLeft.length) ? timeLeft.parent().next().html().trim() : hitData.duration;
if (hitData.duration != theDuration) { hitData.duration = theDuration; updated=true; }
var requesterTip = $(xmlDoc).find("#requester\\.tooltip");
var requesterNameNode = (requesterTip.length) ? $(requesterTip).eq(0).parent().next() : null;
var theRequesterName = ($(requesterNameNode)) ? ( ($(requesterNameNode).find("a").length) ? $(requesterNameNode).find("a").html().trim() : $(requesterNameNode).html().trim() ) : "";
theRequesterName = (theRequesterName) ? theRequesterName : hitData.requesterName;
if (hitData.requesterName == "" || hitData.requesterName == hitData.groupId) { hitData.requesterName = theRequesterName; updated=true; }
var numberHitsTip = $(xmlDoc).find("#number_of_hits\\.tooltip");
var theNumberHits = (numberHitsTip.length) ? numberHitsTip.parent().next().html().trim() : hitInfo.numberHits;
hitInfo.numberHits = theNumberHits;
var rewardTip = $(xmlDoc).find("#reward\\.tooltip");
var theReward = (rewardTip.length) ? rewardTip.parent().next().find("span").html().replace("$","").trim() : hitData.pay;
if (hitData.pay != theReward) { hitData.pay = theReward; updated=true; }
processResults( theNumber, "ACCEPTED" );
if (updated) gDelayedSave = true;
console.log("accepted: " + theNumber + " | updated: " + updated + " | groupId: " + hitGroupId);
} else if (notAccepted.length) {
var formData = {};
formData.hitId = $(xmlDoc).find("input[name='hitId']").eq(0).val();
formData.prevHitSubmitted = $(xmlDoc).find("input[name='prevHitSubmitted']").eq(0).val();
formData.prevRequester = $(xmlDoc).find("input[name='prevRequester']").eq(0).val();
formData.requesterId = $(xmlDoc).find("input[name='requesterId']").eq(0).val();
formData.prevReward = $(xmlDoc).find("input[name='prevReward']").eq(0).val();
formData.groupId = $(xmlDoc).find("input[name='groupId']").eq(0).val();
formData.signature = $(xmlDoc).find("input[name='signature']").eq(0).val();
var iframeSrc = $(xmlDoc).find("iframe").attr("src");
var acceptHitURL = acceptLink(formData);
if (iframeSrc) {
if (formData.requesterId=="AGVV5AWLJY7H2") {
if (hitData.filterMode>0 && hitData.filterMode <= Object.keys(gZingFuncOptions).length) {
requestUrl(iframeSrc, theNumber, gZingFuncOptions[hitData.filterMode].functionName, errorRequest, formData, "");
} else {
console.log("Filter Mode is off");
hitInfo.goToUrl.push({"url":acceptHitURL,"theNumber":theNumber});
theCycler.frontOfTheLine(theNumber);
}
}
}
} else { processResults( theNumber, "ERROR" ); }
}
function makeStatus() { return {"accepted":0,"skipped":0,"errors":0,"tooFast":0,"noHits":0,"fullQueue":0,"hitsStreak":0,"noHitsStreak":0,"searched":0,"orphan":0,"hitsResults":0,"notQual":0}; }
function buttonStatus(buttonName,theData,buttonChange) {
if (buttonName=="collect") {
} else if (buttonName=="ham") {
}
}
function addHitCollection(theData,theNumber,tabIndex) {
var pandaUrl = pandaLink(theData.groupId);
var previewUrl = previewLink(theData.groupId);
var filterFuncData = (theData.action.indexOf("Filter") != -1) ? ((theData.requesterId=="AGVV5AWLJY7H2") ? gZingFuncOptions : null) : null;
gMainData.hitCollection[theNumber] =
{"collecting":"off","pandaUrl":pandaUrl,"previewUrl":previewUrl,"goToUrl":[],"theNumber":theNumber,"data":theData,"status":makeStatus(),"specialOptions":null,"hitCell":null,"ham":"off","minutes":0,"newTitle":"","numberHits":"0","once":false,"filterFuncData":filterFuncData,"searching":"off","lastAccept":null,"tabIndex":tabIndex};
return theNumber;
}
function addQueueCheck() {
theCycler.addJob( function( elapsed, theNumber ) {
gMainData.queueStatus.searched++;
requestUrl("https://www.mturk.com/mturk/sortmyhits?searchSpec=HITSearch%23T%231%2310%23-1%23T%23!Status!0!rO0ABXQACEFzc2lnbmVk!%23!Deadline!0!%23!&selectedSearchType=hitgroups&searchWords=&sortType=Deadline%3A0&pageSize=25",1,function(theResult,theNumber,data1,data2) {
return parseQueuePage(theResult);
},function() { errorRequest(); } );
displayMainStatus();
return true;
}, -1, gMainOptions.queueTimer, true);
}
function startCollecting(theNumber,thisButton) {
var hitInfo = gMainData.hitCollection[theNumber], theGoToUrl = null;
var hitData = hitInfo.data;
if (hitData.once) hitData.dailyDone = 0;
hitInfo.collecting = "on";
//console.log("Turning on " + theNumber);
theCycler.addJob( function( elapsed, theNumber ) {
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
if (hitInfo.ham == "ontimed") {
if (hitData.hamTimer > 0 && hitInfo.lastAccept) {
var nowTime = new Date();
var elapsedTime = nowTime - hitInfo.lastAccept;
var theSeconds = elapsedTime / 1000;
var theMinutes = Math.floor(theSeconds / 60);
var offHamMode = (hitInfo.ham == "ontimed") ? "paused" : "off";
if (theSeconds >= hitData.hamTimer) {
toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff,offHamMode);
hitInfo.lastAccept = null;
}
}
}
if ( checkLimits(theNumber) ) {
hitInfo.status.searched++;
if (hitInfo.goToUrl.length) {
console.log("Found a gotoUrl so I must do Url");
if ( (hitInfo.data.action.substring(0,6) == "Search" || hitInfo.data.action == "FilterPanda") && !hitInfo.hitCell.data("firstPanda") )
theGoToUrl = hitInfo.goToUrl.shift();
else theGoToUrl = hitInfo.goToUrl[0];
var theUrl=theGoToUrl.url;
} else {
var theUrl = ( hitInfo.data.action == "Panda" ) ? hitInfo.pandaUrl : (hitInfo.data.action.substring(0,6) == "Search") ? requesterSearch(hitData.requesterId) : hitInfo.previewUrl;
}
gMainData.searched++;
gMainData.lastElapsed = elapsed;
//console.log("Doing Number: " + theNumber + " | going to: " + theUrl);
if (theUrl.indexOf("selectedSearchType=hitgroups")!=-1) requestUrl(theUrl,theNumber,parseHitSearchPage, errorRequest, hitInfo.status.searched, "");
else requestUrl(theUrl,theNumber,parseMturkHitPage, errorRequest, hitInfo.status.searched, "");
displayHitStatus(theNumber);
return true;
} else if (gScriptStatus == "normal") {
$("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":"#FF9999"});
$("#JRCellNum_" + theNumber).animate({backgroundColor: $("#JRCellNum_" + theNumber).data("backgroundColor")}, 40000);
return false;
}
}, theNumber, 0, true);
gMainData.jobs++;
addQueueCheck();
}
function stopCollecting(theNumber,thisButton) {
//console.log("turning off " + theNumber);
if (gMainData.hitCollection[theNumber].collecting == "on") {
gMainData.hitCollection[theNumber].collecting = "off";
gMainData.hitCollection[theNumber].goToUrl.splice(0,gMainData.hitCollection[theNumber].goToUrl.length);
theCycler.removeJob(theNumber);
gMainData.jobs--;
}
if (theCycler.jobs() == 0) theCycler.removeJob(-1); // Stop mturk queue checking. Doesn't matter how many hits now.
displayHitStatus(theNumber);
}
function stopAll() {
$.each(gMainData.hitCollection, function( index, value ) {
if (value.collecting == "on") {
toggleButton( $("#JRCollectB_" + index),startCollecting,stopCollecting);
if (value.collecting=="off" && value.ham != "off") toggleButtonOff($("#JRHamB_" + index),hamOn,hamOff);
}
});
}
function hamOn(theNumber,thisButton) {
var onMode = "on";
$(".JRHamButton").each( function() {
if ( $(this).data("theNumber") != theNumber ) $(this).data("disabled",true);
updateHitColors($(this).data("theNumber"));
});
if (gMainData.hitCollection[theNumber].ham == "paused") onMode = "ontimed";
gMainData.hitCollection[theNumber].ham = onMode;
theCycler.hamOn(theNumber);
theCycler.skippingReset();
theCycler.cycleResetChange(gMainOptions.HamCycleNumber);
}
function hamOff(theNumber,thisButton,theMode) {
var passedMode = theMode || "off";
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"));
});
}
if (hitInfo.ham == "ontimed") passedMode = "paused";
gMainData.hitCollection[theNumber].ham = passedMode;
$("#JRCellNum_" + theNumber).data("firstPanda",false);
theCycler.hamOff();
theCycler.skippingReset();
theCycler.cycleResetChange(gMainOptions.cycleNumber);
}
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").tooltip( "option", "disabled", true );
}
function addTab(tabContainer,theTitle,isSortable,theID,tabData,appendClose) {
var theTab = createTab(tabContainer,theTitle,isSortable,theID,tabData,appendClose)
.data({"tabData":tabData});
createDiv().insertBefore(theTab.find("br.cleartab"))
.data({"tabData":tabData})
.attr({"class":"tabContents connectedSortable"})
.css({"overflow":"auto"})
.sortable({dropOnEmpty: true,delay:400,connectWith: ".connectedSortable",tolerance: "pointer","items":".JRHitCell:not(.ui-not-sortable)",
helper:"clone",opacity: 0.9,appendTo:"body",
start: function( event, ui ) {
//$(".hasTooltip").tooltip("disable");
ui.item.addClass('noclick');
ui.item.data("oldPosition",ui.item.index());
ui.item.data("received",false);
},
receive: function( event, ui ) {
ui.item.data("received",true);
$(event.target).find(".JRHitDummy").remove();
gTabsData[ui.item.data("hitInfo").tabIndex].positions.splice(ui.item.data("oldPosition"), 1);
$(event.target).data("tabData").positions.splice(ui.item.index(), 0, ui.item.data("theNumber"));
ui.item.data("hitInfo").tabIndex = $(gTabsData).index($(event.target).data("tabData"));
ui.item.data("hitData").tabNumber = $(event.target).data("tabData").tabNumber;
$(event.target).append(createDiv(" ").attr("class","JRHitCell JRHitDummy").data("hitInfo",{"tabIndex":0}).css({"height":"160px","width":"200px"}));
saveSettings();
},
stop: function( event, ui ) {
if (ui.item.data("hitInfo") && !ui.item.data("received")) {
$(event.target).find(".JRHitDummy").remove();
var thePositions = gTabsData[ui.item.data("hitInfo").tabIndex].positions;
thePositions.splice(ui.item.index(), 0, thePositions.splice(ui.item.data("oldPosition"), 1)[0]);
$(event.target).append(createDiv(" ").attr("class","JRHitCell JRHitDummy").data("hitInfo",{"tabIndex":0}).css({"height":"160px","width":"200px"}));
saveSettings();
}
$(".hasTooltip").tooltip("enable");
}
});
return theTab;
}
function dataEdited(thisArea,theValue) {
$("#JREditDialog").data("edited",true);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Save')").button().show();
var inputEdit = createTextInput(theValue).css({"width":"300px"});
$(inputEdit).focus( function() { $(this).select(); });
$(thisArea).find("span:not(.errorEditLine)").replaceWith(inputEdit);
$(inputEdit).focus();
}
function dataTrueFalse(thisArea,theValue) {
$("#JREditDialog").data("edited",true);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Save')").button().show();
if (theValue) returnValue=false;
else returnValue=true;
$(thisArea).find("span").html(returnValue.toString());
return returnValue;
}
function dataPandaSearch(thisArea,theValue) {
$("#JREditDialog").data("edited",true);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Save')").button().show();
if (theValue) returnValue=false;
else returnValue=true;
$(thisArea).find("span").html(returnValue.toString());
return returnValue;
}
function saveAlarmsData() {
$.each(gAlarmSounds, function( index, value ) {
var importFileID = "importFileInput-" + index;
value.audio = $("#" + importFileID).data("audio");
var base64 = $("#" + importFileID).data("base64");
if (base64) GM_setValue(value.nameVar,JSON.stringify(base64));
});
saveSettings();
return true;
}
function saveOptionsData() {
var showHelpTooltipsEdit = $("#JREditDialog #showHelpTooltipsEdit input");
if (showHelpTooltipsEdit.length) gMainOptions.showHelpTooltips = $(showHelpTooltipsEdit).eq(0).val();
helpToolTips();
saveSettings();
theCycler.cycleResetChange(gMainOptions.cycleNumber);
displayMainStatus();
return true;
}
function saveTimersData() {
var cycleEdit = $("#JREditDialog #timersCycleEdit input");
if (cycleEdit.length) gMainOptions.cycleNumber = parseInt($(cycleEdit).eq(0).val());
var goHamEdit = $("#JREditDialog #timersGoHamEdit input");
if (goHamEdit.length) gMainOptions.HamCycleNumber = parseInt($(goHamEdit).eq(0).val());
var hamDelayEdit = $("#JREditDialog #timersHamDelayEdit input");
if (hamDelayEdit.length) gMainOptions.hamDelayTimer = parseInt($(hamDelayEdit).eq(0).val());
var checkQueueEdit = $("#JREditDialog #timersCheckQueueEdit input");
if (checkQueueEdit.length) {
gMainOptions.queueTimer = parseInt($(checkQueueEdit).eq(0).val());
if (theCycler.jobs() > 0) { theCycler.removeJob(-1); addQueueCheck(); };
}
var cycleIncreaseEdit = $("#JREditDialog #timersCycleIncreaseEdit input");
if (cycleIncreaseEdit.length) gMainOptions.cycleIncrease = parseInt($(cycleIncreaseEdit).eq(0).val());
var cycleDecreaseEdit = $("#JREditDialog #timersCycleDecreaseEdit input");
if (cycleDecreaseEdit.length) gMainOptions.cycleDecrease = parseInt($(cycleDecreaseEdit).eq(0).val());
var cycleAddingEdit = $("#JREditDialog #timersCycleAddingEdit input");
if (cycleAddingEdit.length) {
gMainOptions.cycleAdding = parseInt($(cycleAddingEdit).eq(0).val());
$("#JrCycleAddingButton").find("span").html("Add " + gMainOptions.cycleAdding);
}
var cycleAutoIncreaseEdit = $("#JREditDialog #timersCycleAutoIncreaseEdit input");
if (cycleAutoIncreaseEdit.length) gMainOptions.cycleAutoIncrease = parseInt($(cycleAutoIncreaseEdit).eq(0).val());
saveSettings();
theCycler.cycleResetChange(gMainOptions.cycleNumber);
displayMainStatus();
return true;
}
function saveJobData() {
var theNumber = $("#JREditDialog").data("theNumber");
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var requesterNameEdit = $("#JREditDialog #requesterNameEdit input");
if (requesterNameEdit.length) hitData.requesterName = $(requesterNameEdit).eq(0).val();
var friendlyRNameEdit = $("#JREditDialog #friendlyRNameEdit input");
if (friendlyRNameEdit.length) hitData.friendlyRName = $(friendlyRNameEdit).eq(0).val();
var requesterIdEdit = $("#JREditDialog #requesterIdEdit input");
if (requesterIdEdit.length) hitData.requesterId = $(requesterIdEdit).eq(0).val();
var actionEdit = $("#JREditDialog #actionEdit input");
if (actionEdit.length) hitData.action = $(actionEdit).eq(0).val();
var groupIdEdit = $("#JREditDialog #groupIdEdit input");
if (groupIdEdit.length) {
hitData.groupId = $(groupIdEdit).eq(0).val();
hitInfo.pandaUrl = pandaLink(hitData.groupId);
hitInfo.previewUrl = previewLink(hitData.groupId);
}
var payEdit = $("#JREditDialog #payEdit input");
if (payEdit.length) hitData.pay = $(payEdit).eq(0).val();
var qualEdit = $("#JREditDialog #qualEdit input");
if (qualEdit.length) hitData.qual = $(qualEdit).eq(0).val();
var titleEdit = $("#JREditDialog #titleEdit input");
if (titleEdit.length) hitData.title = $(titleEdit).eq(0).val();
var friendlyTitleEdit = $("#JREditDialog #friendlyTitleEdit input");
if (friendlyTitleEdit.length) hitData.friendlyTitle = $(friendlyTitleEdit).eq(0).val();
var durationEdit = $("#JREditDialog #durationEdit input");
if (durationEdit.length) hitData.duration = $(durationEdit).eq(0).val();
var queueLimitEdit = $("#JREditDialog #queueLimitEdit input");
if (queueLimitEdit.length) hitData.queueLimit = Number($(queueLimitEdit).eq(0).val());
var dailyLimitEdit = $("#JREditDialog #dailyLimitEdit input");
if (dailyLimitEdit.length) hitData.dailyLimit = Number($(dailyLimitEdit).eq(0).val());
var onceEdit = $("#JREditDialog #onceEdit input");
if (onceEdit.length) hitData.once = $(onceEdit).eq(0).val();
var hamTimerEdit = $("#JREditDialog #hamTimerEdit input");
if (hamTimerEdit.length) hitData.hamTimer = $(hamTimerEdit).eq(0).val();
var dailyDoneEdit = $("#JREditDialog #dailyDoneEdit input");
if (dailyDoneEdit.length) hitData.dailyDone = $(dailyDoneEdit).eq(0).val();
var audioforceEdit = $("#JREditDialog #audioforceEdit input");
if (audioforceEdit.length) hitData.audioforce = $(audioforceEdit).eq(0).val();
var filterModeEdit = $("#JREditDialog #filterModeEdit select");
if (filterModeEdit.length) hitData.filterMode = $(filterModeEdit).eq(0).val();
updateHitCell(theNumber);
saveSettings();
updateHitColors( theNumber );
return true;
}
function saveEditedData() {
if ( $("#JREditDialog").data("edited") ) {
if ($("#JREditDialog").data("editing") == "job") return saveJobData();
else if ($("#JREditDialog").data("editing") == "timers") return saveTimersData();
else if ($("#JREditDialog").data("editing") == "alarms") return saveAlarmsData();
else if ($("#JREditDialog").data("editing") == "options") return saveOptionsData();
else if ($("#JREditDialog").data("editing") == "groupingCreate") return saveGroupingCreateData();
else if ($("#JREditDialog").data("editing") == "groupingHitsEdit") return saveGroupingHitsData();
}
}
function saveToFile(theData) {
var blob = new Blob( [JSON.stringify(theData)], {type: "text/plain"});
var dl = document.createElement("A");
dl.href = URL.createObjectURL(blob);
dl.download = "PandaCrazy_" + formatAMPM("short") + ".json";
document.body.appendChild(dl);
dl.click();
dl.remove();
}
function exportJobs() {
//load from database to temp data variable
$("#JRWaitDialog").html("");
$("#JRWaitDialog").dialog("open");
saveToFile({"Requesters":gRequestersData,"Options":gMainOptions,"Tabsdata":gTabsData,"Grouping":gGroupingData,"Tabsinfo":gTabsInfo,"SoundOptions":setupSoundOptions()});
$("#JRWaitDialog").dialog("close");
}
function importJobs(theFile) {
//load json text and verify it's correct data for the database
$("div[aria-describedby='JRWaitDialog'] .ui-dialog-buttonpane button:contains('Cancel') span").html("Close");
$("#JRWaitDialog").data("closeme",function() { saveSettings(); });
$("#JRWaitDialog").html("");
$("#JRWaitDialog").dialog("open");
$("#JRWaitDialog").dialog("option", "title", "Please wait for importing data");
if (window.File && window.FileReader && window.FileList && window.Blob) {
var reader = new FileReader();
reader.onload = function() {
$("#JRWaitDialog").append(createDiv("Loaded file in memory."))
var textData = reader.result;
setTimeout( function() {
try {
$("#JRWaitDialog").append(createDiv("Parsing the imported Data."))
var theData = JSON.parse(textData);
$("#JRWaitDialog").append(createDiv("Stopping all Jobs"))
stopAll();
setTimeout( function() {
$("#JRWaitDialog").append(createDiv("Removing all Job Cells"))
$("#JRMainTabs").find(".ui-tabs-panel").each( function() {
$(this).find(".JRHitCell").each( function() {
$(this).remove();
});
});
setTimeout( function() {
$("#JRWaitDialog").append(createDiv("Removing all Tabs"))
$.each(gTabsData, function( index, value ) {
var panelId = $("#JRTab_" + value.tabNumber).closest( "li" ).remove().attr( "aria-controls" );
$( "#" + panelId ).remove();
$("#JRMainTabs").tabs( "refresh" );
});
setTimeout( function() {
$("#JRWaitDialog").append(createDiv("Deleting Collection Data"))
$.each(gMainData.hitCollection, function( index, value ) {
delete gMainData.hitCollection[index];
});
setTimeout( function() {
$("#JRWaitDialog").append(createDiv("Deleting Requesters Data"))
$.each(gRequestersData, function( index, value ) { delete gRequestersData[index]; });
$("#JRWaitDialog").append(createDiv("Deleting Grouping Data"))
$.each(gGroupingData, function( index, value ) { delete gGroupingData[index]; });
$.each(gGroupings, function( index, value ) { delete gGroupings[index]; });
gGroupingsSort.splice(0,gGroupingsSort.length);
setTimeout( function() {
$("#JRWaitDialog").append(createDiv("Deleting Tabs"))
$.each(gTabsData, function( index, value ) {
delete gTabsData[index];
});
gTabsInfo = {};
$("#addNewtab").remove();
setTimeout( function() {
$("#JRWaitDialog").append(createDiv("Adding imported data in the database."))
gMainOptions = theData["Options"];
defaultFillIn(gMainOptions,gDefaultMainOptions);
var soundOptions = {};
if (theData["SoundOptions"]) soundOptions = theData["SoundOptions"];
else soundOptions = setupSoundOptions();
fillInSoundOptions(soundOptions);
gRequestersData = loadInDBVersions(theData["Requesters"]);
gTabsData = theData["Tabsdata"];
if (theData["Tabsinfo"]) gTabsInfo = theData["Tabsinfo"];
else gTabsInfo = gDefaultTabsInfo;
convertTabDatabase();
$.each(gTabsData, function( index, value ) { defaultFillIn(value,gDefaultTabsData[0]); });
if (theData["Grouping"]) gGroupingData = theData["Grouping"];
else gGroupingData = gDefaultGroupingData;
$.each(gGroupingData, function( index, value ) { defaultFillIn(value,gDefaultGroupingData["JR First"]); });
fillInGroupings();
$.each(gTabsData, function( index, value ) {
addTab($("#JRMainTabs"),value.tabName,true,"JRTab_" + value.tabNumber,value,true).css({"overflow":"visible"});
});
fillTabs();
appendAddTabButton();
setTimeout( function() {
$("#JRMainTabs").tabs("option", "active", 0);
$("#JRWaitDialog").append(createDiv("Importing is finished."))
$("#JRWaitDialog").dialog("option", "title", "Importing data is now done.");
$("div[aria-describedby='JRWaitDialog'] .ui-dialog-buttonpane button:contains('Close')").show();
$("#JRMainTabs").css({"height":$(".ui-layout-center").innerHeight() - $("#JRTheControls").innerHeight() - 8});
$("#JRMainTabs").find(".tabContents").css({"height":$(".ui-layout-center").innerHeight() - $("#JRMainTabs").
find(".ui-tabs-nav").innerHeight() - $("#JRTheControls").innerHeight() - 8})
},1);
},1);
},1);
},1);
},1);
},1);
},1);
} catch(e) {
console.log("Could not parse text in file. Sorry.");
}
},50);
}
reader.readAsBinaryString(theFile);
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
function checkGroupings(groupingData) {
if (!groupingData.data) return false;
if (!groupingData.data.grouping) return false;
for (var i=0; iRight click on the jobs you want to be in Delayed Ham Mode.")
.css({"font-size":"13px","text-align":"center","margin-top":0}).appendTo(infoArea);
} else {
if (gMainData.jobs==0) {
createDiv().html("Sorry. You need to start collecting hits to create a grouping instantly.")
.css({"font-size":"14px","text-align":"center"}).appendTo(infoArea);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Create Group')").hide();
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Save')").hide();
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Cancel') span").html("Close");
} else {
createDiv().html("Do you really want to create an instant grouping for all the hits collecting now?")
.css({"font-size":"14px","text-align":"center"}).appendTo(infoArea);
$("#JREditDialog").data({"creating":"created"});
}
}
$(".ui-dialog-titlebar").hide();
$("#JREditDialog").dialog("open");
} else if ($("#JREditDialog").data("creating") == "created") {
$("#JREditDialog").data({"theGrouping":theGrouping});
$("#JREditDialog").data({"theDelayed":theDelayed});
saveGroupingCreateData("Instantly Created #" + (gGroupingData["JR First"].theNumber + 1),"Grouping instantly made so no description");
$("#JREditDialog").data("button",null);
toggleButton(theButton,null,null);
$("#JREditDialog").dialog("close");
showGroupingDialog("view",$("#JREditDialog").data("button"));
} else if (theGrouping.length>0) {
formatDialog("JREditDialog",300,620,"Name your grouping to create it:",theButton,"groupingCreate",true);
$("#JREditDialog").data({"theGrouping":theGrouping});
$("#JREditDialog").data({"theDelayed":theDelayed});
var groupingArea = createDiv().attr("class","groupingArea").css({"margin":"15px 15px"}).appendTo($("#JREditDialog"));
createDiv().html("").css({"margin":"15px 0 0 20px","font-size":"14px","color":"red","height":"30px"})
.attr("class","groupingCreateError").appendTo(groupingArea);
createDiv().html("Type in the name of this grouping:").css({"font-size":"15px"}).appendTo(groupingArea);
createDiv().append(createTextInput("").attr("class","groupName").css({"width":"200px","margin":"5px 0 0 30px","height":"25px"})).appendTo(groupingArea);
createDiv().html("Type in the description of this grouping:").css({"font-size":"15px","margin-top":"5px"}).appendTo(groupingArea);
createDiv().append(createTextInput("").attr("class","groupDesc").css({"width":"350px","margin":"5px 0 0 30px","height":"25px"})).appendTo(groupingArea);
var addGroupingButtonArea = createDiv().append(createSpanButton( function(e) {
var theName = $("#JREditDialog").find(".groupName").val().toString();
var theDescription = $("#JREditDialog").find(".groupDesc").val().toString();
if (theName!=="") {
if (saveGroupingCreateData(theName,theDescription)) {
$("#JREditDialog").data("button",null);
toggleButton(theButton,null,null);
$("#JREditDialog").dialog("close");
showGroupingDialog("view",$("#JREditDialog").data("button"));
} else {
$("#JREditDialog .groupingCreateError:first").html("Error: Found another grouping with this name. Type in a UNIQUE name.");
}
} else {
$("#JREditDialog .groupingCreateError:first").html("Error: You must type in a unique grouping name.");
}
},"Create This Named Group",gButtonOffBgColor,gButtonOffColor,"12px"))
.css({"margin":"10px 0 0 35px"}).appendTo(groupingArea);
$("#JREditDialog").dialog("open");
} else {
var realCreating = $("#JREditDialog").data("creating");
formatDialog("JREditDialog",106,600,"No groupings selected!",theButton,"groupingCreate",true);
$("#JREditDialog").data("yesFunction",function() {
$("#JREditDialog").dialog( "close"); showGroupingCreateDialog($("#JREditDialog").data("button"),[],[],$("#JREditDialog").data("creating"));
});
$("#JREditDialog").dialog("option", "position", { my: "center top", at: "center top", of: $("body") });
var infoArea = createDiv().attr("class","infoArea").css({"margin":"15px 15px"}).appendTo($("#JREditDialog"));
if (realCreating == "selection") {
createDiv().html("You forgot to select hits for the group. Try again?").css({"font-size":"14px","text-align":"center"}).appendTo(infoArea);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Yes')").show();
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('No')").show();
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Cancel')").hide();
} else {
createDiv().html("There are no hits currently being collected. Start one first.").css({"font-size":"14px","text-align":"center"}).appendTo(infoArea);
}
$(".ui-dialog-titlebar").hide();
$("#JREditDialog").dialog("open");
}
}
function refreshGroupingHitsDialog(theKey,groupingViewArea) {
var theGrouping = gGroupings[theKey].data.grouping;
var theDelayed = gGroupings[theKey].data.delayed;
for (var i=0,len=theGrouping.length; i").appendTo(groupingViewArea);
}
function refreshGroupingsDialog(groupingViewArea) {
var returnValue = {"noGrouping":false,"collecting":false};
$(groupingViewArea).find(".groupingLine").each( function() {
$(this).remove();
});
$.each(gGroupingsSort, function( index, theKey ) {
var value = gGroupings[theKey];
if (theKey != "JR First") {
var theBackground = "#F1EDC2";
if (value.collecting) { theBackground = "#66CD00"; returnValue["collecting"] = true; }
if (!checkGroupings(value)) { theBackground = "#F08080"; returnValue["noGrouping"] = true; }
if (value.data.grouping.length==0) { theBackground = "#F08080"; returnValue["noGrouping"] = true; }
var groupingLine = createDiv()
.css({"margin-top":"2px","background-color":theBackground,"padding":"2px 3px 2px 3px","height":"17px","border":"2px ridge black","cursor":"pointer"})
.attr({"class":"groupingLine"}).data({"theKey":theKey,"theIndex":index})
.click( function() {
if (value.data.grouping.length>0) {
value.collecting = !value.collecting;
for (var i=0,len=value.data.grouping.length; i" + $(e.target).data("theKey")).attr("class","questionArea")
.css({"margin":"15px 8px 0 8px","font-size":"19px","text-align":"center","line-height":"20px"}).appendTo($("#JRYesNoDialog"));
$("#JRYesNoDialog").dialog("open");
},"Del",gButtonOffBgColor,gButtonOffColor,"12px").data({"theKey":theKey,"theIndex":index})
.css({"float":"right"}).appendTo(groupingLine);
var addGroupingButtonArea = createSpanButton( function(e) {
e.stopPropagation();
$("#JREditDialog").dialog( "close");
showGroupingCreateDialog($("#JREditDialog").data("button"),[],[],"add",$(e.target).data("theKey"));
},"Add",gButtonOffBgColor,gButtonOffColor,"12px").data({"theKey":theKey,"theIndex":index})
.css({"float":"right"}).appendTo(groupingLine);
var addGroupingButtonArea = createSpanButton( function(e) {
e.stopPropagation();
var theKey = $(e.target).data("theKey");
formatDialog("JREditDialog",600,815,"Groupings Edit: " + theKey,$("#JREditDialog").data("button"),"groupingHitsEdit",true);
$("#JREditDialog").data("nameKey",theKey);
$("#JREditDialog").data("closeme",function() { showGroupingDialog("view",$("#JREditDialog").data("button")); });
$("#JREditDialog").data("NOCloseDialog",true);
createDiv().html("Click on the jobs to toggle it from keeping or removing it. [Red = remove] [Bright Green = keep] Right click to make it a delayed Ham mode which will have a dark green background.")
.css({"font-size":"13px","text-align":"center"}).appendTo($("#JREditDialog"));
var editGroupArea = createDiv().attr("class","editGroupArea").css({"margin":"10px 15px"}).appendTo($("#JREditDialog"));
createDiv().html("Group Name: ").append(createSpan(theKey.toString())).css("margin-top","4px")
.attr({"class":"editLine hasHelptip","id":"groupNameEdit"}).appendTo(editGroupArea)
.click( function() { dataEdited($(this),theKey); })
.append(createSpan().attr("class","errorEditLine").css({"color":"red","margin-left":"5px"}))
createDiv().html("Group Description: ").append(createSpan(gGroupingData[theKey].description.toString())).css("margin-top","2px")
.attr({"class":"editLine hasHelptip","id":"groupDescriptionEdit"}).appendTo(editGroupArea)
.click( function() { dataEdited($(this),gGroupingData[theKey].description); });
var groupingViewArea = createDiv().attr("class","groupingViewArea").css({"border":"1px solid grey","margin":"15px 1px","padding":"5px 1px"})
.appendTo($("#JREditDialog"));
refreshGroupingHitsDialog(theKey,groupingViewArea);
},"Edit",gButtonOffBgColor,gButtonOffColor,"12px").data({"theKey":theKey,"theIndex":index})
.css({"float":"right"}).appendTo(groupingLine);
}
});
if (returnValue["collecting"]) $("#JREditDialog .JRCollectingInstr").html("Groupings which are collecting are in green color.");
else $("#JREditDialog .JRCollectingInstr").html("");
if (returnValue["noGrouping"]) $("#JREditDialog .JREmptyInstr").html("Groupings which have NO hits grouped are in red.");
else $("#JREditDialog .JREmptyInstr").html("");
}
function showGroupingDialog(doThis,theButton) {
var dialogHeight = ($(window).height() > 600) ? 600 : $(window).height()-60;
formatDialog("JREditDialog",600,780,"Groupings List:",theButton,"grouping " + doThis,true);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Cancel') span").html("Close");
var infoArea = createDiv().attr("class","infoArea").css({"margin":"15px 15px","text-align":"center"}).appendTo($("#JREditDialog"));
createDiv().html("Click on the Grouping Name you want to start or stop.").css("font-size","14px").appendTo(infoArea);
createDiv().html("").attr({"class":"JRCollectingInstr"}).css("font-size","14px").appendTo(infoArea);
createDiv().html("").attr({"class":"JREmptyInstr"}).css("font-size","14px").appendTo(infoArea);
var groupingViewArea = createDiv().attr("class","groupingViewArea").css({"border":"1px solid grey","margin":"15px 15px","padding":"5px 3px"})
.appendTo($("#JREditDialog"));
refreshGroupingsDialog(groupingViewArea);
$("#JREditDialog").dialog("open");
}
function showExportImportDialog(porting,theButton) {
formatDialog("JREditDialog",200,300,porting + " data",theButton,"export and importing",true);
var exportImportArea = createDiv().attr("class","exportImportArea").css("margin","15px 15px").appendTo($("#JREditDialog"));
if (porting=="Export") {
createSpanButton( function(e) { checkDelayedSave();
var theButton = $("#JREditDialog").data("button");
$("#JREditDialog").data("button",null);
toggleButton(theButton,null,null);
$("#JREditDialog").dialog("close");
exportJobs();
},"Export to File",gButtonOffBgColor,gButtonOffColor,"12px").appendTo(exportImportArea);
} else {
createDiv().css({"margin":"5px 0 10px 0"}).append($("").attr({"type":"file","id":"importFileInput"})
.change( function(event) { $("#importFromFileButton").data("disabled",false).css({"background-color":gButtonOffBgColor}); } )).appendTo(exportImportArea);
createSpanButton( function(e) { checkDelayedSave();
if ( !$(e.target).data("disabled") ) importJobs( $("#importFileInput").prop("files")[0] );
var theButton = $("#JREditDialog").data("button");
$("#JREditDialog").data("button",null);
toggleButton(theButton,null,null);
$("#JREditDialog").dialog("close");
},"Import From File",gButtonDisabledBgColor,gButtonOffColor,"12px").appendTo(exportImportArea)
.attr({"id":"importFromFileButton"})
.data("disabled",true);
}
$("#JREditDialog").dialog("open");
}
function showAddJobsDialog(theButton) {
formatDialog("JREditDialog",250,600,"Add a new PANDA!",theButton,"add job",true);
var addJobArea = createDiv().attr("class","addJobArea").css("margin","15px 15px").appendTo($("#JREditDialog"));
createDiv().html("Below enter the preview or the previewandaccept url. You may enter just the groupID number too. This is needed for panda jobs. ")
.append(createTextInput("").attr("class","groupIdInput").css({"width":"400px","margin-left":"30px"})
.keypress(function(e) {
if(e.which == 13) $("#JREditDialog .JRAddPanda:first span").click();
}))
.append(createDiv()
.append(createCheckbox().attr("class","collectNow").prop('checked', true).css("margin-left","70px")).append(createSpan("Start Collecting"))
.append(createCheckbox().attr("class","onlyOnce").css("margin-left","20px")).append(createSpan("Collect only once"))).appendTo(addJobArea);
var addGroupIDButtonArea = createDiv().append(createSpanButton( function(e) {
var theValue = $("#JREditDialog .groupIdInput:first").val();
var collectNow = $("#JREditDialog .collectNow:first").prop('checked');
var onlyOnce = $("#JREditDialog .onlyOnce:first").prop('checked');
$("#JREditDialog .groupIDError").html("");
var parsedGroupID = "";
if (theValue=="") { $("#JREditDialog .groupIDError").html("Please Enter a url or GroupID first."); }
else if (theValue.indexOf("groupId=")!=-1) {
parsedGroupID = theValue.split("groupId=")[1];
if (parsedGroupID.indexOf("&")!=-1) parsedGroupID = parsedGroupID.split("&")[0];
} else if (theValue.indexOf("mturk.com")==-1) {
parsedGroupID = theValue;
} else { $("#JREditDialog .groupIDError").html("Please Enter a url or GroupID first."); }
if (parsedGroupID!="") {
console.log("found GroupID: " + parsedGroupID);
var active = $( "#JRMainTabs" ).tabs( "option", "active" );
var newHitData = jQuery.extend(true, {}, gRequestersData[0]);
newHitData.requesterName = ""; newHitData.requesterId = ""; newHitData.action = "Panda"; newHitData.groupId = parsedGroupID;
newHitData.pay = "0.00"; newHitData.qual = ""; newHitData.title = parsedGroupID; newHitData.queueLimit = 0; newHitData.duration = "";
newHitData.audioforce = ""; newHitData.hitlimit = ""; newHitData.mute = false; newHitData.position = null;
newHitData.tabNumber = gTabsData[active].tabNumber; newHitData.once = onlyOnce; newHitData.hamTimer = gMainOptions.hamDelayTimer;
var newCell = addHitData(newHitData,active);
updateHitCell(newCell.data("theNumber"));
if (collectNow) {
newCell.data("status","on");
toggleButton( newCell.find(".JRCollectButton"),startCollecting,stopCollecting );
}
var theButton = $("#JREditDialog").data("button");
toggleButton(theButton,null,null);
$("#JREditDialog").dialog("close");
}
},"Add Panda for Group ID hit",gButtonOffBgColor,gButtonOffColor,"12px")).attr("class","JRAddPanda")
.css({"margin":"6px 0 0 35px"}).appendTo(addJobArea);
createSpan("").attr("class","groupIDError").css({"color":"red","margin-left":"10px"}).appendTo(addGroupIDButtonArea);
$("#JREditDialog .groupIDError")
$("#JREditDialog").dialog("open");
}
function alarmReaderEditor(fileInput) {
$("#JREditDialog").data("edited",true);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Save')").show();
if (fileInput.prop("files")[0].size > 6000000) return -1;
var reader = new FileReader();
reader.onload = function() {
var readerContents = reader.result;
var base64Audio = btoa(readerContents);
var newAudio = new Audio("data:audio/wav;base64," + base64Audio);
playNewSound( newAudio );
fileInput.data("base64",base64Audio);
fileInput.data("audio",newAudio);
}
reader.readAsBinaryString(fileInput.prop("files")[0]);
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
return -2;
};
return 1;
}
function showAlarmsDialog( theNumber, theButton ) {
var dialogHeight = ($(window).height() > 700) ? 700 : $(window).height()-60;
formatDialog("JREditDialog",dialogHeight,740,"Edit your alarms according to what you like:",theButton,"alarms",true);
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Cancel')").show();
$("div[aria-describedby='JREditDialog'] .ui-dialog-buttonpane button:contains('Cancel') span").html("Close");
var alarmsArea = createDiv().attr("class","alarmsArea").css({"margin":"15px 15px"}).appendTo($("#JREditDialog"));
createDiv().html("Alarms must be less than 6MB. I recommend the alarms to be less than 10 seconds. There is no limit to the length because the script doesn't check that.")
.css({"font-size":"15px","text-align":"center","margin":"15px 15px"}).appendTo(alarmsArea);
var statusArea = createDiv("Status: ").attr("id","alarmStatusArea").css({"margin":"20px 15px"}).appendTo(alarmsArea);
$.each(gAlarmSounds, function( index, value ) {
var importFileID = "importFileInput-" + index;
var soundDescription = value.desc.split("|");
var addAppend = createSpan(soundDescription[0]).css({"font-weight":"bolder","textDecoration":"underline"});
if (soundDescription.length>1) addAppend = addAppend.append(createSpanButton(function(e) {
showPromptDialog("Enter the pay rate this alarm will sound when the pay rate is less than this:",
$(e.target).html().replace("$",""),$("#JREditDialog").data("theButton"),function(theValue) {
gAlarmSounds[$(e.target).data("theIndex")].payRate = theValue;
$(e.target).html("$" + theValue);
$("#JRPromptDialog").dialog( "close");
});
},"$" + value.payRate,"ivory","black","12px").data("theIndex",index).css({"font-weight":"normal"}))
.append(createSpan(soundDescription[1]).css({"font-weight":"bolder","textDecoration":"underline"}));
if (soundDescription.length>2) addAppend = addAppend.append(createSpanButton(function(e) {
showPromptDialog("Enter the minutes that this alarm will sound if the duration is less than this:",
$(e.target).html().replace("$",""),$("#JREditDialog").data("theButton"),function(theValue) {
gAlarmSounds[$(e.target).data("theIndex")].lessMinutes = theValue;
$(e.target).html(theValue);
$("#JRPromptDialog").dialog( "close");
});
},value.lessMinutes,"ivory","black","12px").data("theIndex",index).css({"font-weight":"normal"}))
.append(createSpan(soundDescription[2]).css({"font-weight":"bolder","textDecoration":"underline"}));
createDiv().attr("class","alarmInputEdits")
.append(createDiv().append(createSpanButton(function(e) { playNewSound($("#" + importFileID).data("audio")); }
,"- Play -","ivory","black","13px").css({"margin-right":"20px"}))
.append(addAppend)
.css({"margin-top":"10px"}))
.append(createDiv().html("Change to: ").append($("").attr({"type":"file","id":importFileID,"accept":"audio/*"}).data("audio",value.audio).data("base64",null)
.change( function() {
var returnValue = alarmReaderEditor($(this));
if ( returnValue > 0 ) $("#alarmStatusArea").html("Status: Audio File Loaded.").css("color","green");
else if ( returnValue == -1 ) $("#alarmStatusArea").html("Status: Audio File was way too big. File must be less than 6MB").css("color","red");
else $("#alarmStatusArea").html("Status: Audio File was not loaded. Are you sure it was an audio file?").css("color","green");
})).css({"margin":"8px 0 0 80px"})).appendTo(alarmsArea);
});
$("#JREditDialog").dialog("open");
}
function showEditOptionsDialog( theNumber, theButton ) {
var dialogHeight = ($(window).height() > 640) ? 640 : $(window).height()-60;
formatDialog("JREditDialog",dialogHeight,650,"Change options:",theButton,"options",true);
var optionsArea = createDiv().attr("class","optionsArea").css({"margin":"15px 15px"}).appendTo($("#JREditDialog"));
createDiv().html("Click on the options you would like to change below:")
.css({"font-size":"15px","text-align":"center"}).appendTo(optionsArea);
createDiv().html("Show Help Tooltips: ").css("margin-top","30px").append(createSpan( gMainOptions.showHelpTooltips.toString() ).css("font-weight","bolder"))
.attr({"class":"editLine hasHelptip","id":"showHelpTooltipsEdit","title":"Show help tootips on all buttons, tabs or editable options? Sometimes these helpful tips can get in the way especially if you already know how everything works."})
.appendTo(optionsArea)
.click( function() { gMainOptions.showHelpTooltips=dataTrueFalse($(this),gMainOptions.showHelpTooltips); });
$(".editLine").tooltip({ show: {delay:1000} });
helpToolTips();
$("#JREditDialog").dialog("open");
}
function showEditTimersDialog( theNumber, theButton ) {
var dialogHeight = ($(window).height() > 640) ? 640 : $(window).height()-60;
formatDialog("JREditDialog",dialogHeight,650,"Edit this hit:",theButton,"timers",true);
var timersArea = createDiv().attr("class","timersArea").css({"margin":"15px 15px"}).appendTo($("#JREditDialog"));
createDiv().html("All the timers on this page is measured in Milliseconds. 1000 Milliseconds is equal to 1 second. Click on numbers to edit.")
.css({"font-size":"15px","text-align":"center"}).appendTo(timersArea);
createDiv().html("Cycle Timer: ").append(createSpan(gMainOptions.cycleNumber.toString())).css("margin-top","30px")
.attr({"class":"editLine hasHelptip","id":"timersCycleEdit","title":"This is the number of milliseconds for the script to wait until it checks on the next job. By default 970 should be fast enough to grab hits fast."}).appendTo(timersArea)
.click( function() { dataEdited($(this),gMainOptions.cycleNumber); });
createDiv().html("GoHam Cycle Timer: ").append(createSpan(gMainOptions.HamCycleNumber.toString())).css("margin-top","10px")
.attr({"class":"editLine hasHelptip","id":"timersGoHamEdit","title":"This is the number of milliseconds for the script to wait until it checks on the next job when in HAM mode. By default I have set it at 700 but 500 can be good too."}).appendTo(timersArea)
.click( function() { dataEdited($(this),gMainOptions.HamCycleNumber); });
createDiv().html("Default GoHam Delay Timer: ").append(createSpan(gMainOptions.hamDelayTimer.toString())).css("margin-top","10px")
.attr({"class":"editLine hasHelptip","id":"timersHamDelayEdit","title":"When you change a job mode from normal to Delayed Ham Mode by click and holding the Ham button then this is the time the script will change back to Normal mode when it receives no more hits in Ham Mode. This time is used for any NEW jobs. The current jobs will have their own timer set when it was created."}).appendTo(timersArea)
.click( function() { dataEdited($(this),gMainOptions.hamDelayTimer); });
createDiv().html("Check Queue Timer Every: ").append(createSpan(gMainOptions.queueTimer.toString())).css("margin-top","10px")
.attr({"class":"editLine hasHelptip","id":"timersCheckQueueEdit","title":"This is the time you want the script to check your mturk queue. A minute seems fine because it only uses it when you have a limit on a job. If this timer is too low then it can make collecting pandas slower."}).appendTo(timersArea)
.click( function() { dataEdited($(this),gMainOptions.queueTimer); });
var AdvancedArea = createDiv().attr("class","advancedArea").css({"border":"1px solid grey","margin":"20px 0 0 0","padding":"5px 3px"}).appendTo(timersArea);
createDiv().html("Advanced Options:").css({"font-size":"15px","text-align":"center"}).appendTo(AdvancedArea);
createDiv().html("Cycle Increase Button: ").append(createSpan(gMainOptions.cycleIncrease.toString())).css("margin-top","15px")
.attr({"class":"editLine hasHelptip","id":"timersCycleIncreaseEdit","title":"The number of milliseconds to add to the cycle when pressing the increase button in the cycler menu."}).appendTo(AdvancedArea)
.click( function() { dataEdited($(this),gMainOptions.cycleIncrease); });
createDiv().html("Cycle Decrease Button: ").append(createSpan(gMainOptions.cycleDecrease.toString())).css("margin-top","10px")
.attr({"class":"editLine hasHelptip","id":"timersCycleDecreaseEdit","title":"The number of milliseconds to subtract from the cycle when pressing the decrease button in the cycler menu."}).appendTo(AdvancedArea)
.click( function() { dataEdited($(this),gMainOptions.cycleDecrease); });
createDiv().html("Cycle Add Time Button: ").append(createSpan(gMainOptions.cycleAdding.toString())).css("margin-top","10px")
.attr({"class":"editLine hasHelptip","id":"timersCycleAddingEdit","title":"The number of milliseconds to add to the cycle when pressing the add to button in the cycler menu. This is for a fast slow down instead of pressing the increase button a lot of times."}).appendTo(AdvancedArea)
.click( function() { dataEdited($(this),gMainOptions.cycleAdding); });
createDiv().html("Cycle Auto Slowdown Increase: ").append(createSpan(gMainOptions.cycleAutoIncrease.toString())).css("margin-top","10px")
.attr({"class":"editLine hasHelptip","id":"timersCycleAutoIncreaseEdit","title":"The number of milliseconds to add to the cycle when it has received an exceed error from mturk. Don't want it to slow down too quick so a small number here should be fine."}).appendTo(AdvancedArea)
.click( function() { dataEdited($(this),gMainOptions.cycleAutoIncrease); });
$(".editLine").tooltip({ show: {delay:1000} });
helpToolTips();
$("#JREditDialog").dialog("open");
}
function showEditHitDialog( theNumber, theButton ) {
var dialogHeight = ($(window).height() > 640) ? 640 : $(window).height()-60;
formatDialog("JREditDialog",dialogHeight,600,"Edit this hit:",theButton,"job",true);
$("#JREditDialog").data("theNumber",theNumber);
var hitInfo = gMainData.hitCollection[theNumber];
var hitData = hitInfo.data;
var requesterArea = createDiv().attr("class","requesterArea").css("margin","15px 8px").appendTo($("#JREditDialog"));
createDiv().html("Details of hit. All can be edited except for details in red. Click on details to edit.")
.css({"font-size":"15px","text-align":"center"}).appendTo(requesterArea);
createDiv().html("Queue Limit: ").append(createSpan( hitData.queueLimit.toString() )).css({"margin-top":"10px"})
.attr({"class":"editLine hasHelptip","id":"queueLimitEdit","title":"Enter the limit of the number of any hits in your queue. It will stop collecting hits until your queue is less than this number. Doesn't matter what hits are in the queue. It only looks at the total number of the queue."})
.appendTo(requesterArea)
.click( function() { dataEdited($(this),hitData.queueLimit.toString()); });
createDiv().html("Daily Limit: ").append(createSpan( hitData.dailyLimit.toString() ))
.attr({"class":"editLine hasHelptip","id":"dailyLimitEdit","title":"Enter the number to limit this hit for collection per day. Once it collects this amount of hits from this panda it will stop until the next day. (Not Implemented yet)"})
.appendTo(requesterArea)
.click( function() { dataEdited($(this),hitData.dailyLimit.toString()); });
createDiv().html("Daily Done: ").append(createSpan(hitData.dailyDone.toString()))
.attr({"class":"editLine hasHelptip","id":"dailyDoneEdit"}).appendTo(requesterArea)
.click( function() { dataEdited($(this),hitData.dailyDone.toString()); });
createDiv().html("Ham Timer (seconds): ").append(createSpan( hitData.hamTimer.toString() ))
.attr({"class":"editLine hasHelptip","id":"hamTimerEdit","title":"Enter the number of seconds this hit should be on Ham after a delayed ham reaction. This only works when you put the ham button in the delayed ham status. When a panda is found it will instantly start hamming this hit at the global ham timer. When it stops seeing any more hits it will wait this amount of seconds to turn off Ham and go back into delayed Ham status."})
.appendTo(requesterArea)
.click( function() { dataEdited($(this),hitData.hamTimer.toString()); });
createDiv().html("Once: ").append(createSpan( hitData.once.toString() ))
.attr({"class":"editLine hasHelptip","id":"onceEdit","title":"If this is true then it will only collect one hit and then it will stop. You can start it again and it will collect one again. This is very useful for surveys."})
.appendTo(requesterArea)
.click( function() { hitData.once=dataTrueFalse($(this),hitData.once); });
createDiv().html("Friendly Requester Name: ").append(createSpan(hitData.friendlyRName))
.attr({"class":"editLine hasHelptip","id":"friendlyRNameEdit","title":"Enter a friendly name for this requester. This name will show on the hit cell instead of the original name. Enter a blank name to show the original name."})
.appendTo(requesterArea)
.click( function() { dataEdited($(this),hitData.friendlyRName); });
createDiv().html("Friendly Title: ").append(createSpan(hitData.friendlyTitle))
.attr({"class":"editLine hasHelptip","id":"friendlyTitleEdit","title":"Enter a friendly title for this hit. This title will show on the hit cell instead of the original title. Useful for long titles so you can shorten it or make it more rememorable. Enter a blank title to show the original title."})
.appendTo(requesterArea)
.click( function() { dataEdited($(this),hitData.friendlyTitle); });
var advancedArea = createDiv().attr("class","advancedArea").css({"border":"1px solid grey","margin":"20px 0 0 0","padding":"5px 3px"}).appendTo(requesterArea);
createDiv().html("Advanced Options most are changed by the script automatically:").css({"font-size":"15px","text-align":"center"}).appendTo(advancedArea);
createDiv().html("The Number: ").append(createSpan(theNumber)).appendTo(advancedArea).css({"margin-top":"5px","color":"red"});
createDiv().html("Action: ").append(createSpan(hitData.action))
.attr({"class":"editLine hasHelptip","id":"actionEdit","title":"Advanced use only. Should be Panda for normal use."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.action); });
createDiv().html("Requester Name: ").append(createSpan(hitData.requesterName))
.attr({"class":"editLine hasHelptip","id":"requesterNameEdit","title":"This is the original title of the hit. Shouldn't edit this because the script will replace it when it finds the hit. Change the friendly name instead."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.requesterName); });
createDiv().html("Requester ID: ").append(createSpan(hitData.requesterId))
.attr({"class":"editLine hasHelptip","id":"requesterIdEdit","title":"This is the ID of the requester. Script only uses it for search actions so don't worry about it. But if you know the requester ID you can fill it in to complete it or to have it do a search action instead."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.requesterId); });
createDiv().html("Group ID: ").append(createSpan(hitData.groupId))
.attr({"class":"editLine hasHelptip","id":"groupIdEdit","title":"No reason to change this because you can just add a new job a lot faster."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.groupId); });
createDiv().html("Pay: ").append(createSpan(hitData.pay))
.attr({"class":"editLine hasHelptip","id":"payEdit","title":"Shows the pay rate for this hit. No need to change it because the script will fill it in automatically."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.pay); });
createDiv().html("Qualifications: ").append(createSpan(hitData.qual)).css("color","red") // Can not be edited.
.attr({"class":"editLine hasHelptip","id":"qualEdit"}).appendTo(advancedArea);
createDiv().html("Title: ").append(createSpan(hitData.title))
.attr({"class":"editLine hasHelptip","id":"titleEdit","title":"Shows the title of the hit. No need to change it because the script will fill it in automatically. Change the friendly title instead."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.title); });
createDiv().html("Duration: ").append(createSpan(hitData.duration))
.attr({"class":"editLine hasHelptip","id":"durationEdit","title":"Displays the duration for this hit. The script will fill it in automatically when it finds it's first panda."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.duration); });
createDiv().html("Force Audio: ").append(createSpan(hitData.audioforce))
.attr({"class":"editLine hasHelptip","id":"audioforceEdit","title":"Not implemented yet. Will be used to change the alarm for this hit no matter the pay rate or duration."}).appendTo(advancedArea)
.click( function() { dataEdited($(this),hitData.audioforce); });
if (hitData.action.indexOf("Filter") != -1) {
var filterModeArea = createDiv().html("Filter Mode: ")
.attr({"class":"editLine hasHelptip","id":"filterModeEdit"}).appendTo(advancedArea)
.change( function() { dataEdited($(this),hitData.filterMode.toString()); });
var filterSelection = $("