function storyChildInit()
{
  // this "Child" is a WorkerPool object and runs in a separate thread from the UI
  // need to make the db connection from this thread, since global objects are not shared
  db = google.gears.factory.create('beta.database', '1.0');
  db.open('diggoraclev1');
  gearsWorkerPool.onmessage = storyChildHandler;
}

function storyChildHandler(msg, sender)
{
  var q, exists, p1, p2;
  // p1 will either be "new" or "chg"
  p1 = msg.substr(0,3);
  p2 = msg.substr(4);
  gearsWorkerPool.sendMessage("start|"+msg, sender);
  if (p1 == "new")
  {
    q = "SELECT count(*) as mycount FROM storydata WHERE id = " + p2;
    exists = sqlToObj(q);
    if (exists[0].mycount == 0)
    {
      // set up blank fields and set cache to 0
      // seeing the 0 cache will tell the story updater to get the full text on it
      q = "INSERT INTO storydata (id, title, submit_date, link, href, description, promote_date, status, diggs, comments, submitter, topic, container, cache) ";
      q += "VALUES (" + p2 + ", '', 0, '', '', '', 0, '', 0, 0, 0, '', '', 0)";
      db.execute(q);
      // The fts2 virtual table can cause problems, so let's only touch it if we know this field doesn't exist
      q = "SELECT count(*) as mycount FROM storytext WHERE rowid = " + p2;
      var textexists = sqlToObj(q);
      if (textexists[0].mycount == 0)
      {
        q = "INSERT INTO storytext (rowid, title, description) ";
        q += "VALUES (" + p2 + ", '', '')";
        tmp = sqlToObj(q);
      }
    }
  } else
  if (p1 == "chg")
  {
    qArr = p2.split("checkAddUser(");
    if (qArr.length > 1)
    {
      id = checkAddUser(qArr[1].substring(0, qArr[1].indexOf(")")));
      p2 = qArr[0] + id + qArr[1].substring(qArr[1].indexOf(")")+1);
    }
    q = p2;
    tmp = sqlToObj(q);
  }
  gearsWorkerPool.sendMessage("end|"+msg, sender);
  gearsWorkerPool.sendMessage("done", sender);
}

function updateStories()
{
  var arrStoriesToUpdate, params;
  // gets up to 100 stories that have not been cached recently
  arrStoriesToUpdate = getStoriesToUpdate();
  if (arrStoriesToUpdate.length > 0)
  {
    strStoryIds = arrStoriesToUpdate.join(",");
    params = {
      endPoint : "/stories/"+strStoryIds,
      count : 100
    };
    diggRequestComplete = function (obj)
    {
      sqlToObj("UPDATE storydata SET cache = " + (currentTime() + 1000000) + " WHERE id IN ("+strStoryIds+")");
      var i;
      var s = obj.stories;
      if (!s.length>0)
      {
        s = [s];
      }
      for (i=0;i<s.length;i++)
      {
        // story has already been created in database with 'diggs' call
        // update blank fields with full story data
        promote = s[i].promote_date > 0 ? String(s[i].promote_date) : "0";
        q = "UPDATE storydata SET ";
        q += "title = '" + dbClean(s[i].title) + "', ";
        q += "submit_date = " + String(s[i].submit_date) + ", ";
        q += "link = '" + dbClean(s[i].link) + "', ";
        q += "href = '" + dbClean(s[i].href) + "', ";
        q += "description = '" + dbClean(s[i].description) + "', ";
        q += "promote_date = " + promote + ", ";
        q += "status = '" + dbClean(s[i].status) + "', ";
        q += "diggs = " + String(s[i].diggs) + ", ";
        q += "comments = " + String(s[i].comments) + ", ";
        // checkAddUser() can be expensive when running 100x in this loop
        // affects UI, so i should look into sending it to a Worker
        q += "submitter = checkAddUser(" + s[i].user.name + "), ";
        q += "topic = " + objTopics[s[i].topic.short_name].id + ", ";
        q += "container = " + objTopics[s[i].container.short_name].id + ", ";
        q += "cache = " + currentTime() + " ";
        q += "WHERE id = " + String(s[i].id);
        workerPool.sendMessage("chg:"+q, storyChildId);

        q = "UPDATE storytext SET ";
        q += "title = '" + dbClean(s[i].title) + "', ";
        q += "description = '" + dbClean(s[i].description) + "' ";
        q += "WHERE rowid = " + String(s[i].id);
        //console.log(q);
        workerPool.sendMessage("chg:"+q, storyChildId);
        workerTasks += 2;
      }
    }
    callQueue.push([updateStories,[]]);
    diggRequest(params);
  }
}

function getStoriesToUpdate ()
{
  var q, objStories, arrStories = [];
  q = "SELECT id FROM storydata " +
    "WHERE (submit_date > " + (currentTime() - (3600*48)) + " AND cache < " + (currentTime() - 3600) + ") " +
    "OR cache = 0 " +
    "ORDER BY cache, id LIMIT 100";
  objStories = sqlToObj(q);
  for (var i in objStories)
  {
    if (objStories[i].id != undefined)
    {
      arrStories.push(objStories[i].id);
    }
  }
  // returns array of stories that need to be updated
  return arrStories;
}
