var http = createRequestObject();
var c = 0;
var c2 = 0;
ID = setTimeout("sendRequest()",10);
ID2 = setTimeout("timer()",100);

function createRequestObject() 
{
	var xmlhttp;
	try 
	{ 
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
  catch(e) 
	{
    try 
		{ 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
    catch(f) 
		{ 
			xmlhttp=null; 
		}
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") 
	{
  	xmlhttp=new XMLHttpRequest();
  }
	return  xmlhttp;
}

function sendRequest() 
{
 	try
	{
		var d = new Date();
    var time = Math.round(d.getTime() / 1000);
    var userId = document.getElementById("userId").value;
    var testId = document.getElementById("testId").value;
		http.open('GET', 'ajax.php?time=' + time + '&userId=' + userId + '&testId=' + testId);
    http.onreadystatechange = handleResponse;
		http.send(null);
	}
	catch(e){}
	finally{}
	ID = setTimeout("sendRequest()",5000);
}


function handleResponse() 
{
	try
	{
    if ((http.readyState == 4)&&(http.status == 200))
		{
    	var response = parseInt(http.responseText);
			if (response<=0)
      {
      	// casovy limit vyprsal
				var d = new Date();
		    var time = Math.round(d.getTime() / 1000);
		    var oldQId = document.getElementById("oldQId").value;
		    var testId = document.getElementById("testId").value;
				clearTimeout(ID);
				document.getElementById('container').innerHTML = '<div>Časový limit vypršal. Pokračujte kliknutím na <a href="?site=evaluateTest&amp;testId='+testId+'&amp;oldQId='+oldQId+'&amp;time='+time+'">tento link</a>.</div>';
      }
      else
      {
				var d = new Date();
		    var time = Math.round(d.getTime() / 1000);
				//document.getElementById('totalTime').innerHTML = response;
				c = response + time;
      }
		}
  }
	catch(e){}
	finally{}
}

function formatTime(ts)
{
	ts = parseInt(ts);
	s = ts % 60;
	m = (Math.floor(ts / 60) % 60);
	h = Math.floor(ts / 3600);
	return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s);
}

function timer()
{
	var d = new Date();
  var time = Math.round(d.getTime() / 1000);
	if (c==0)
	{
		c = parseInt(document.getElementById("globTime").value) + time;
	}
	if (c2==0)
	{
		c2 = time - parseInt(document.getElementById("questionTime").value);
	}
	document.getElementById('totalTime').innerHTML = formatTime(c - time);
	document.getElementById('qTime').innerHTML = formatTime(time - c2);
	ID2 = setTimeout("timer()",1000);
}
