// defaults
var phpbwmeter_lang = "en";
var phpbwmeter_progress_bar = 0;

// constants
var phpbwmeter_start = 0;
var phpbwmeter_in_progress = 1;
var phpbwmeter_finished = 2;
var phpbwmeter_error = 3;

var phpbwmeter_type_upload = 0;
var phpbwmeter_type_download = 1;

// different languages
var phpbwmeter_translations = new Array;
phpbwmeter_translations["en"] = new Array;
phpbwmeter_translations["en"]["wait"] = "Aguarde...";
phpbwmeter_translations["en"]["start"] = "Calculando...";
phpbwmeter_translations["en"]["error"] = "Error";

phpbwmeter_translations["pl"] = new Array;
phpbwmeter_translations["pl"]["wait"] = "Czeka...";
phpbwmeter_translations["pl"]["start"] = "Pomiar rozpoczety...";
phpbwmeter_translations["pl"]["error"] = "Blad";

// internal
var phpbwmeter_upload_id;
var phpbwmeter_download_id;
var phpbwmeter_progress;
var phpbwmeter_stops;
var phpbwmeter_down_time_start;
var phpbwmeter_up_time_start;
//var phpbwmeter_sugestao_id;

// requests. You may use them to access information about request progress
var phpbwmeter_down_request = new XMLHttpRequest();
var phpbwmeter_up_request = new XMLHttpRequest();

function phpbwmeter_bw(size, time) {
  // Convert number of bytes and number of seconds to kilobits per second.
  //
  // size: number of bytes
  // time: time in seconds
  Bps = size / time;
  kbps = Bps * 8 / 1000;
  kbps = Math.round (kbps);
  return kbps;
}

function phpbwmeter_upload(url, size, callback) {
  // Perform upload bandwidth measurement.
  //
  // url: URL of phpbwmeter.php file (may be relative)
  // size: number of bytes to upload during test, in kilo(1024)bytes
  // callback: function to call on events during test.
  //
  // Callback function takes 4 arguments:
  // type: will be set to phpbwmeter_type_upload
  // code: one of: phpbwmeter_{start,finished,error}
  // x, y: depend on code
  // 
  // Code phpbwmeter_start is used before we upload data, x and y are null.
  // Code phpbwmeter_finished is used when test was completed successfuly.
  //   x is number of bytes uploaded, y is time in seconds.
  // Code phpbwmeter_error is used to indicate HTTP error. x contains HTTP
  //   result code, y is null.
  var content = "12345678901234567890123456789012"; // 32 bytes
  var i = 0;
  for (i = 0; i < 5; i++) {
    content = content + content;
  } // 1024 bytes
  var kilobyte = content;
  for (i = 1; i < size; i++) {
    content = content + kilobyte;
  }
  phpbwmeter_up_request.open("POST", url, true);
  phpbwmeter_up_request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
  phpbwmeter_up_request.onreadystatechange = function() {
    var done = 4, ok = 200;
    if (phpbwmeter_up_request.readyState == done) {
      if (phpbwmeter_up_request.status == ok) {
              time = new Date();
              phpbwmeter_time_end = time.getTime();
             period = phpbwmeter_time_end
          - phpbwmeter_up_time_start;
              if (period == 0)
          period = .1;
        period = period / 1000;
        callback(phpbwmeter_type_upload,
            phpbwmeter_finished,
                   size * 1024 + 2,
             period);
      } else {
        callback(phpbwmeter_type_upload,
            phpbwmeter_error,
                   phpbwmeter_up_request.status,
             null);
      }
    }

  };

  callback(phpbwmeter_type_upload, phpbwmeter_start, null, null);
  time = new Date();
  phpbwmeter_up_time_start = time.getTime();
  phpbwmeter_up_request.send("v=" + content);

}

function phpbwmeter_download(url, size, callback) {
  // Perform download bandwidth measurement.
  //
  // url: URL of phpbwmeter.php file (may be relative)
  // size: number of bytes to download during test, in kilo(1024)bytes
  // callback: function to call on events during test.
  //
  // Callback function takes 4 arguments:
  // type: will be set to phpbwmeter_type_download
  // code: one of: phpbwmeter_{start,in_progress,finished,error}
  // x, y: depend on code
  // 
  // Code phpbwmeter_start is used when we send download request, x and y
  //    are null.
  // Code phpbwmeter_in_progress is used multiple times during download if
  //   progress reporting was enabled (phpbwmeter_enable_progress_bar()).
  //   x is percent of download completed, y is null.
  // Code phpbwmeter_finished is used when test was completed successfuly.
  //   x is number of bytes downloaded, y is time in seconds.
  // Code phpbwmeter_error is used to indicate HTTP error. x contains HTTP
  //   result code, y is null.
  phpbwmeter_progress = 0;
  phpbwmeter_stops = Math.round(size / 20);
  phpbwmeter_down_request.open("GET", url + "?datasize=" + size, true);
  phpbwmeter_down_request.setRequestHeader("Content-Type",
                           "application/x-www-form-urlencoded");
  phpbwmeter_down_request.onreadystatechange = function() {
    var done = 4, downloading = 3, ok = 200;
    if (phpbwmeter_down_request.readyState == done) {
      if (phpbwmeter_down_request.status == ok) {
        time = new Date();
        phpbwmeter_time_end = time.getTime();
        period = phpbwmeter_time_end
          - phpbwmeter_down_time_start;
        if (period == 0)
          period = .1;
        period = period / 1000;
        callback(phpbwmeter_type_download, phpbwmeter_finished,
            phpbwmeter_down_request.responseText.length, period);
      } else {
        callback(phpbwmeter_type_download, phpbwmeter_error,
            phpbwmeter_down_request.status, null);
      }
    } else if (phpbwmeter_down_request.readyState == downloading &&
         phpbwmeter_progress_bar) {
      phpbwmeter_progress++;
      if (phpbwmeter_progress % phpbwmeter_stops == 0) {
        callback(phpbwmeter_type_download, phpbwmeter_in_progress,
            Math.round(phpbwmeter_down_request.responseText.length 
              / (size * 1024) * 100), null);
      }
    }
  };
  
  callback(phpbwmeter_type_download, phpbwmeter_start, null, null);
  time = new Date();
  phpbwmeter_down_time_start = time.getTime();
  phpbwmeter_down_request.send(null);

}

function phpbwmeter_callback(type, code, x, y, z, w) {
  // Generic callback to be used with phpbwmeter_{upload,download}
  // Updates contents of HTML element with id equal to phpbwmeter_upload_id and
  // phpbwmeter_download_id for upload/download respectively.
  //
  // See phpbwmeter_{upload,download} comments for more information about
  // callback arguments.
  var element_id;
  if (type == phpbwmeter_type_upload)
    element_id = phpbwmeter_upload_id;
  else
    element_id = phpbwmeter_download_id;

  if (code == phpbwmeter_start) {
    document.getElementById(element_id).innerHTML = 
      phpbwmeter_translations[phpbwmeter_lang]["start"];
  } else if (code == phpbwmeter_in_progress) {
    document.getElementById(element_id).innerHTML =
      phpbwmeter_translations[phpbwmeter_lang]["start"] + " (" + x + "%)";
  } else if (code == phpbwmeter_error) {
    document.getElementById(element_id).innerHTML =
      phpbwmeter_translations[phpbwmeter_lang]["error"] + ": " + x;
  } else {
    document.getElementById(element_id).innerHTML =
	phpbwmeter_bw(x, y) + " kbps";
//      x + "B / " + y + "s = " + phpbwmeter_bw(x, y) + "kbps";

        if (parseInt(document.getElementById(phpbwmeter_download_id).innerHTML) >= 300)
        {
                document.getElementById(phpbwmeter_sugestao_id).innerHTML = "<font color=#333333 size=2>Para um teste mais preciso, de acordo com a velocidade da sua internet, recomendamos o <i><font color=FF0000><a href=index.php?modelo=2 class=tbc>medidor completo</a></i></font>.</font>";
        }else
        {
                document.getElementById(phpbwmeter_sugestao_id).innerHTML = "<font color=#333333 size=2>Para um teste mais preciso, de acordo com a velocidade da sua internet, recomendamos o <i><font color=FF0000><a href=index.php?modelo=1 class=tbc>medidor expresso</a></i></font>.</font>";

        }


  }
}

function phpbwmeter_set_lang(lang) {
  // Chooses set of strings to use in phpbwmeter_callback.
  // Consult list of available translations at the beginning of this file.
  phpbwmeter_lang = lang;
}

function phpbwmeter_enable_progress_bar() {
  // Enables progress reporting during download test.
  phpbwmeter_progress_bar = 1;
}

function phpbwmeter_run(url, size, upload_id, download_id, sugestao_id) {
  // Runs download and upload tests sequentially.
  //
  // url, size: like for phpbwmeter_{upload,download} functions
  // upload_id, download_id: id of HTML elements, which content will be updated
  //   to show test results.
  phpbwmeter_upload_id = upload_id;
  phpbwmeter_download_id = download_id;
  phpbwmeter_sugestao_id = sugestao_id;

  document.getElementById(upload_id).innerHTML =
    phpbwmeter_translations[phpbwmeter_lang]["wait"];
  document.getElementById(download_id).innerHTML =
    phpbwmeter_translations[phpbwmeter_lang]["wait"];

  document.getElementById(sugestao_id).innerHTML = "";

  phpbwmeter_download(url, size, function(a, b, c, d, e){
      phpbwmeter_callback(a, b, c, d, e);
      if (b == phpbwmeter_finished) {
        phpbwmeter_upload(url, size,
           phpbwmeter_callback);
      }

    });


}

