"), tabsContainer = createContainer().attr("id",idName).css({"height":"99%"});
tabList.appendTo(tabsContainer);
tabsContainer.tabs().delegate( "span.ui-icon-close", "click", function(e) {
var currentTab = $(e.target).closest("li"), currentIndex = $(currentTab).index();
$("#JRMainTabs").tabs("option", "active", currentIndex);
var returnValue = confirm("Are you sure you want to delete this Tab?\nAll hits inside the tab will be moved to the Main Tab.\nNo Hits will be lost.");
if (returnValue) {
var currentAriaTab = $("#" + (currentTab.attr("aria-controls"))), mainAriaTab = $("#" + ($("#JRTab_1").attr("aria-controls")));
var currentData = $(currentTab).data("tabData");
if (currentData.positions.length>0) {
for (var i=0, len=currentData.positions.length; i").html("" + theTitle + "")
.attr({"id":theID,"class":theClasses}).css({"font-size":"10px"}).data({"tabData":tabData}).appendTo( tabContainer.find("ul") );
if (appendClose) {
theTabLi.append(createSpan("Remove Tab").attr({"class":"ui-icon ui-icon-close","role":"presentation"}));
theTabLi.bind("contextmenu", function(e) {
if ($(e.target).closest("li").index() > 0) {
var returnName = prompt("Enter Tab Label : ", $(e.target).html());
if (returnName && returnName!=="") { $(e.target).html(returnName); $(e.target).closest("li").data("tabData").tabName = returnName; saveSettings(); }
}
e.preventDefault();
return false;
});
}
theTabDiv.data({"tabData":tabData}).appendTo(tabContainer);
if (isSortable) {
theTabLi.click( function() { $(this).focus(); $("#" + $(this).attr("aria-controls")).find(".tabContents").focus(); })
.droppable({ tolerance: 'pointer', drop: moveToTab,
over: function( event, ui ) {
var inTabId = $(event.target).attr("aria-controls"); $("#JRMainTabs").tabs("option", "active", $(event.target).index());
$(event.target).focus(); $("#" + inTabId).find(".tabContents").focus(); ui.draggable.data("sameTab",false);
}
});
}
if (needBr) theTabDiv.html(" ");
tabContainer.tabs("refresh");
return theTabDiv;
}
function changeTheme(name) {
if (typeof changeTheme.head === 'undefined') {
changeTheme.head = document.getElementsByTagName('head')[0];
changeTheme.style = document.createElement('style');
changeTheme.style.type = 'text/css';
changeTheme.style.innerHTML = "";
changeTheme.head.appendChild(changeTheme.style);
}
if (name in gThemes) {
gMainOptions.themeName = name;
var css = ".thControls {background-color:" + gThemes[name].controls.bg + "; color:" + gThemes[name].controls.color + "; border-color:" + gThemes[name].controls.bColor + "; } .thControls .thColor2 {color:" + gThemes[name].controls.color2 + ";} .ui-layout-pane {background-color:" + gThemes[name].main.bg + " !important;} .ui-widget-content {background-color:" + gThemes[name].center.bg + " !important;} .JROffButton {background-color:" + gThemes[name].buttons.bgOff + " !important; color:" + gThemes[name].buttons.colorOff + "; border-color:" + gThemes[name].buttons.bColorOff + " !important; } .JRCellButton.JROffButton {background-color:" + gThemes[name].cellButtons.bgOff + " !important; color:" + gThemes[name].cellButtons.colorOff + " !important; border-color:" + gThemes[name].cellButtons.bColorOff + " !important; } .JROnButton {background-color:" + gThemes[name].buttons.bgOn + " !important; color:" + gThemes[name].buttons.colorOn + " !important; border-color:" + gThemes[name].buttons.bColorOn + " !important; } .JRCellButton.JROnButton {background-color:" + gThemes[name].cellButtons.bgOn + " !important; color:" + gThemes[name].cellButtons.colorOn + " !important; border-color:" + gThemes[name].cellButtons.bColorOn + " !important; } .JRPausedButton {background-color:" + gThemes[name].cellButtons.bgPaused + " !important; color:" + gThemes[name].cellButtons.colorPaused + " !important; border-color:" + gThemes[name].cellButtons.bColorPaused + " !important; } .JRCellButton.JRDisableButton {background-color:" + gThemes[name].cellButtons.bgDisable + " !important; color:" + gThemes[name].cellButtons.colorDisable + " !important; border-color:" + gThemes[name].cellButtons.bColorDisable + " !important; } .ui-tabs-nav {background-color:" + gThemes[name].tabs.bg + " !important; color:" + gThemes[name].tabs.color + " !important;} .JRDialog {background-color:" + gThemes[name].dialog.bg + " !important; color:" + gThemes[name].dialog.color + " !important;} .ui-tooltip {background-color:" + gThemes[name].dialog.bg + " !important; color:" + gThemes[name].dialog.color + " !important;} .dialogModal {background-color:" + gThemes[name].dialog.bg + " !important; color:" + gThemes[name].dialog.color + " !important;} .JRDialog a {color:" + gThemes[name].dialog.colorA + " !important;} .column1 {background-color:" + gThemes[name].dialog.bgC1 + " !important; color:" + gThemes[name].dialog.colorC1 + " !important;} .column2 {background-color:" +gThemes[name].dialog.bgC2 + " !important; color:" + gThemes[name].dialog.colorC2 + " !important;} .column3 {background-color:" + gThemes[name].dialog.bgC3 + " !important; color:" + gThemes[name].dialog.colorC3 + " !important;} .column3\\.1 {background-color:" + gThemes[name].dialog.bgC2 + " !important; color:" + gThemes[name].dialog.colorC2 + " !important;} .column4 {background-color:" + gThemes[name].dialog.bgC4 + " !important; color:" + gThemes[name].dialog.colorC4 + " !important;} .JRTabs.ui-state-default {background-color:" + gThemes[name].tabs.bgD + " !important;} .ui-state-default .JRTabLabel {color:" + gThemes[name].tabs.colorD + " !important;} .JRTabs.ui-state-default.ui-state-active {background-color:" + gThemes[name].tabs.bgA + " !important;} .ui-state-default.ui-state-active .JRTabLabel {color:" + gThemes[name].tabs.colorA + " !important;} .JRTabs.ui-state-hover {background-color:" + gThemes[name].tabs.bgH + " !important;} .JRTAddButton {background-color:" + gThemes[name].buttons.bgOff + " !important; color:" + gThemes[name].buttons.colorOff + " !important;}";
changeTheme.style.innerHTML = css;
$(".JRStatusText").css({"color":gThemes[name].colorEmp.color2});
}
}
// Alarm function -----------
function doAfterSound() {
if (gAlarmObject.ttsString!=="") speakThisNow(gAlarmObject.ttsString); gAlarmObject.ttsString = null;
gAlarmObject.removeEventListener("ended",doAfterSound);
}
function playThisSound( keyName, ttsString ) {
if (gSoundOptions[keyName].mute) { if (gSoundOptions[keyName].tts && ttsString && ttsString!=="") speakThisNow(ttsString); else return; }
if (gAlarmObject) gAlarmObject.pause(); gAlarmObject = null; gAlarmObject = gAlarmSounds[keyName].audio; gAlarmObject.currentTime = 0;
gAlarmObject.volume = gMainOptions.alarmVolume/100; gAlarmObject.ttsString = (ttsString && ttsString!=="") ? ttsString : "";
gAlarmObject.addEventListener("ended", doAfterSound); gAlarmObject.play();
}
function playNewSound( AudioObject ) {
if (gSoundFile) gSoundFile.pause();
gSoundFile = AudioObject; gSoundFile.currentTime = 0; gSoundFile.volume = gMainOptions.alarmVolume/100;
gSoundFile.play();
}
function speakThisNow(thisText) {
if('speechSynthesis' in window){
var speech = new window.SpeechSynthesisUtterance(thisText);
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
}
function setupFixSound() { // Thanks goes to parseHex from Greasyfork for finding this workaround. Seems to be working.
if (gAudioFixStarted) return;
gAudioFixStarted = true;
gOscillator = gAudioCtx.createOscillator();
var gainNode = gAudioCtx.createGain();
gOscillator.connect(gainNode); gainNode.connect(gAudioCtx.destination);
gOscillator.type = 'sine';
gainNode.gain.setTargetAtTime(0.0004, gAudioCtx.currentTime, 0);
gOscillator.frequency.setTargetAtTime(30, gAudioCtx.currentTime + 0.5, 0.5);
gOscillator.start();
}
// Main cycler class that handles all timers, queues, pauses, and hams
var theCycler = (function() {
var privateVars = {
_timers: [], _theQueue: [], _theFrontOfTheLineQueue: [], _theFrontOfTheLineTimer: [],
_before1: new Date(), _before2: new Date(), _lastRemoved: -1, _theCycle: 500, _realCycle: 500,
_theCycleElapsed: 0, _theCycleSkipping: 0, _paused: false, _doHam: null, _timeoutVar: null
};
var privateFunctions = {
_getInTimer: function(theNumber) {
for (var i=0, len=privateVars._timers.length; i -1) return [foundNumber,privateVars._theQueue.splice(foundNumber, 1)[0]];
else if (foundNumber == -86) { var returnData = privateVars._doHam; privateVars._doHam = null; return [foundNumber,returnData]; }
else return null;
},
_goFrontOfTheLineTimer: function() {
var frontOfTheLineNumber = privateVars._theFrontOfTheLineTimer.shift();
var frontOfTheLineItem = privateFunctions._getInTimer(frontOfTheLineNumber);
if (gMainOptions.debugger==2) console.log("Frontofthelinetimer: " + JSON.stringify(frontOfTheLineItem)); // debugger =2 for queue details.
if (frontOfTheLineItem) {
frontOfTheLineItem.runFunction.apply("frontoftheline",[frontOfTheLineItem.elapsed,frontOfTheLineItem.theNumber] );
frontOfTheLineItem.elapsed = 0;
return true;
} else return false;
},
_goFrontOfTheLine: function() {
var frontOfTheLineNumber = privateVars._theFrontOfTheLineQueue.shift(), thisItem = null, removeResult = null, frontOfTheLineQueue = null;
removeResult = privateFunctions._removeFromQueue(frontOfTheLineNumber);
if (!removeResult) return false;
frontOfTheLineQueue = removeResult[1];
if (frontOfTheLineQueue) {
if (gMainOptions.debugger==2) console.log("Frontofthelinequeue: " + JSON.stringify(frontOfTheLineQueue)); // debugger =2 for queue details.
for (var c=0, len=frontOfTheLineQueue.length; c= privateVars._timers[i].milliSeconds) {
returnStatus = privateVars._timers[i].runFunction.apply("timer",[privateVars._timers[i].elapsed,privateVars._timers[i].theNumber] );
privateVars._timers[i].elapsed = 0;
}
}
return returnStatus;
},
_doQueue: function() {
var skipThis = true, queueItem = null, counter=0, doOnce=false, weighted=false, weightedRan=false, removed=false;
if (gMainOptions.debugger==2) console.log("Queue: " + JSON.stringify(privateVars._theQueue)); // debugger =2 for queue details.
do {
queueItem = privateVars._theQueue[counter];
if (queueItem.length>1) weighted=true;
if (queueItem[0].weightStatus=="item") { // check to see if this item is not null for weighted items. Non weighted items will never have nulls.
try { skipThis = !queueItem[0].runFunction.apply("queue",[privateVars._theCycleElapsed,queueItem[0].theNumber] ); }
catch(e) { console.log('JRPanda: An error has occurred: '+e.message); }
doOnce = queueItem[0].doOnce;
if (privateVars._lastRemoved==queueItem[0].theNumber) removed=true; // Was this item removed already?
if (!removed) privateVars._theQueue.splice(counter,1); // remove from queue because item was either done or skipped.
weightedRan=true;
} else weightedRan=false;
if (weighted && !removed) queueItem.push(queueItem.shift()); // Take from top of item queue and place on bottom to keep null weight items.
if (weighted && !weightedRan && !removed) privateVars._theQueue.splice(counter,1,queueItem); // Replace item in same place if this was skipped because of null weight item.
if ( (!weighted && !doOnce && !removed) || (weighted && weightedRan && !removed) ) privateVars._theQueue.push(queueItem);
counter++; weighted=false;
} while (privateVars._theQueue.length > 0 && skipThis && counter < privateVars._theQueue.length);
privateVars._lastRemoved = -1; // Reset last removed so everything is fresh.
},
_theLoop: function() {
var continueCheck = true;
var elapsed = new Date().getTime() - privateVars._before1.getTime();
var elapsed2 = new Date().getTime() - privateVars._before2.getTime();
if (elapsed2 >= 50) {
if (privateVars._theFrontOfTheLineTimer.length > 0) continueCheck = !privateFunctions._goFrontOfTheLineTimer();
if (continueCheck && privateVars._timers.length > 0) continueCheck = !privateFunctions._doTimers(elapsed2);
privateVars._before2 = new Date();
}
continueCheck = true;
if (elapsed >= privateVars._realCycle) {
privateVars._theCycleElapsed = elapsed;
if (privateVars._theFrontOfTheLineQueue.length > 0) continueCheck = !privateFunctions._goFrontOfTheLine();
if (continueCheck && privateVars._doHam) { continueCheck = false; privateFunctions._goHam(); }
if (continueCheck && privateVars._theQueue.length>0) { privateFunctions._doQueue(); }
privateVars._before1 = new Date();
}
privateVars._timeoutVar = setTimeout(privateFunctions._theLoop, 5);
}
};
var output = {
addJob: function(func, theNumber, milliSeconds, doOnce, weight) {
if (typeof func === 'function' && !isNaN(milliSeconds)) {
doOnce = (typeof doOnce != 'undefined') ? doOnce : false; weight = (typeof weight != 'undefined') ? weight : 0;
if (privateFunctions._checkInQueue(theNumber)!=-1) return;
for(var i=0, len=privateVars._timers.length; i 0) privateVars._timers.unshift(jobData[0]);
}
if (privateVars._timeoutVar===null) { privateVars._before1 = new Date(); privateVars._before2 = new Date(); privateFunctions._theLoop(); }
},
removeJob: function(theNumber) {
var returnValue = false;
if (privateFunctions._removeFromQueue(theNumber)) privateVars._lastRemoved = theNumber;
for (var i=0, len=privateVars._timers.length; i0 || privateVars._theQueue.length>0)
privateVars._timeoutVar = setTimeout(privateFunctions._theLoop, 0);
},
frontOfTheLineTimer: function( theNumber ) { privateVars._theFrontOfTheLineTimer.push(theNumber); },
frontOfTheLine: function( theNumber ) { privateVars._theFrontOfTheLineQueue.push(theNumber); },
changeWeight: function( theNumber, newWeight ) {
var foundNumber = privateFunctions._checkInQueue(theNumber), thisItem=null, itemQueue=null;
if (foundNumber==-86) itemQueue = privateVars._doHam;
else if (foundNumber>-1) itemQueue = privateVars._theQueue.splice(foundNumber, 1)[0];
if (itemQueue) {
for (var c=0, len=itemQueue.length; c gMainOptions.captchaAt+5)) ? "" : "Captcha Count: " + gMainData.captchaCounter);
}
function createQueueLinks(theData) {
var theLinks = createSpan2();
if (theData.hitId!=="" && theData.groupId!=="" && theData.assignmentId!=="" && gMainData.authenticityToken!=="") {
var returnLinkURL = createLink2("Return","#","_blank","Return");
returnLinkURL.addEventListener('click', function() {
gAlarmSounds.queueAlert.audio.pause();
showYesNoDialog("Are you sure you want to return this hit?",function() {
returnHit(theData.groupId,theData.hitId,theData.assignmentId);
});
return false;
});
theLinks.appendChild(returnLinkURL); theLinks.appendChild(document.createTextNode(" :: "));
}
if (theData.hitId!=="") {
var continueLinkURL = createLink2("Continue Work",theData.continueURL.replace("ref=w_pl_prvw","from_queue=true"),"_blank","Continue Work");
continueLinkURL.classList.add("JRQueueContinue");
continueLinkURL.addEventListener('click', function(e) {
gAlarmSounds.queueAlert.audio.pause();
var theHeight=window.outerHeight-80, theWidth=window.outerWidth-10;
window.open($(e.target).attr("href"),"_blank","width=" + theWidth + ",height=" + theHeight + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
return false;
});
theLinks.appendChild(continueLinkURL);
}
return theLinks;
}
function displayQueueStatus(queueAlertOK) {
var lowestTime = null, theTimeLeft = null, timeLeftString="";
addToQueueWatchLog(createSpan(""),true);
gMainData.hitsInQueue = gQueueData.length;
if (gQueueData.length>0) {
for (var i=gQueueData.length-1; i>=0; i--) {
theTimeLeft = getTimeLeft(gQueueData[i].timeLeft);
timeLeftString = (!theTimeLeft || theTimeLeft.weeks<0) ? "Expired" : convertToTimeString(theTimeLeft);
addToQueueWatchLog(createSpan("(" + gQueueData[i].requesterName + ") [$" + gQueueData[i].pay + "] - " +
timeLeftString + " - " + gQueueData[i].title + " :: ").data("thisData",gQueueData[i])
.append(createQueueLinks(gQueueData[i])));
}
if (queueAlertOK && !$("#muteQueueWatchAlarm").is(":checked")) {
lowestTime = getTimeLeft(gQueueData[0].timeLeft);
if (lowestTime && lowestTime.weeks < 1 && lowestTime.days < 1 && lowestTime.hours < 1 && lowestTime.minutes < parseInt(gSoundOptions.queueAlert.lessMinutes)) {
if (!gAlarmSounded) { gAlarmSounded = lowestTime; gAlarmSounded.minutes=60; }
if (lowestTime.minutes < gAlarmSounded.minutes) {
gAlarmSounded = lowestTime;
if (!gSoundOptions.queueAlert.mute) playThisSound("queueAlert");
else if (gSoundOptions.queueAlert.tts) speakThisNow("Running out of time!");
$("#JRQueueWatchLog").css({"background-color":"#8A0000"});
$("#JRQueueWatchLog").animate({"backgroundColor":"#000000"}, 10000, function() {
$("#JRQueueWatchLog").css({"background-color":"#000000"});
});
}
} else gAlarmSounded = null;
}
} else {
addToQueueWatchLog(createDiv("You have no hits in your queue at this time. Click on the black background to refresh your queue. " +
"An alarm will be heard if a hit has " + gSoundOptions.queueAlert.lessMinutes + " minutes left. Mute the alarm to the right if not needed. " +
"This window gets updated every " + convertToSeconds(gMainOptions.queueTimer) + " seconds.")
.css({"font-size":"15px","color":"#7FFFD4","margin-top":"12px","text-align":"center","line-height":"18px"}));
}
$("#JRStatusTab_2 .JRTabLabel:first").html("Queue Watch - " + ((gMainData.hitsInQueue <=25) ? gMainData.hitsInQueue : "25"));
}
function fullQueueTimer() { gFullQueue = false; }
function displayHitStatus( container,theNumber ) {
if (!window.jQuery || theNumber<0) return;
var hitInfo = gMainData.hitCollection[theNumber], hitStatus = hitInfo.status;
var skippedStatus = (hitInfo.data.action.toLowerCase().indexOf("filter") != -1) ? "Skip: " + hitStatus.skipped + " | " : "";
var missedStatus = (hitInfo.data.action.toLowerCase().indexOf("pantha") != -1) ? "Miss: " + hitStatus.missed + " | " : "";
var foundHits = (hitInfo.data.action.toLowerCase().indexOf("search") != -1) ? "/" + hitStatus.foundHits : "";
var statusText = "[ Acc: " + hitStatus.accepted + foundHits + " | " + skippedStatus + missedStatus + "Srch: " + hitStatus.searched + " ]";
if (container) $(container).html(statusText);
else $("#JRCellStatus_" + theNumber).html( statusText );
displayMainStatus();
}
function processResults( theNumber, result, finalUrl, jobData ) {
var hitInfo = (theNumber>0) ? gMainData.hitCollection[theNumber] : null;
var hitData = (hitInfo) ? hitInfo.data : null;
var hitStatus = (hitInfo) ? hitInfo.status : null;
var hitDataActionSix = (hitData) ? hitData.action.toLowerCase().substring(0,6) : "";
switch(result) {
case "NOTQUALIFIED":
if (hitStatus) hitStatus.notQual++;
hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRHamButton"),hamOn,hamOff,"off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
updateHitCell(theNumber);
break;
case "BLOCKED": // stop collecting this job. Change background to error color.
if (hitStatus) hitStatus.blocked++;
hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRHamButton"),hamOn,hamOff,"off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
updateHitCell(theNumber);
break;
case "NOACCEPT": // Missed a hit because someone else took it. So mad.
if (hitDataActionSix == "search" || hitDataActionSix == "pantha") { hitStatus.missed++; hitStatus.noHits++; gMainData.missed++; }
break;
case "NOMORE":
if (hitStatus) hitStatus.noHits++;
gMainData.noHits++;
break;
case "TOOFAST":
if (hitStatus) hitStatus.tooFast++;
gMainData.tooFast++;
if (theCycler.isHamOn()) gMainData.tooFastHam++; else gMainData.tooFastNormal++;
if (gSlowDownAuto) theCycler.cycleIncrease(gMainOptions.cycleAutoIncrease);
if (finalUrl) {
var acceptPage = (finalUrl.indexOf("mturk/accept") != -1);
var previewPage = (finalUrl.indexOf("mturk/preview") != -1);
if (acceptPage || previewPage) {
if (hitDataActionSix == "search" || (hitDataActionSix == "pantha" && acceptPage)) {
if (gMainOptions.debugger>0) console.log("got a PRE for a search or pantha on: " + finalUrl); // debugger >0 for pre on search or pantha
hitInfo.goToUrl.push({"url":finalUrl,"theNumber":theNumber});
}
}
}
break;
case "LOGGEDOFF":
if (!theCycler.isPaused()) {
var addText = createDiv("You are logged out of Amazon.
Can't accept hits so pausing.
Please log back in!")
.css({"margin-top":"30px","font-size":"17px","text-align":"center"});
$(addText).append(createDiv(createLink("Log in to Mturk Page","http://worker.mturk.com/","_blank","http://worker.mturk.com/")
.click( function() {
gJRPOP = window.open("http://worker.mturk.com/","_blank","width=" + 1000 + ",height=" + 800 + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
return false;
})).css({"margin-top":"15px"}));
showWaitDialog("Logged Out!!","",function() {
theCycler.unpause();
$("#JRPauseButton").html("Pause").css({"background-color":"ivory","color":"black"});
theCycler.frontOfTheLineTimer(-1);
},null,addText,true);
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
if (gNotifications) showNotification( "ALERT: Logged Off!", "You are logged off of mturk so need to log back in as soon as possible",
"loggedoff", "3ALERT3", true);
if (!gSoundOptions.hasToPause.mute) playThisSound("hasToPause");
else if (gSoundOptions.hasToPause.tts) speakThisNow("Sorry. You were logged off of m turk.");
}
break;
case "DAILYLIMIT":
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
checkDelayedSave(); stopAll();
showWaitDialog("Daily Limit Reached","",function() {},null,
createDiv("ALERT: CONGRATS!
You have reached your mturk daily limit!! You must wait for tomorrow. Go outside and see the sun!")
.css({"font-size":"18px","text-align":"center","margin":"20px 10px","line-height":"22px"}),false,240,510);
if (gNotifications) showNotification( "ALERT: CONGRATS!", "You have reached your daily limit!! You must wait for tomorrow. Go outside and see the sun!",
"loggedoff", "3ALERT3", true);
break;
case "NOTCOMPLETED":
case "ERROR":
if (hitStatus) hitStatus.error++;
gMainData.error++;
break;
case "QUEUEMAX":
if (hitStatus) hitStatus.fullQueue++;
if (!gFullQueue) {
if (!gSoundOptions.fullQueue.mute) playThisSound("fullQueue");
else if (gSoundOptions.fullQueue.tts) speakThisNow("Your queue is full!");
gFullQueueTimer = setTimeout( function() { fullQueueTimer(); }, 240000 );
}
gFullQueue = true;
gMainData.fullQueue++;
break;
case "SKIPPED":
if (hitStatus) hitStatus.skipped++;
gMainData.skipped++;
break;
case "ACCEPTED":
gMainData.captchaCounter++;
if (hitStatus) hitStatus.accepted++;
if (hitInfo.ham == "ontimed") hitInfo.lastAccept = new Date();
var collectedDate = new Date(), newDateString = formatAMPM("onlydate",collectedDate); hitData.day = newDateString;
if (hitData.dailyLimit && hitData.dailyLimit>0) hitData.dailyDone = (gMturkDate == hitData.day) ? hitData.dailyDone+1 : 1;
if (hitData.once) hitData.oneDone = 1;
gMainData.accepted++; gMainData.hitsInQueue++;
gQueueDelay.push({"date":new Date(), "jobData":jobData});
addToQueueWatch(jobData);
gSendQueue = true;
var hitPay = parseFloat(hitData.pay), theDuration = hitInfo.minutes;
gMainData.payCounter = gMainData.payCounter + hitPay; gMainData.totalEarnings = gMainData.projectedEarnings + gMainData.payCounter;
if (theDuration===0 && hitData.duration!="0") {
theDuration = (hitData.duration.indexOf("weeks")!=-1) ? 5000 : (hitData.duration.indexOf("day")!=-1) ? 1500 : (hitData.duration.indexOf("hours")!=-1) ? 200 :
(hitData.duration.indexOf("hour")!=-1) ? 60 : (hitData.duration.indexOf("minutes")!=-1) ? parseInt(hitData.duration.split("minutes")[0]) : 1;
hitInfo.durationParsed = getTimeLeft(hitData.duration); hitInfo.minutes = theDuration;
}
var theSoundFile = "less99", notificationTitle = "Accepted Hit From: " + hitData.requesterName;
var notificationMessage = "Pay: " + hitData.pay + "\nDuration: " + hitData.duration + "\nTitle: " + hitData.title;
if (!hitData.mute) {
if ( hitPay < parseFloat(gSoundOptions.less2.payRate) ) {
theSoundFile = (theDuration !== 0 && theDuration<=parseInt(gSoundOptions.less2Short.lessMinutes)) ? "less2Short" : "less2";
} else if ( hitPay <= parseFloat(gSoundOptions.less5.payRate) ) {
theSoundFile = (theDuration !== 0 && theDuration<=parseInt(gSoundOptions.less5Short.lessMinutes)) ? "less5Short" : "less5";
} else if ( hitPay <= parseFloat(gSoundOptions.less15.payRate) ) {
theSoundFile = (theDuration !== 0 && theDuration<=parseInt(gSoundOptions.less15Short.lessMinutes)) ? "less15Short" : "less15";
} else if ( hitPay < parseFloat(gSoundOptions.less99.payRate) ) { theSoundFile = "less99"; }
if (hitData.audioforce !== "") theSoundFile = hitData.audioforce;
var speakThis = (gSoundOptions[theSoundFile].tts) ? "Accepted hit from " + hitData.requesterName + ". Duration " + hitData.duration +
". Paying " + hitData.pay : "";
//if (gRapidSuppress.jobNumber != theNumber) { if (gSoundOptions[theSoundFile].mute) speakThisNow(speakThis); else playThisSound(theSoundFile,speakThis); }
if (gSoundOptions[theSoundFile].mute) speakThisNow(speakThis); else playThisSound(theSoundFile,speakThis);
gRapidSuppress.jobNumber = theNumber; gRapidSuppress.counter = 8;
}
if (gScriptStatus == "normal") {
var noLimits = checkLimits(theNumber);
hitInfo.hitCell.stop(true,true);
if (!noLimits && !hitData.once) { hitInfo.hitCell.css({"background-color":"#FFA691"}); }
else {
hitInfo.hitCell.css({"background-color":"yellow"});
hitInfo.hitCell.animate({"backgroundColor": hitInfo.hitCell.data("backgroundColor")}, 30000);
}
}
if (gNotifications) showNotification( notificationTitle, notificationMessage, "accepted", hitData.groupId);
if ( hitInfo.ham == "paused" ) { toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff); }
addToAcceptedLog( hitData.requesterName + " - " + hitData.groupId +
" [" + formatAMPM("dayandtime",collectedDate) + "] - " + hitData.title );
updateHitCell(theNumber);
gDelayedSave = true;
break;
}
if (theNumber > 0) displayHitStatus(null,theNumber);
}
function returnHit(groupId,hitId,assignmentId) {
GM_xmlhttpRequest({
method: "POST", url: "https://worker.mturk.com/projects/" + groupId + "/tasks/" + hitId + "?assignment_id=" + assignmentId + "&ref=w_wp_rtrn_top",
headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" },
data: "_method=delete&authenticity_token=" + encodeURIComponent(gMainData.authenticityToken),
onload: function() { removeFromQueueWatch(hitId); },
});
}
function requestUrl(theUrl, theNumber, theFunction, errorFunction, data1, data2, theResponseType, acceptText) {
theResponseType = theResponseType || ""; acceptText = acceptText || "text/html";
if (gMainOptions.debugger>1) console.log("JR going to get: " + theUrl); // debugger >1 for request details
GM_xmlhttpRequest({
method: "GET",
url: theUrl,
headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "User-Agent": "Mozilla/5.0", "Accept": acceptText },
responseType: theResponseType,
onload: function(response) { if (typeof theFunction == 'function') theFunction(response,theNumber,data1,data2); },
onerror: function(response) { errorRequest(response,theNumber); }
});
}
function errorRequest(response,theNumber) {
if (response && response.error) {
console.log("error " + theNumber + ": " + response.error);
if (response.error.indexOf("https://www.amazon.com/ap/signin?")!=-1) processResults( theNumber, "LOGGEDOFF", response.error );
}
}
function pandaLinkNew(theGroupId) { return "http://worker.mturk.com/projects/" + theGroupId.trim() + "/tasks/accept_random?ref=w_pl_prvw"; }
function previewLinkNew(theGroupId) { return "http://worker.mturk.com/projects/" + theGroupId.trim() + "/tasks?ref=w_pl_prvw"; }
function requesterSearchNew(theRequesterID,minReward) { return "https://worker.mturk.com/requesters/" + theRequesterID.trim() + "/projects?page_size=30&filters%5B" +
"qualified%5D=true&filters%5Bmasters%5D=false&sort=num_hits_desc&filters%5Bmin_reward%5D=" + minReward + "&format=json"; }
function acceptLinkNew(theGroupId,theHitId) { return "https://worker.mturk.com/projects/" + theGroupId.trim() + "/tasks/" + theHitId.trim() + "/accept?ref=w_wp_acpt_top"; }
function setSearchOptionsDefault() {
var searchOptions = JSON.parse(JSON.stringify(gDefaultSearchOptions)), theHistory = {};
return {"searchOptions":searchOptions,"theHistory":theHistory};
}
function checkLimits(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, returnValue = false, secondsOn = Math.floor((new Date() - hitInfo.started) / 1000);
var thisKey = hitData.requesterName + "::" + hitData.title + "::" + hitData.pay;
if (hitData.queueLimit === 0 && hitData.queueHitLimit === 0 && hitData.dailyLimit === 0 && !hitData.once && hitData.secondsOff==-1) returnValue = true;
else if ( (hitData.once && hitData.oneDone>0) || (hitData.dailyLimit > 0 && parseInt(hitData.dailyLimit) <= parseInt(hitData.dailyDone)) ||
(hitData.secondsOff!=-1 && secondsOn >= hitData.secondsOff) ) {
if (hitInfo.hitCell.data("status")=="on") hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRHamButton"),hamOn,hamOff,"off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
returnValue = false; }
else if (hitData.queueHitLimit > 0 && (gQueueCount[thisKey] === "undefined" || gQueueCount[thisKey] >= hitData.queueHitLimit)) returnValue = false;
else if (hitData.queueLimit > 0 && hitData.queueLimit <= gMainData.hitsInQueue) returnValue = false;
else returnValue = true;
return returnValue;
}
function checkJobMode(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, returnValue = true;
if (hitData.action.toLowerCase().indexOf("panda")!=-1 && hitData.groupId==="") {
if (hitInfo.hitCell.data("status")=="on") hitInfo.hitCell.data("status","off");
toggleButtonOff( hitInfo.hitCell.find(".JRCollectButton"),startCollecting,stopCollecting);
returnValue=false;
}
return returnValue;
}
function createCloneButton(thetext,bgColor,theStyle,className) {
var cloneButton = createSpanButton(function() {},className,thetext,bgColor,null,null,theStyle); return cloneButton;
}
function initCloneButton(hitRow,theData,className,hitNumber,theFunction) {
var cloneButton = hitRow.getElementsByClassName(className)[0]; cloneButton.style.display = "inline-block";
cloneButton.setAttribute("data-hitNumber",hitNumber); cloneButton.setAttribute("data-theData",JSON.stringify(theData));
$(cloneButton).on("click", function(e) { theFunction(e); });
}
function addAJob(e,thisData,once,collectNow,disableButtons,search) {
thisData = (thisData) || JSON.parse(e.target.getAttribute("data-theData"));
if (thisData.requesterId==="") search=false;
if (!("secondsOff" in thisData)) thisData.secondsOff=-1; if (!("goHam" in thisData)) thisData.goHam=false; // added options but make sure earlier scripts can work also.
if (thisData.groupId!=="" || search) {
var newNumber = fillNewHitData(thisData.requesterName, thisData.requesterId, thisData.groupId, thisData.pay,
thisData.title, thisData.duration, once, true, collectNow, (search) ? "search" : "panda", thisData.secondsOff, thisData.goHam);
gMainData.hitCollection[newNumber].numberHits = thisData.hitsAvailable; theCycler.frontOfTheLine(newNumber);
if (disableButtons && e) $(e.target).closest(".hitRow").find(".JRPandaButton,.JROnceButton,.JRAddJobButton").addClass("ui-state-disabled").off("click");
}
}
function createHitRow(theData,buttons,dialogWidth,titleWidth,fromWhere) {
if (fromWhere!="mturk" && fromWhere!="jobs" && fromWhere!="grouping") return;
var durationTime = (theData.duration != "Time") ? getTimeLeft(theData.duration) : theData.duration, theCheckbox = null;
var durationText = (theData.duration != "Time") ? ((durationTime) ? durationTime.hours + ":" + ("0" + durationTime.minutes).slice(-2) : "0.00") : theData.duration;
var payText = (theData.pay) ? ((theData.pay == "Pay") ? theData.pay : "$" + theData.pay) : "0";
var spanWidth = dialogWidth - titleWidth, hitRow = null;
if (!gTemplateHitRow) {
gTemplateHitRow = document.createElement('div');
var commonSpanStyle = " border:1px solid black; display:inline-block; overflow:hidden; white-space: nowrap; box-sizing:content-box";
gTemplateHitRow.className = "hitRow";
if (fromWhere=="jobs" || fromWhere=="grouping") gTemplateHitRow.appendChild(createCheckbox2("JRCheckbox",null,"margin:-15px 2px 0 0; padding:0; display:inline-block;"));
gTemplateHitRow.appendChild(createSpan2("column1","First","background-color:#FBF5E6; width:140px; text-align:right;" + commonSpanStyle));
gTemplateHitRow.appendChild(createSpan2("column2","Second","background-color:#FCF6CF; width:" + spanWidth + "px; cursor:pointer;" + commonSpanStyle));
gTemplateHitRow.appendChild(createSpan2("column3","Third","background-color:#F0FFFF; width:35px;" + commonSpanStyle));
if (fromWhere=="mturk") gTemplateHitRow.appendChild(createSpan2("column3.1","4th","background-color:#F5F5DC; width:40px;" + commonSpanStyle));
gTemplateHitRow.appendChild(createSpan2("column4","5th","background-color:#7FFFD4; width:40px;" + commonSpanStyle));
gTemplateHitRow.appendChild(createCloneButton("Collect",""," overflow:hidden; display:none; height:12px; line-height:12px;box-sizing:content-box",
"JRCollectButton JRCellButton JRButton JROffButton"));
gTemplateHitRow.appendChild(createCloneButton("Details",""," overflow:hidden; display:none; height:12px; line-height:12px;box-sizing:content-box",
"JRDetailsButton JRCellButton JRButton JROffButton"));
gTemplateHitRow.appendChild(createCloneButton("Panda",""," overflow:hidden; display:none; height:12px; line-height:12px;box-sizing:content-box",
"JRPandaButton JRCellButton JRButton JROffButton"));
gTemplateHitRow.appendChild(createCloneButton("Once",""," overflow:hidden; display:none; height:12px; line-height:12px;box-sizing:content-box",
"JROnceButton JRCellButton JRButton JROffButton"));
gTemplateHitRow.appendChild(createCloneButton("Add",""," overflow:hidden; display:none; height:12px; line-height:12px;box-sizing:content-box",
"JRAddJobButton JRCellButton JRButton JROffButton"));
}
if (gTemplateHitRow) {
if (fromWhere=="mturk" || theData.duration == "Time" || ((fromWhere=="jobs" || fromWhere=="grouping") && parseInt(theData.jobNumber) in gMainData.hitCollection)) {
hitRow = gTemplateHitRow.cloneNode(true);
hitRow.getElementsByClassName("column1")[0].textContent = (theData.friendlyRName && theData.friendlyRName!=="") ? theData.friendlyRName : theData.requesterName;
hitRow.getElementsByClassName("column2")[0].textContent = (theData.friendlyTitle && theData.friendlyTitle!=="") ? theData.friendlyTitle : theData.title;
hitRow.getElementsByClassName("column3")[0].textContent = durationText;
if (fromWhere=="mturk") hitRow.getElementsByClassName("column3.1")[0].textContent = theData.hitsAvailable;
hitRow.getElementsByClassName("column4")[0].textContent = payText;
if (fromWhere=="jobs" && theData.jobNumber != "-1" && theData.duration != "Time") {
initCloneButton(hitRow,theData,"JRCollectButton JRButton JROffButton",theData.jobNumber,function(e) {
var theClone = gMainData.hitCollection[e.target.getAttribute("data-hitNumber")].hitCell.find(".JRCollectButton")[0];
$(theClone).click(); $(e.target).removeClass().addClass($(theClone).attr("class"));
});
initCloneButton(hitRow,theData,"JRDetailsButton JRButton JROffButton",theData.jobNumber,function(e) {
var hitNumber = e.target.getAttribute("data-hitNumber");
showEditHitDialog(hitNumber,$(e.target),function() { $("#JREditDialog").dialog( "close"); });
});
theCheckbox = hitRow.getElementsByClassName("JRCheckbox")[0];
theCheckbox.setAttribute("data-hitNumber",theData.jobNumber);
} else if (fromWhere=="jobs" && theData.duration == "Time") {
hitRow.getElementsByTagName("input")[0].addEventListener("click", function(e) {
$(e.target).closest(".searchingResultsArea").find("input").prop("checked",$(e.target).prop("checked"));
});
} else if (fromWhere=="mturk" && theData.duration != "Time") {
initCloneButton(hitRow,theData,"JRPandaButton JRButton JROffButton",theData.jobNumber,function(e) { addAJob(e,null,false,true,true,false); });
initCloneButton(hitRow,theData,"JROnceButton JRButton JROffButton",theData.jobNumber,function(e) { addAJob(e,null,true,true,true,false); });
initCloneButton(hitRow,theData,"JRAddJobButton JRButton JROffButton",theData.jobNumber,function(e) { addAJob(e,null,false,false,true,false); });
} else if (fromWhere=="grouping" && theData.duration != "Time") {
if (theData.selected) hitRow.getElementsByClassName("JRCheckbox")[0].checked = true;
theCheckbox = hitRow.getElementsByClassName("JRCheckbox")[0];
theCheckbox.setAttribute("data-hitNumber",theData.jobNumber);
var addThisClass = "JRDelayedHam JRButton", theStatus = "false";
if (theData.hamOn) { addThisClass += " JROnButton"; theStatus = "true"; }
else { addThisClass += " JROffButton"; }
var hamDelayed = createSpanButton(function(e) {
e.target.setAttribute("data-status",(e.target.getAttribute("data-status") == "true") ? "false" : "true");
if (e.target.getAttribute("data-status") == "true") $(e.target).removeClass("JROffButton").addClass("JROnButton");
else $(e.target).removeClass("JROnButton").addClass("JROffButton");
},addThisClass,"Delayed Ham Mode",null,null,null," overflow:hidden; display:inline-block; height:12px; line-height:12px; box-sizing:content-box");
hamDelayed.setAttribute("data-status",theStatus);
hitRow.appendChild(hamDelayed);
}
} else { delete gRequestersData[parseInt(theData.jobNumber)]; gDelayedSave=true; }
}
return hitRow;
}
function historyUnique(searchData,requestersInfo,historyLimit) {
var searchHistory = searchData.theHistory, historyArray = searchData.searchOptions.historyArray, returnValue = false;
if (searchHistory[requestersInfo.groupId]) { searchHistory[requestersInfo.groupId].date = new Date(); returnValue = false; }
else { searchHistory[requestersInfo.groupId] = {"info":requestersInfo,"date":new Date()}; historyArray.push(requestersInfo.groupId); returnValue = true; }
if (historyArray.length>historyLimit) {
var removeThese = historyArray.splice(0, historyArray.length-historyLimit);
for (var i=0, len=removeThese.length; i parseFloat(searchOptions.maxReward)) return false;
if (searchOptions.excludeTerm.length && searchOptions.excludeTerm[0] !== "" && requestersData.title.toLowerCase().indexOf(searchOptions.excludeTerm[0].toLowerCase()) != -1)
return false;
if (searchOptions.includeTerm.length && searchOptions.includeTerm[0] !== "" && requestersData.title.toLowerCase().indexOf(searchOptions.includeTerm[0].toLowerCase()) == -1)
return false;
return true;
}
function parseHitSearchPage(theResult,theNumber,searchWhere) {
var theData = null, searchArea = null, jsonReceived = (theResult.responseHeaders.indexOf("application/json") != -1) ? true : false;
var hitInfo = (theNumber>0) ? gMainData.hitCollection[theNumber] : null, hitData = (hitInfo) ? hitInfo.data : null, finalUrl = theResult.finalUrl;
var parser = new DOMParser(), xmlDoc = (!jsonReceived) ? parser.parseFromString(theResult.responseText,"text/html") : null;
searchArea = (searchWhere=="mturk") ? $("#JRSavedMturkArea1") : $("#JRSavedJobsArea1");
if (!jsonReceived) {
var errorTitle_Array = xmlDoc.getElementsByClassName("error_title"), 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", finalUrl );
parser = null; xmlDoc = null; errorTitle_Array = null; errorTitle = null; searchArea = null;
return;
} else if (errorTitle && errorTitle.innerHTML.indexOf("Your search did not match any HITs") != -1) {
if (theNumber<=0) {
$(searchArea).find(".searchingResultsArea").empty();
$(searchArea).find(".searchingResultsArea").append(createDiv("Nothing Found! Sorry.").css({"font-size":"25px","margin-top":"200px","text-align":"center"}));
gSavedSearchArea = "";
}
parser = null; xmlDoc = null; errorTitle_Array = null; errorTitle = null; searchArea = null;
return;
}
} else { theData = theResult.response; }
if (theData && "error" in theData) { processResults( theNumber, "TOOFAST", finalUrl ); return; }
var requestersInfo = doResultsJSON(theData), goUrl = "";
if (requestersInfo.length > 0) {
if (gMainOptions.debugger>1) console.log("JR HitsearchPage : I found some hits: " + requestersInfo.length); // debugger >1 for SearchPage details
if (theNumber<=0) {
$(searchArea).find(".searchingResultsArea").empty();
var captions = {"requesterName":"Requester Name","title":"Hit Title","duration":"Time","hitsAvailable":"# Hits","pay":"Pay","collect":"caption"};
var dialogWidth = $("#JRjqModalDialog-Search").width();
$(searchArea).find(".searchingResultsArea").append(createHitRow(captions,false,dialogWidth,450,searchWhere));
$(searchArea).find(".searchingResultsArea").append(createDiv()
.css({"margin-left":"5px","margin-top":"0px","background-color":"black","height":"6px","width":(dialogWidth - 145) + "px"}));
for (var ii=0, len1=requestersInfo.length; ii0) ? tempPrevDiv[0].firstElementChild.dataset.reactProps : null, url1 = firstForm.action;
if (reactInfo) {
reactInfo = JSON.parse(reactInfo).modalOptions;
var contactRequesterUrl = reactInfo.contactRequesterUrl, contactVar = (contactRequesterUrl.indexOf("requester_id") != -1) ? "requester_id%5D=" : "requesterId=";
jobData.hitsAvailable = reactInfo.assignableHitsCount; jobData.requesterName = reactInfo.requesterName;
jobData.groupId = url1.split("/projects/")[1].split("/")[0];
jobData.hitId = "" + url1.split("/tasks/")[1].split("?")[0];
jobData.assignmentId = url1.split("assignment_id=")[1].split("&")[0];
jobData.continueURL = url1.replace("&ref=w_wp_rtrn_top","&from_queue=true"); jobData.returnURL = "";
var tempContact = contactRequesterUrl.split(contactVar); if (tempContact.length) jobData.requesterId = contactRequesterUrl.split(contactVar)[1].split("&")[0];
jobData.totalSeconds = reactInfo.assignmentDurationInSeconds; jobData.timeData = convertSecondsToTimeData(jobData.totalSeconds); jobData.title = reactInfo.projectTitle;
jobData.timeLeft = convertToTimeString(jobData.timeData); jobData.pay = parseFloat(reactInfo.monetaryReward.amountInDollars).toFixed(2);
jobData.duration = jobData.timeLeft;
}
return jobData;
}
function checkUpdateData(theNumber,requestersInfo) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, updated = false;
if (hitData.title != requestersInfo.title) { hitData.title = requestersInfo.title; updated=true; }
if (hitData.duration != requestersInfo.duration) { hitData.duration = requestersInfo.duration; updated=true; }
if (hitData.requesterName != requestersInfo.requesterName) { hitData.requesterName = requestersInfo.requesterName; updated=true; }
if (hitData.pay != requestersInfo.pay) { hitData.pay = requestersInfo.pay; updated=true; }
hitInfo.hitId = requestersInfo.hitId; hitInfo.numberHits = requestersInfo.hitsAvailable;
if (updated) gDelayedSave = true;
}
function parseMturkHitPage(theResult,theNumber) {
var hitInfo = gMainData.hitCollection[theNumber], parser = new DOMParser(), finalUrl = theResult.finalUrl, mturkLimit = false;
var htmlDoc = parser.parseFromString(theResult.responseText,"text/html"), errorTitle = htmlDoc.getElementsByClassName("error_title")[0];
if (htmlDoc.getElementsByClassName("error-page").length) errorTitle = htmlDoc.getElementsByClassName("error-page")[0];
if (errorTitle && errorTitle.innerHTML.indexOf("You have exceeded the") != -1) {
processResults( theNumber, "TOOFAST", finalUrl );
parser = null; htmlDoc = null; errorTitle = null; return;
}
var colxspush1 = htmlDoc.getElementsByClassName("col-xs-push-1"), hitGroupsPage = htmlDoc.getElementsByClassName("result-count-info"), newAlerts = [];
var loggedOff = (finalUrl.indexOf("www.amazon.com/ap/signin") != -1), backSearchLink = htmlDoc.getElementsByClassName("back-to-search-link");
if (loggedOff) { processResults( theNumber, "LOGGEDOFF", finalUrl ); parser = null; htmlDoc = null; return; }
if (colxspush1.length) {
if ( colxspush1[0].innerHTML.indexOf("You must upgrade your browser to continue.") != -1 ) newAlerts = colxspush1[1].querySelectorAll("div");
else newAlerts = colxspush1[0].querySelectorAll("div");
}
var projectDetailBar = htmlDoc.getElementsByClassName("project-detail-bar"), requestersInfo = {}, updated = false;
if (htmlDoc.getElementById("alertboxHeader") || htmlDoc.getElementById("alertBox") || (newAlerts.length && projectDetailBar.length===0) ) {
var alertHeaderHTML = "";
if (htmlDoc.getElementById("alertboxHeader")) alertHeaderHTML = htmlDoc.getElementById("alertboxHeader").innerHTML;
else if (htmlDoc.getElementById("alertBox")) alertHeaderHTML = htmlDoc.getElementById("alertBox").innerHTML;
else alertHeaderHTML = parseNewHitPageWarning(newAlerts);
mturkLimit = (alertHeaderHTML.indexOf("Come back tomorrow to continue") != -1) || (alertHeaderHTML.indexOf("You cannot work on any more HITs today") != -1);
if (!mturkLimit && alertHeaderHTML.indexOf("There are no") != -1) {
processResults( theNumber, "NOMORE", finalUrl ); parser = null; htmlDoc = null; errorTitle = null; return;
} else if (alertHeaderHTML.indexOf("has chosen to prevent you from working on any of this Requester") != -1) {
processResults( theNumber, "BLOCKED", finalUrl ); parser = null; htmlDoc = null; errorTitle = null; return;
} else if (alertHeaderHTML.indexOf("You have too many HITs already") != -1 || alertHeaderHTML.indexOf("Your Task Queue is full") != -1 ||
alertHeaderHTML.indexOf("You have accepted the maximum number") != -1) {
processResults( theNumber, "QUEUEMAX", finalUrl ); parser = null; htmlDoc = null; errorTitle = null; return;
} else if (alertHeaderHTML.indexOf("You have already accepted this HIT") != -1) {
processResults( theNumber, "ALREADYACCEPT", finalUrl ); parser = null; htmlDoc = null; errorTitle = null; return;
} else if (alertHeaderHTML.indexOf("The HIT you were viewing could not be accepted") != -1) {
processResults( theNumber, "NOACCEPT", finalUrl ); parser = null; htmlDoc = null; errorTitle = null; return;
} else if (alertHeaderHTML.indexOf("You are not qualified to accept") != -1 || alertHeaderHTML.indexOf("Your Qualifications do not meet the") != -1 ||
alertHeaderHTML.indexOf("The Project has required Qualifications") != -1 || alertHeaderHTML.indexOf("This HIT requires Qualifications") != -1) {
processResults( theNumber, "NOTQUALIFIED", finalUrl ); parser = null; htmlDoc = null; errorTitle = null; return;
} else if (alertHeaderHTML.indexOf("No HITs match your criteria") != -1) {
hitGroupsPage = ["none found"];
}
}
hitInfo.status.notQual = 0; hitInfo.status.blocked = 0;
if (htmlDoc.querySelector('img[src^="https://opfcaptcha-prod.s3.amazonaws.com/"]')) {
gMainData.captchaCounter=0;
if (!gMainOptions.disableCaptchaAlert) {
var pandaLink = hitInfo.pandaNewUrl;
var addText = createDiv("Found a captcha when trying to get " + hitInfo.data.requesterName + " Pausing script.")
.css({"margin-top":"30px","line-height":"20px","font-size":"18px","text-align":"center"})
.append(createDiv(createLink("Try panda link to fill in panda.",pandaLink,"_blank",pandaLink)
.click( function(e) {
gJRPOP = window.open($(e.target).attr("href"),"_blank","width=" + 1200 + ",height=" + 900 + ",scrollbars=yes,toolbar=yes,menubar=yes,location=yes");
return false;
})).css({"margin-top":"15px"}));
showWaitDialog("Captcha Alert!!","",function() {
theCycler.unpause();
$("#JRPauseButton").html("Pause").css({"background-color":"ivory","color":"black"});
},null,addText,true);
if (!theCycler.isPaused()) {
theCycler.pause();
$("#JRPauseButton").html("Resume").css({"background-color":"red","color":"white"});
if (gNotifications) showNotification( "ALERT: Captcha ALERT!", "Just found a captcha so you better go fill it in as soon as possible!",
"captcha", "3ALERT3", true);
if (!gSoundOptions.hasToPause.mute) playThisSound("hasToPause");
else if (gSoundOptions.hasToPause.tts) speakThisNow("Found a captcha! Paused.");
}
}
parser = null; htmlDoc = null; return;
}
var hitAccepted = $(htmlDoc).find("button:contains('Return')"), notAccepted = $(htmlDoc).find("button:contains('Skip')"), hitData = hitInfo.data;
if (errorTitle && errorTitle.innerHTML.indexOf("Your request was not completed successfully") != -1) {
processResults( theNumber, "NOTCOMPLETED", finalUrl );
} else if (mturkLimit) {
processResults( theNumber, "DAILYLIMIT", finalUrl );
} else if (hitAccepted.length && projectDetailBar.length) {
requestersInfo = parseNewHitPageRequesters(htmlDoc); checkUpdateData(theNumber,requestersInfo);
processResults( theNumber, "ACCEPTED", finalUrl, requestersInfo );
if (gMainOptions.debugger>1) console.log("accepted: " + theNumber + " | updated: " + updated + " | groupId: " + hitData.groupId); // debugger >1 for accepting stats
} else if (notAccepted.length) {
var formData = {};
formData.hitId = htmlDoc.getElementsByName("hitId")[0].value; formData.prevHitSubmitted = htmlDoc.getElementsByName("prevHitSubmitted")[0].value;
formData.prevRequester = htmlDoc.getElementsByName("prevRequester")[0].value; formData.requesterId = htmlDoc.getElementsByName("requesterId")[0].value;
formData.prevReward = htmlDoc.getElementsByName("prevReward")[0].value; formData.groupId = htmlDoc.getElementsByName("groupId")[0].value;
formData.signature = htmlDoc.getElementsByName("signature")[0].value;
var iframeSrc = $(htmlDoc).find("iframe").attr("src"), acceptHitURL = acceptNewLink(formData), useAcceptHit = false;
if (iframeSrc && formData.requesterId=="AGVV5AWLJY7H2") {
if (hitData.filterMode>0 && hitData.filterMode <= Object.keys(gZingFuncOptions).length) {
requestUrl(iframeSrc, theNumber, gZingFuncOptions[hitData.filterMode].functionName, errorRequest, formData);
} else { useAcceptHit = true;}
}
if (hitData.action.toLowerCase().indexOf("pantha")!=-1 || useAcceptHit) {
if (gMainOptions.fastPantha) requestUrl(acceptHitURL,theNumber,parseMturkHitPage, errorRequest);
else { hitInfo.goToUrl.push({"url":acceptHitURL,"theNumber":theNumber}); theCycler.frontOfTheLine(theNumber); }
if ( hitInfo.ham == "paused" ) toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff);
}
} else if (hitGroupsPage.length) { // got redirected to a display all hit group page for some reason.
console.log("Hit Group Page came from Number: " + theNumber + " | finalurl: " + finalUrl);
} else if (backSearchLink.length) { // got redirected to a display all hit group page for some reason.
console.log("Hit Group Page came from Number: " + theNumber + " | finalurl: " + finalUrl);
} else { console.log("Unknown response: " + JSON.stringify(theResult.responseText)); processResults( theNumber, "ERROR", finalUrl ); }
parser = null; htmlDoc = null; hitAccepted = null; errorTitle = null; notAccepted = null;
}
function makeStatus() { return {"accepted":0,"skipped":0,"errors":0,"tooFast":0,"noHits":0,"fullQueue":0,"hitsStreak":0,"foundHits":0,
"noHitsStreak":0,"searched":0,"orphan":0,"hitsResults":0,"notQual":0,"missed":0,"blocked":0,"reachedLimit":false}; }
function makeCollection(pandaUrl,previewUrl,theNumber,theData,addStatus,filterFuncData,tabIndex,pandaNewUrl) { return {"collecting":"off","pandaUrl":pandaUrl,
"previewUrl":previewUrl,"goToUrl":[],"theNumber":theNumber,"data":theData,"status":(addStatus) ? makeStatus(): null,"specialOptions":null,"hitCell":null,
"ham":"off","minutes":0,"newTitle":"","numberHits":"0","once":false,"filterFuncData":filterFuncData,"searching":"off","lastAccept":null,"newHitsFound":false,
"tabIndex":tabIndex,"hitId":"","durationParsed":null,"dateDone":null,"elapsedSeconds":0,"pandaNewUrl":pandaNewUrl,"started":null};
}
function addHitCollection(theData,theNumber,tabIndex) {
var pandaNewUrl = pandaLinkNew(theData.groupId), pandaUrl = pandaLinkNew(theData.groupId), previewUrl = pandaLinkNew(theData.groupId);
var filterFuncData = (theData.action.toLowerCase().indexOf("filter") != -1) ? ((theData.requesterId=="AGVV5AWLJY7H2") ? gZingFuncOptions : null) : null;
gMainData.hitCollection[theNumber] = makeCollection(pandaUrl,previewUrl,theNumber,theData,true,filterFuncData,tabIndex,pandaNewUrl);
return theNumber;
}
function addQueueCheck() {
var searchUrl = "https://worker.mturk.com/tasks", acceptText = "";
function queueChecker(theResult) { displayMainStatus(); return parseQueuePage(theResult); }
function jobQueueChecker() {
gQueueCheckinProgress=true; gMainData.queueStatus.searched++;
requestUrl(searchUrl, 1, queueChecker, errorRequest, null, null, null, acceptText );
}
requestUrl(searchUrl, 1, queueChecker, errorRequest, null, null, null, acceptText );
theCycler.addJob( jobQueueChecker, -96, gMainOptions.queueTimer, false, 0);
}
function popupClosed() {
gJRPOP = null;
if ($("#JRWaitDialog").dialog('isOpen') === true) { $("div[aria-describedby='JRWaitDialog'] .ui-dialog-buttonpane button:contains('Unpause')").click(); }
}
function detectUnfocus() {
if (gMainOptions.unfocusWarning && !gMainOptions.unfocusDeThrottle) {
if ( (typeof document.hidden !== "undefined" && document.hidden) ||
(typeof document.mozHidden !== "undefined" && document.mozHidden && !gOnMac) ) {
if (!gScriptHidden) {
showNotification( "Panda Crazy not Focussed.", "Please put Panda Crazy in a window of it's own and not a tab or minimized so it works " +
"efficiently to grab hits as fast as possible. Thank you. This warning may be disabled in the options/general menu",
"NOTFOCUSED", "PC Alert", true );
if (!gNotifications || gMainOptions.disableNotifications) speakThisNow("Script needs to be in a window of it's own without tabs!");
else speakThisNow("Hey!");
}
gScriptHidden=true;
}
}
if (gMainOptions.unfocusDeThrottle) {
if (!gAudioCtx) gAudioCtx = new gAudioContext();
if (gAudioCtx.state === 'running') setupFixSound();
}
try { if (gJRPOP !== null && gJRPOP.closed) popupClosed(); } catch (e) { popupClosed(); }
}
function addExternalScriptCheck() {
function setStoreData() {
if (gQueueData) localStorage.setItem("JR_QUEUE_StoreData",JSON.stringify( {"date": Math.floor(new Date().getTime() / 1000), "ScriptID": gScriptID, "queue":gQueueData} ));
}
gExtInterval = setInterval( function() {
setStoreData(); detectUnfocus();
var sendQueue=null, sendPE=null, needQueue=false, sStr='JR_message_', eStr='_pandacrazy', numId=0;
if ((Object.keys(gExternalData)).length) {
for (var key in gExternalData) {
if (!gExternalData[key].gotPong) {
if (gExternalData[key].timeCount>20) {
numId = gExternalData[key].numId; gExternalData[key].timeCount=0; delete gExternalData[key];
localStorage.removeItem(sStr+'D_'+numId+eStr); localStorage.removeItem(sStr+'S_'+numId+eStr);
localStorage.removeItem(sStr+'pong_'+numId+eStr); localStorage.removeItem(sStr+'send_'+numId+eStr);
}
else gExternalData[key].timeCount++;
} else { gExternalData[key].gotPong=false; gExternalData[key].timeCount=0; }
}
if (needQueue || gSendQueue) { sendQueue=gQueueData; sendPE=gMainData.projectedEarnings; gSendQueue=false; }
sendPingMessage("",{"queue":sendQueue,"queueChanged":false,"PE":sendPE},null);
}
}, -92, 700, false, 0);
}
function startCollecting(theNumber,thisButton) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data; hitInfo.collecting = "on";
if (hitData.dailyLimit && hitData.dailyLimit>0) hitData.dailyDone = (gMturkDate == hitData.day) ? hitData.dailyDone : 0;
if (hitData.once) hitData.oneDone = 0; hitInfo.started = new Date();
theCycler.addJob( function( elapsed, theNumber ) {
var hitInfo = gMainData.hitCollection[theNumber], hitData = hitInfo.data, hitStatus = hitInfo.status, thisNewDate = new Date();
var newDateString = formatAMPM("onlydate",thisNewDate), hamElapsedSeconds = -1, accElapsedTime = -1; hitData.day = newDateString;
if (gRapidSuppress.counter>0) gRapidSuppress.counter--;
else { gRapidSuppress.jobNumber=-1; gRapidSuppress.counter=0; }
if (hitInfo.ham == "ontimed" || hitInfo.ham.substring(0,10) == "onFirstHam") {
if (gHamStart!==null) hamElapsedSeconds = (thisNewDate - gHamStart) / 1000;
if (hitInfo.lastAccept!==null) accElapsedTime = (thisNewDate - hitInfo.lastAccept) / 1000;
var offHamMode = (hitInfo.ham == "ontimed") ? "paused" : "off";
if (hitData.hamTimer > 0 && (hitInfo.lastAccept!==null || gHamStart!==null)) {
if ( (accElapsedTime >= hitData.hamTimer) || (hitInfo.ham.substring(0,10) == "onFirstHam" && hamElapsedSeconds >= 3) ) {
if (hitInfo.ham.substring(0,10) == "onFirstHam") { hitInfo.ham = hitInfo.ham.replace("onFirstHam",""); }
toggleButton($("#JRHamB_" + theNumber),hamOn,hamOff,offHamMode); hitInfo.lastAccept = null;
}
}
}
var checkJob = checkJobMode(theNumber);
if ( checkLimits(theNumber) && checkJob ) {
if (hitStatus.reachedLimit) {
hitStatus.reachedLimit = false; $("#JRCellNum_" + theNumber).stop(true,true);
$("#JRCellNum_" + theNumber).css({"background-color":$("#JRCellNum_" + theNumber).data("backgroundColor")});
} else $("#JRCellNum_" + theNumber).css({"background-color":$("#JRCellNum_" + theNumber).data("backgroundColor")});
var theUrl = "", hitDataAction = hitData.action.toLowerCase();
hitInfo.elapsedSeconds = (hitInfo.dateDone) ? (Math.round( ((thisNewDate - hitInfo.dateDone)/1000) * 10 ) / 10) : 0;
hitInfo.dateDone = thisNewDate; hitStatus.searched++;
if (hitDataAction.substring(0,6) == "search" && hitData.searchData===null) hitData.searchData = setSearchOptionsDefault();
var searchOptions = hitData.searchData.searchOptions, useSearch = (hitDataAction.substring(0,6) == "search") ? true : false;
var acceptText = (gNewSite) ? "application/json" : null;
if (hitInfo.goToUrl.length) {
useSearch = false;
if ( (hitDataAction.substring(0,6) == "search" || hitDataAction == "filterpanda" || hitDataAction == "pantha") && !hitInfo.hitCell.data("saveSearchGroupId") )
theUrl = (hitInfo.goToUrl.shift()).url;
else theUrl = (hitInfo.goToUrl[0]).url;
} else {
theUrl = ( hitDataAction == "panda" ) ? ( (gNewSite) ? hitInfo.pandaNewUrl : hitInfo.pandaUrl) :
(useSearch && gNewSite) ? requesterSearchNew(hitData.requesterId,searchOptions.minReward) : (gNewSite) ? hitInfo.pandaNewUrl : hitInfo.previewUrl;
}
gMainData.searched++;
gMainData.lastElapsed = elapsed;
if (gMainOptions.debugger>1) console.log("Doing Number: " + theNumber + " | going to: " + theUrl); // debugger >1 for doing details
if (useSearch) requestUrl(theUrl,theNumber,parseHitSearchPage, errorRequest, hitStatus.searched, null, "json", acceptText);
else requestUrl(theUrl,theNumber,parseMturkHitPage, errorRequest, hitStatus.searched);
if (gNewOldSite) requestUrl(hitInfo.pandaNewUrl,theNumber,parseMturkHitPage, errorRequest, hitStatus.searched); // gNewOldSite for both new and old site panda.
displayHitStatus(null,theNumber);
addToStatusLog(theNumber);
return true;
} else if (gScriptStatus == "normal" && checkJob) {
hitInfo.hitCell.stop(true,true);
hitInfo.hitCell.css({"background-color":"#FFA691"});
if (hitInfo.hitCell.data("status")=="off") {
hitInfo.hitCell.animate({"backgroundColor": hitInfo.hitCell.data("backgroundColor")}, 50000);
hitStatus.reachedLimit = false;
} else hitStatus.reachedLimit = true;
return false;
}
}, theNumber, 0, false, hitData.weight);
gMainData.jobs++;
}
function stopCollecting(theNumber,thisButton) {
if (gMainOptions.debugger>1) console.log("turning off " + theNumber); // debugger >1 for collecting info
if (gMainData.hitCollection[theNumber].collecting == "on") {
setTimeout( function() { if (!gMainData.hitCollection[theNumber] || gMainData.hitCollection[theNumber].collecting == "off") removeFromStatusLog(theNumber); },9000);
gMainData.hitCollection[theNumber].collecting = "off";
gMainData.hitCollection[theNumber].status.reachedLimit = false;
gMainData.hitCollection[theNumber].goToUrl.splice(0,gMainData.hitCollection[theNumber].goToUrl.length);
gMainData.hitCollection[theNumber].started = null;
$("#JRCellNum_" + theNumber).css({"background-color":$("#JRCellNum_" + theNumber).data("backgroundColor")});
theCycler.removeJob(theNumber);
gMainData.jobs--;
}
if (theNumber > 0) displayHitStatus(null,theNumber);
}
function stopAll() {
$.each(gMainData.hitCollection, function( index, value ) {
if (value.collecting == "on") {
toggleButton( $("#JRCollectB_" + index),startCollecting,stopCollecting);
if (value.collecting=="off" && value.ham != "off") toggleButtonOff($("#JRHamB_" + index),hamOn,hamOff);
}
});
localStorage.removeItem("JR_QUEUE_StoreData");
}
function hamOn(theNumber,thisButton) {
var onMode = "on", hitInfo = gMainData.hitCollection[theNumber]; gHamStart = new Date();
$(".JRHamButton").each( function() {
if ( $(this).data("theNumber") != theNumber ) { $(this).data("disabled",true); $(this).addClass("JRDisableButton"); }
updateHitColors($(this).data("theNumber"));
});
if (hitInfo.ham == "paused") { onMode = "ontimed"; if (hitInfo.data.hamTimer > 0) hitInfo.lastAccept = new Date(); }
hitInfo.ham = onMode; theCycler.hamOn(theNumber); theCycler.skippingReset(); theCycler.cycleResetChange(gMainOptions.HamCycleNumber);
}
function hamOff(theNumber,thisButton,theMode) {
var passedMode = theMode || "", hitInfo = gMainData.hitCollection[theNumber];
if (hitInfo.ham.substring(0,2) == "on") {
$(".JRHamButton").each( function() {
if ( $(this).data("disabled") ) { $(this).data("disabled",false); $(this).removeClass("JRDisableButton"); }
updateHitColors($(this).data("theNumber"));
});
cycleButtonSelect(gMainOptions.savedCycleNum);
theCycler.hamOff();
theCycler.skippingReset();
}
hitInfo.lastAccept = null; gHamStart = null;
if (passedMode === "" && hitInfo.ham == "ontimed" && hitInfo.collecting != "off") passedMode = "paused";
gMainData.hitCollection[theNumber].ham = (passedMode==="") ? "off" : passedMode;
saveGroupIdSearching(hitInfo,false);
}
function muteJob(theNumber) {
var hitInfo = gMainData.hitCollection[theNumber];
hitInfo.data.mute = !hitInfo.data.mute;
hitInfo.hitCell.data("mute",hitInfo.data.mute);
updateHitColors( theNumber );
saveSettings();
}
function helpToolTips() {
if (gMainOptions.showHelpTooltips) $(".hasHelptip").tooltip( "option", "disabled", false );
else $(".hasHelptip:not(.keepHelptip)").tooltip( "option", "disabled", true );
}
function addTab(tabContainer,tabContents,theTitle,isSortable,theID,tabData,appendClose,needBr) {
tabContents = tabContents || createDiv(); needBr = (typeof needBr != 'undefined') ? needBr : true;
var theTab = createTab(tabContainer,theTitle,isSortable,theID,tabData,appendClose,needBr).data({"tabData":tabData});
tabContents.data({"tabData":tabData}).attr({"class":"tabContents connectedSortable"}).css({"overflow":"auto"})
.droppable({ tolerance: 'pointer', drop: moveToTab })
.sortable({dropOnEmpty: true,delay:400,tolerance: "pointer","items":".JRHitCell:not(.ui-not-sortable)",
helper:"clone",opacity: 0.9,appendTo:"body",
start: function( event, ui ) {
ui.item.addClass('noclick'); ui.item.data("oldPosition",ui.item.index()); ui.item.data("sameTab",true);
},
stop: function( event, ui ) {
if (ui.item.data("hitInfo") && !ui.item.data("received")) {
var thePositions = gTabsData[ui.item.data("hitInfo").tabIndex].positions;
thePositions.splice(ui.item.index(), 0, thePositions.splice(ui.item.data("oldPosition"), 1)[0]);
saveSettings();
}
}
});
if (needBr) tabContents.insertBefore(theTab.find("br.cleartab")); else tabContents.appendTo(theTab);
return theTab;
}
function fillNewHitData(requesterName, requesterId, groupId, pay, title, duration, onlyOnce, toMain, collectNow, theAction, secondsOff, goHam) {
var active = (toMain) ? 0 : $( "#JRMainTabs" ).tabs( "option", "active" ); goHam = (typeof goHam != 'undefined') ? goHam : false;
var newHitData = jQuery.extend(true, {}, gDefaultRequestersData[0]); secondsOff = (typeof secondsOff != 'undefined') ? secondsOff : -1;
newHitData.action = (theAction) || "panda"; newHitData.qual = ""; newHitData.queueLimit = 0; newHitData.audioforce = ""; newHitData.hitlimit = ""; newHitData.mute = false;
newHitData.position = null; newHitData.tabNumber = gTabsData[active].tabNumber; newHitData.hamTimer = (gMainOptions.hamDelayTimer) || gDefaultMainOptions.hamDelayTimer;
newHitData.once = (onlyOnce) || false; newHitData.requesterName = (requesterName) || ""; newHitData.requesterId = (requesterId) || "";
newHitData.groupId = (groupId) ? groupId.trim() : ""; newHitData.searchData = setSearchOptionsDefault();
newHitData.dateAdded = new Date(); newHitData.secondsOff = parseInt(secondsOff); newHitData.pay = (pay) || "0.00";
newHitData.title = (title) ? title.trim() : groupId.trim(); newHitData.duration = (duration) || "";
var newCell = addHitData(newHitData,active);
if (collectNow) { newCell.data("status","on"); toggleButton( newCell.find(".JRCollectButton"),startCollecting,stopCollecting ); }
if (theCycler.isHamOn()) { newCell.find(".JRHamButton").data("disabled",true); newCell.find(".JRHamButton").addClass("JRDisableButton"); }
else if (goHam) {
toggleButton(newCell.find(".JRHamButton"),hamOn,hamOff); // turn on ham mode and it's already in first ham mode so it will turn off in 3 seconds.
newCell.data("hitInfo").ham = "onFirstHam" + newCell.data("hitInfo").ham;
}
updateHitCell(newCell.data("theNumber")); updateHitColors(newCell.data("theNumber"));
return newCell.data("theNumber");
}
function changeToEdited(idName) { $("#"+idName).data("edited",true); $("div[aria-describedby=" + idName+ "] .ui-dialog-buttonpane button:contains('Save')").button().show(); }
function inputNumMS(thisOne,isMS) {
if (isMS) $(thisOne).parent().find(".theInputEdit").val(convertToSeconds(parseInt(thisOne.value),3));
else $(thisOne).parent().find(".theInputEdit2").val(convertToMilliseconds(parseFloat(thisOne.value)));
}
function backToDefault(thisButton,inputClass,thisValue,doubleDigit) {
var idName = $(thisButton).data("idName"), editing = $("#"+idName).data("editing"), dataKey = $(thisButton).closest(".editLine").data("dataKey");
var theDefaultObject = (editing=="searchoptions") ? gDefaultSearchOptions : (editing=="job") ? gDefaultRequestersData[0] : (editing=="timers") ? gDefaultMainOptions :
(editing=="alarms") ? gAlarmSounds : (editing=="options") ? gDefaultMainOptions : null;
if (theDefaultObject && dataKey in theDefaultObject) {
var defaultValue = theDefaultObject[dataKey];
if (editing=="job" && dataKey=="requesterName") defaultValue="";
if (editing=="job" && dataKey=="requesterId") defaultValue="";
if (editing=="job" && dataKey=="action") defaultValue="panda";
if (editing=="job" && dataKey=="secondsOff") defaultValue=0;
if (thisValue) $(thisButton).html((doubleDigit) ? ("0" + defaultValue).slice(-2) : defaultValue);
else {
var thisArea = $(thisButton).closest(".editLine");
$(thisArea).find("."+inputClass+":first").val(defaultValue);
if ($(thisArea).data("seconds2ms")) $(thisArea).find(".theInputEdit2").val(convertToMilliseconds(parseFloat(defaultValue)));
}
changeToEdited(idName);
}
}
function dataEdited(idName,thisArea,theValue,extraValue) {
extraValue = extraValue || null;
var inputEdit1 = null, inputEdit2 = null, input1Label="", setValue=theValue;
if ( $(thisArea).find(".theInputEdit").length > 0 ) return;
changeToEdited(idName); $(thisArea).off("click");
if (extraValue=="minutes") setValue = (setValue>0) ? Math.round(setValue/60) : "0";
else if (extraValue && extraValue!="seconds") setValue = convertToSeconds(parseInt(theValue),3);
inputEdit1 = createTextInput(setValue).attr("class","theInputEdit").css({"width":"300px"});
if ($(thisArea).data("seconds2ms")) {
input1Label = " Seconds: ";
$(inputEdit1).css({"width":"50px"});
inputEdit2 = createTextInput(convertToMilliseconds(parseFloat(theValue))).attr("class","theInputEdit2").css({"width":"50px"});
}
var inputEditSpan = createSpan(input1Label).append(inputEdit1);
if (inputEdit2) inputEditSpan.append(createSpan(" Milliseconds: ")).append(inputEdit2);
if ($(thisArea).data("doClick")) $(inputEdit1).click( function(e) { $(thisArea).data("doClick")(e); });
if ($(thisArea).data("idToo")) {
var secondArea = $(thisArea).data("idToo"), secondKey = $("#"+secondArea).data("dataKey");
if (secondKey) {
var theNumber = $("#"+idName).data("theNumber"), secondValue = gMainData.hitCollection[theNumber].data[secondKey];
var secondInputEdit = createTextInput(secondValue).attr("class","theInputEdit").css({"width":"300px"});
var secondInputEditSpan = createSpan().append(secondInputEdit);
$(secondInputEdit).after($(createSpanButton(function(e) { backToDefault(e.target,"theInputEdit",false,false); },"","D",
gButtonOffBgColor,gButtonOffColor,"8px")).css({"margin-left":"5px"}).data("idName",idName));
$("#" + secondArea).find("span:not(.errorEditLine):not(.defaultEdit):not(.editButton)").replaceWith(secondInputEditSpan);
$("#" + secondArea).off("click");
}
}
$(inputEdit1).focus( function(e) {
if ($(e.target).closest(".editLine").data("doFocus") && !$(e.target).closest(".editLine").data("focusOff")) $(e.target).closest(".editLine").data("doFocus")(e);
$(e.target).select();
});
$(inputEdit1).after($(createSpanButton(function(e) { backToDefault(e.target,"theInputEdit",false,false); },"defaultButton","D",
gButtonOffBgColor,gButtonOffColor,"8px")).css({"margin-left":"5px"}).data("idName",idName));
if (inputEdit2) {
$(inputEdit2).focus( function(e) { $(e.target).select(); });
$(inputEdit1).on( "input", function() { if (this.value==="") { this.value=0; $(this).select(); } inputNumMS(this,false); });
$(inputEdit2).on( "input", function() { if (this.value==="") { this.value=0; $(this).select(); } inputNumMS(this,true); });
} else {
if ($(thisArea).closest(".editLine").data("doInput")) $(inputEdit1).on( "input", function() { $(this).closest(".editLine").data("doInput")(); });
}
$(thisArea).find("span:not(.errorEditLine):not(.defaultEdit):not(.optionButton)").replaceWith(inputEditSpan);
$(inputEdit1).focus();
}
function dataIncDecNumber(idName,currentNumber,limitNumber) {
var formatNumber = (limitNumber>9) ? ("0" + currentNumber).slice(-2) : currentNumber;
return createSpan().append($(createSpanButton( function(e) {
var limitNumber = $(e.target).data("limitNumber"), numberIncDec = $(e.target).parent().find(".numberIncDec"), theNumber = parseInt(numberIncDec.html());
theNumber = (theNumber>0) ? theNumber-1 : 0;
numberIncDec.html((limitNumber>9) ? ("0" + theNumber).slice(-2) : theNumber);
changeToEdited(idName);
},"","<",gButtonOffBgColor,gButtonOffColor,"9px")).data({"limitNumber":limitNumber}))
.append(createSpan(formatNumber.toString()).attr({"class":"numberIncDec nonselectable"}).data("idName",idName))
.dblclick( function(e) { backToDefault(e.target,"numberIncDec",true,(limitNumber>9)); } )
.append($(createSpanButton( function(e) {
var limitNumber = $(e.target).data("limitNumber"), numberIncDec = $(e.target).parent().find(".numberIncDec"), theNumber = parseInt(numberIncDec.html());
theNumber = (theNumber9) ? ("0" + theNumber).slice(-2) : theNumber);
changeToEdited(idName);
},"",">",gButtonOffBgColor,gButtonOffColor,"9px")).data({"limitNumber":limitNumber}));
}
function dataTrueFalse(idName,thisArea,theValue) {
changeToEdited(idName);
var newValue=false, theSpan = $(thisArea).closest("div").find("span");
if (theSpan.html()=="true") newValue=false; else newValue=true;
$(theSpan).html(newValue.toString());
}
function dataDropdownList(idName,thisArea,optionList,theValue,runThis) {
var dropdownList = createDropdownList("JRDropdown",optionList,"box-shadow: none; color:#000000;",runThis);
dropdownList.value = theValue; dropdownList.blur(); $("#" + idName).focus();
return dropdownList;
}
function dataRadioButtons(idName,theName,theValues,theValue,theChangeFunction) {
var radioButtons = createSpan().data("changeFunction",theChangeFunction);
$.each(theValues, function(index, value) {
var valueID = value.toLowerCase(), aRadio = createRadioButton(theName,valueID).attr({"id":valueID + "_radio_" + index}).css({"width":"20px"});
if (valueID == theValue) aRadio.prop("checked",true);
else aRadio.prop("checked",false);
createSpan().append(aRadio).append($("