
function currentTime()
{
  d = new Date();
  return d.getTime()/1000 >> 0;
}

function dbClean(str)
{
  // cheap, dirty, and cruel way to prevent db issues
  // we should be extra careful with strings sent to the virtual table
  var pairs = [[" \"", ' &#8220;'],["'", '&#8217;'],["\"", '&#8221;']];
  for (var i=0;i<pairs.length;i++)
  {
    str = str.split(pairs[i][0]).join(pairs[i][1]);
  }
  return str;
}

// Convenient way to send a query and receive an array of objects
// It's stupid easy to loop through results this way, with 'dot' object syntax
function sqlToObj (sql, matches)
{
  var rs, error = false, eMessage;
  try
  {
    // never fully got the special 'matches' method to work
    // but left this part in here for inspiration...
    if (matches != null)
    {
      rs = db.execute(sql, matches);
    } else
    {
      rs = db.execute(sql);
    }
  } catch (ex)
  {
    error = true;
    eMessage = ex.message || ex.description || String(ex);
  }

  var i, cols, ret, row = 0;
  ret = [];
  if (!rs || error)
  {
    var errMessage = (eMessage || 'Unknown error');
    errMessage = "Error: "+errMessage;
    ret[0] = {
      error : true,
      errorMessage : errMessage
    };
  } else
  if (rs.isValidRow())
  {
    cols = rs.fieldCount();
    while (rs.isValidRow())
    {
      ret[row] = new Object();
      for (i = 0; i < cols; i++)
      {
        ret[row][rs.fieldName(i)] = rs.field(i);
      }
      rs.next();
      row++;
    }
    rs.close();
  }
  return ret;
}

// this wouldn't be difficult to modify to change the date format globally
// it's only used in one place, but oh well
function formatDate (ep)
{
  var myDate, strDate = '';
  myDate = new Date();
  myDate.setTime(parseInt(ep)*1000);
  strDate += myDate.getFullYear() + "-";
  strDate += myDate.getMonth()<9 ? "0" + String(myDate.getMonth()+1) : myDate.getMonth()+1;
  strDate += "-";
  strDate += myDate.getDate()<9 ? "0" + String(myDate.getDate()+1) : myDate.getDate()+1;
  strDate += " " + myDate.getHours() + ":";
  strDate += myDate.getMinutes()<10 ? "0" + String(myDate.getMinutes()) : myDate.getMinutes();
  return strDate;
}

function escapeHtml(s)
{
  return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
}

/// JSON
diggRequest = function(params)
{
  var uri = '../proxy.php5';
  jsoning = true;
  $.getJSON(uri, params, function(json)
  {
    jsoning = false;
    diggRequestComplete (json);
  });
};

diggRequestComplete = function ()
{
  // nothing
}

var lastWorkerCount = 0, workerPauseTime = 0;
function updateStatus ()
{
  var strAction = "", strStatus = "", q, obj, intRegisteredDiggs = 0, intIndexedStories = 0;
  divStatus = document.getElementById("status");
  divStatus.style.display = "";
  // not really using strAction.. but it was handy for debugging
  // users probably wouldn't mind knowing what type of action the tool is in the middle of
  if (jsoning)
  {
    // on the phone
    strAction = "I'm on the phone.";
  } else
  if (workerTasks > 0)
  {
    // moving stuff around
    strAction = "Busy, busy, busy.";
  } else
  if (callQueue.length > 0)
  {
    // still have more stuff to retrieve..
    strAction = "Still have more to do";
  } else
  {
    // am i done?
    divStatus.style.display = "none";
    strAction = "Waiting.";
  }
  q = "SELECT count(*) as mycount FROM diggs WHERE userid = " + currentUserId;
  obj = sqlToObj(q);
  if (obj.length > 0)
  {
    intRegisteredDiggs = obj[0].mycount;
  }
  q = "SELECT count(*) as mycount FROM diggs JOIN storydata ON diggs.storyid = storydata.id WHERE userid = " + currentUserId + " AND title <> ''";
  obj = sqlToObj(q);
  if (obj.length > 0)
  {
    intIndexedStories = obj[0].mycount;
  }
  strStatus = "Diggs Registered: " + intRegisteredDiggs +
    "<br />Stories Indexed: " + intIndexedStories + 
    "<br />Total Stories Dugg: " + myTotalDiggs + 
    "<br />Currently: " + strAction;
  if (myTotalDiggs>=1)
  {
    // nothing
  } else
  {
    intRegisteredDiggs = intIndexedStories = 0;
    myTotalDiggs = .9;
  }
  document.getElementById("registeredDiggs").style.width = Math.floor((intRegisteredDiggs/myTotalDiggs)*150) + "px";
  document.getElementById("indexedStories").style.width = Math.floor((intIndexedStories/myTotalDiggs)*150) + "px";
  if (lastWorkerCount == workerTasks && workerTasks > 0)
  {
    workerPauseTime++;
    if (workerPauseTime > 20)
    {
      console.log("Reset workerTasks! "+workerTasks);
      workerTasks = 0;
    }
  } else
  {
    workerPauseTime = 0;
  }
  lastWorkerCount = workerTasks;
}

