/* global _, Promise, elements, getNow, minToMs, loadScript */
/* global taskInfo, ticketsInfo, dbRef, taskData */
/* global setImgCounters, removeLoader, makeInstructionsList, makeImgRow, ImgTrinary */

// stub db helpers
var stub_db = {
  isTicketInReqAndNotExpired: function (ticket) {
    for (var reqTicketUID in taskData.taskTicketsReq) {
      var reqTicket = taskData.taskTicketsReq[reqTicketUID];
      var poolTicket = taskData.taskTicketsPool[reqTicket[ticketsInfo.ticketsPool_uid]];
      if ((poolTicket.uid === ticket.uid) && (!this.isReqTicketExpired(reqTicket))) return true;
    }
    return false;
  },
  isTicketInRes: function (ticket) {
    for (var resTicketUID in taskData.taskTicketsRes) {
      var resTicket = taskData.taskTicketsRes[resTicketUID];
      var reqTicket = taskData.taskTicketsReq[resTicket[ticketsInfo.ticketsReq_uid]];
      var poolTicket = taskData.taskTicketsPool[reqTicket[ticketsInfo.ticketsPool_uid]];
      if (poolTicket.uid === ticket.uid) return true;
    }
    return false;
  },
  isReqTicketExpired: function (reqTicket) {
    return (getNow() - reqTicket.timeSubmitted) > reqTicket.taskDuration; // TODO create these keys, normalize taskDuration and reference it back from jobs bucket
  },
  remainsOpen: function (poolTicket) {
    if (this.isTicketInRes(poolTicket) || (this.isTicketInReqAndNotExpired(poolTicket))) return false;
    else return true;
  },
  // retrieve up to n open tickets
  getTickets: function (taskName, maxCount) {
    var ticketsToServe = [];
    for (var poolTicketUID in taskData.taskTicketsPool) {
      var poolTicket = taskData.taskTicketsPool[poolTicketUID];
      if (ticketsToServe.length === maxCount) break;
      if (this.remainsOpen(poolTicket)) {
        ticketsToServe.push(dbRef.taskTicketsReq.push(poolTicket)
        .then(function (pushedReqTicketRef) {
          this[ticketsInfo.ticketsPool_uid] = this.uid;
          this.uid = pushedReqTicketRef.path.u[1];
          this.timeSubmitted = getNow();
          this.taskDuration = minToMs(taskInfo.taskDuration); // TODO add this via reference to job entry?
          delete this.img_ref_uid;

          var pushObj = {};
          pushObj[ticketsInfo.ticketsPool_uid] = this[ticketsInfo.ticketsPool_uid];
          pushObj.uid = this.uid;
          pushObj.timeSubmitted = this.timeSubmitted;
          pushObj.taskDuration = this.taskDuration;
          pushedReqTicketRef.set(pushObj);

          return this;
        }.bind(_.deepClone(poolTicket)))
        .catch(function (err) {
          throw err;
        }));
      }
    }
    taskInfo.ticketsReceived = ticketsToServe.length;
    return Promise.all(ticketsToServe);
  },
  getImage: function (reqTicket) {
    var ticketsPoolKey = reqTicket[ticketsInfo.ticketsPool_uid];
    var ticketsPoolTask = taskData.taskTicketsPool[ticketsPoolKey];
    var gottenImg = taskData.imgTickets[ticketsPoolTask.img_ref_uid];
    return gottenImg;
  },
  pushAndAddUID: function (targetRef, sourceObj) {
    var item = sourceObj;
    targetRef.push(item)
      .then(function (tempRef) {
        item.uid = tempRef.path.u[1];
        return tempRef.update({uid: item.uid});
      })
      .then(function () {
        console.log('item at ' + targetRef.path.u[0] + '/' + item.uid + 'updated');
      })
      .catch(function (err) { throw (err); });
  },
};

var loadClasses = function (callback) {
  loadScript('./classes/instructionsList.js', function () {
    elements.instructionsArea.appendChild(makeInstructionsList([
      'Does each of the <span class="img_counter"></span> photos below contain the named concept?'
    ], 'li'));
    loadScript('./classes/imgTrinary.js', function () {
      loadScript('./classes/imgRow.js', function () {
        callback();
      });
    });
  });
};

loadClasses(function () {
  // query db for next 30 images (server will determine these but for now on client-side)
  stub_db.getTickets(taskInfo.taskName, taskInfo.ticketsToGet)
    .then(function(reqTickets) {
    // iterate over server response
      // console.log('succeeded to get', reqTickets.length, 'of', taskInfo.ticketsToGet, 'tickets requested for task', taskInfo.taskName);
      // console.log(reqTickets);
      // instantiate imgTrinary class per image
      removeLoader();
      reqTickets.map(function(reqTicket, i){
        if (i % 3 === 0) elements.mediaArea.appendChild(makeImgRow());
        var newImgTrinary = new ImgTrinary(stub_db.getImage(reqTicket), reqTicket, i);
        elements.resTicketItems.push(newImgTrinary);
        elements.mediaArea.lastElementChild.appendChild(newImgTrinary.trinaryContainer);
      // event listeners on trinary
        // add response and other metadata (worker id, img_ref) to flat output obj based on trinary state change
        // enable submitBtn if all images completed
      });   
      setImgCounters();
    })
    .catch(function(err) {
      console.log('failed to get tickets for task');
      throw err;
    });
    
  // event listener on submitBtn for click
    // iterate over results obj
      // push to img_sanitizer_task_worker_res  
});

var isTaskComplete = function () {
  // return !$j('input[name=""')
};
@@ -201,3158 +201,8 @@
 */%0A%0A
-// stub db helpers%0Avar stub_db = %7B%0A  isTicketInReqAndNotExpired: function (ticket) %7B%0A    for (var reqTicketUID in taskData.taskTicketsReq) %7B%0A      var reqTicket = taskData.taskTicketsReq%5BreqTicketUID%5D;%0A      var poolTicket = taskData.taskTicketsPool%5BreqTicket%5BticketsInfo.ticketsPool_uid%5D%5D;%0A      if ((poolTicket.uid === ticket.uid) && (!this.isReqTicketExpired(reqTicket))) return true;%0A    %7D%0A    return false;%0A  %7D,%0A  isTicketInRes: function (ticket) %7B%0A    for (var resTicketUID in taskData.taskTicketsRes) %7B%0A      var resTicket = taskData.taskTicketsRes%5BresTicketUID%5D;%0A      var reqTicket = taskData.taskTicketsReq%5BresTicket%5BticketsInfo.ticketsReq_uid%5D%5D;%0A      var poolTicket = taskData.taskTicketsPool%5BreqTicket%5BticketsInfo.ticketsPool_uid%5D%5D;%0A      if (poolTicket.uid === ticket.uid) return true;%0A    %7D%0A    return false;%0A  %7D,%0A  isReqTicketExpired: function (reqTicket) %7B%0A    return (getNow() - reqTicket.timeSubmitted) %3E reqTicket.taskDuration; // TODO create these keys, normalize taskDuration and reference it back from jobs bucket%0A  %7D,%0A  remainsOpen: function (poolTicket) %7B%0A    if (this.isTicketInRes(poolTicket) %7C%7C (this.isTicketInReqAndNotExpired(poolTicket))) return false;%0A    else return true;%0A  %7D,%0A  // retrieve up to n open tickets%0A  getTickets: function (taskName, maxCount) %7B%0A    var ticketsToServe = %5B%5D;%0A    for (var poolTicketUID in taskData.taskTicketsPool) %7B%0A      var poolTicket = taskData.taskTicketsPool%5BpoolTicketUID%5D;%0A      if (ticketsToServe.length === maxCount) break;%0A      if (this.remainsOpen(poolTicket)) %7B%0A        ticketsToServe.push(dbRef.taskTicketsReq.push(poolTicket)%0A        .then(function (pushedReqTicketRef) %7B%0A          this%5BticketsInfo.ticketsPool_uid%5D = this.uid;%0A          this.uid = pushedReqTicketRef.path.u%5B1%5D;%0A          this.timeSubmitted = getNow();%0A          this.taskDuration = minToMs(taskInfo.taskDuration); // TODO add this via reference to job entry?%0A          delete this.img_ref_uid;%0A%0A          var pushObj = %7B%7D;%0A          pushObj%5BticketsInfo.ticketsPool_uid%5D = this%5BticketsInfo.ticketsPool_uid%5D;%0A          pushObj.uid = this.uid;%0A          pushObj.timeSubmitted = this.timeSubmitted;%0A          pushObj.taskDuration = this.taskDuration;%0A          pushedReqTicketRef.set(pushObj);%0A%0A          return this;%0A        %7D.bind(_.deepClone(poolTicket)))%0A        .catch(function (err) %7B%0A          throw err;%0A        %7D));%0A      %7D%0A    %7D%0A    taskInfo.ticketsReceived = ticketsToServe.length;%0A    return Promise.all(ticketsToServe);%0A  %7D,%0A  getImage: function (reqTicket) %7B%0A    var ticketsPoolKey = reqTicket%5BticketsInfo.ticketsPool_uid%5D;%0A    var ticketsPoolTask = taskData.taskTicketsPool%5BticketsPoolKey%5D;%0A    var gottenImg = taskData.imgTickets%5BticketsPoolTask.img_ref_uid%5D;%0A    return gottenImg;%0A  %7D,%0A  pushAndAddUID: function (targetRef, sourceObj) %7B%0A    var item = sourceObj;%0A    targetRef.push(item)%0A      .then(function (tempRef) %7B%0A        item.uid = tempRef.path.u%5B1%5D;%0A        return tempRef.update(%7Buid: item.uid%7D);%0A      %7D)%0A      .then(function () %7B%0A        console.log('item at ' + targetRef.path.u%5B0%5D + '/' + item.uid + 'updated');%0A      %7D)%0A      .catch(function (err) %7B throw (err); %7D);%0A  %7D,%0A%7D;%0A%0A
 var 
@@ -664,98 +664,8 @@
 ) %7B%0A
-  // query db for next 30 images (server will determine these but for now on client-side)%0A
   st

Clear file to prepare for using message server