// Define the hash of request counts
var keyupReqCounts = {};

/* EnqueueKeyupRequest
 * 
 * Enqueues a request to call a particular method. After 250ms CallIfValid() will check whether
 * the request is still valid (i.e. no further requests supercede it). If it is, the method will
 * be called.
 * Note: The requested method will be called with no parameters. If this is inadequate, these functions
 * should be enhanced to take an 'options' hash to ultimately be passed to the target method.
 */
function EnqueueKeyupRequest(method_to_call)
{
  if (keyupReqCounts[method_to_call] == null)
  {
    keyupReqCounts[method_to_call] = 0;
  }
  keyupReqCounts[method_to_call] = keyupReqCounts[method_to_call] + 1;
  setTimeout("CallIfValid('"+method_to_call+"', "+keyupReqCounts[method_to_call]+")", 250);
}

/* CallIfValid
 * 
 * Checks if a given request is valid. If it is, the method is executed and the request queue is
 * reset once the method has completed.
 */
function CallIfValid(method_to_call, request_id)
{
  if (IsRequestValid(method_to_call, request_id))
  {
    eval(method_to_call+"()");
    ResetKeyupRequestQueue(method_to_call);
  }
}

/* IsRequestValid
 * 
 * Checks whether a particular request is valid for a given target method. This is determined
 * by checking whether the given request id is the last request id to be created for that method.
 */
function IsRequestValid(method_to_call, request_id)
{
  return (keyupReqCounts[method_to_call] == request_id)
}

/* ResetKeyupRequestQueue
 * 
 * Resets the current request id for a given target method
 */
function ResetKeyupRequestQueue(method_to_call)
{
  keyupReqCounts[method_to_call] = 0;
}