 interval = null;

function openProgressBar() {
 document.forms[0].style.visibility="hidden";
document.getElementById("load_bar").style.visibility="visible";
document.getElementById("big_title").innerHTML="Идет загрузка...";
 document.getElementById("load_bar").style.display="block"; 
 /* generate random progress-id */
 uuid = "";
 for (i = 0; i < 32; i++) {
  uuid += Math.floor(Math.random() * 16).toString(16);
 }
 /* patch the form-action tag to include the progress-id */
 document.getElementById("upload").action="/uploaded/index?X-Progress-ID=" + uuid;

 /* call the progress-updater every 1000ms */
 interval = window.setInterval(
   function () {
     fetch(uuid);
   },
   1000
 );
}

function fetch(uuid) {
 req = new XMLHttpRequest();
 req.open("GET", "/progress", 1);
 req.setRequestHeader("X-Progress-ID", uuid);
 req.onreadystatechange = function () {
  if (req.readyState == 4) {
   if (req.status == 200) {
    /* poor-man JSON parser */
    var upload = eval(req.responseText);
   // alert(req.responseText);
    
    if (!isNaN(upload.received))
    {	
      percent=roundNumber(100*upload.received / upload.size,0)+'%';
      document.getElementById('tp').innerHTML = upload.state+' '+percent;
    } 
     else document.getElementById('tp').innerHTML = upload.state+'complete';

    /* change the width if the inner progress-bar */
    if (upload.state == 'done' || upload.state == 'uploading') {
     bar = document.getElementById('progressbar');
     if (upload.received < upload.size)
     {
      w = 400 * upload.received / upload.size;
      bar.style.width = w + 'px';
     } 
     
     
    }
    /* we are done, stop the interval */
    if (upload.state == 'done') {
     window.clearTimeout(interval);
    }
   }
  }
 }
 req.send(null);
 
 
}


function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

