/******************************************************************************
 * Upload progress bar functions.                                             *
 ******************************************************************************/

// is a progress update currently running?
var running = false;

/**
 * Show the progress bar for the given uploadId.
 */
function showProgress(uploadId)
{
  // Safari doesn't get it...
  if (navigator.userAgent.indexOf("AppleWebKit") != -1 &&
      navigator.userAgent.indexOf("Safari") != -1)
    return;

  // check all file inputs to only show the progress bar if files are actually
  // to be uploaded
  var elements = document.getElementById("editorForm");
  var fileGiven = false;
  for (i = 0; i < elements.length; i++)
    if (elements[i].type == "file" && elements[i].value)
    {
      fileGiven = true;
      break;
    }
  if (!fileGiven)
    return;

  document.getElementById("progressBar").style.display = "block";

  updateProgress(uploadId);
}

/**
 * Update the progress bar of the given uploadId. Updates percentage and bar
 * length.
 */
function updateProgress(uploadId)
{
  if (running)
    return;

  ajaxRequestFunc("meinsnautz/inserate/upload.ajax.html",
    function (response)
    {
      running = true;
      
      // a status array has been passed
      if (response)
      {
        var status = eval("(" + response + ")");
        var percentage = Math.round(status.current/status.total * 100);

        document.getElementById("prFile").innerHTML =
          status.done && status.total != status.current
          ? "Abbruch bei Datei <strong>" + status.filename + "</strong>"
          : "<strong>" + status.filename + "</strong> wird übertragen";

        // set the upload rate
        document.getElementById("rate").innerHTML =
          Math.round(status.rateK) + " kB/s";
      }
      // empty response
      else
        var percentage = 0;

      // update percentage and bar width
      document.getElementById("percentage").innerHTML = percentage + " %";
      document.getElementById("bar").style.width = percentage + "%";

      // refresh the progress bar every second
      if (!status || !status.done)
        setTimeout("updateProgress('" + uploadId + "');", 2000);

      running = false;
    },
    "uploadId=" + uploadId
  );
}
