/*
	verze: 08.08.26
*/
var delay = new Array();
var url = new Array();
var img = new Array();
var count = new Array();
var stat_time = new Array();
var watchdogHandler = new Array();
var repaintHandler = new Array();
infoElement = new Array();

function startRefresh(ref, new_delay, infoEl)
{
    delay[ref.id] = new_delay;
    url[ref.id] = ref.src;
    img[ref.id] = new Image();
    count[ref.id] = 0;
    stat_time[ref.id] = 0;
    infoElement[ref.id] = infoEl;
	document.getElementById(ref.id).onload = function() { preload(ref.id); }
	//zavolat nacteni obrazku
    preload(ref.id);
}

function stopRefresh(ref)
{
	try { clearInterval(watchdogHandler[ref.id]);        } catch (error) {}
	try { clearInterval(repaintHandler[ref.id]);         } catch (error) {}
	try { img[ref.id].onLoad = null;                     } catch (error) {}
	try { document.getElementById(ref.id).onload = null; } catch (error) {}
}

/*******************************************************/

/** Funkce se automaticky zavole v pripade zaseknuti obnovovani
 *  Soucast watchdogu
 */
function reset(id)
{
    var d = new Date();
	// v pripade zakousnuti znova nacte obrazek
	preload(id);
}

/** Posila informaci watchdogu, ze je vse v poradku
 */
function setWatchDog(id)
{
    clearInterval(watchdogHandler[id]);
	watchdogHandler[id] = setInterval("reset('"+id+"')", 8000+delay[id]*2);
}

/** Zameni nove nacteny obrazek za stary
 *  Obcazek musi byt nejdriv jinou funkci nacten do cache
 */
function repaintNow(id)
{
	count[id]++;

	setWatchDog(id);
	if (infoElement[id])
	{
		var dateNow = new Date();
	    if (stat_time[id])
	    {
		    var prodleva = dateNow - stat_time[id].getTime();
		    if (prodleva > 0)
   				document.getElementById(infoElement[id]).innerHTML = (1000 / prodleva).toFixed(1) + ' fps, snímek č. ' + count[id];
		}
		stat_time[id] = dateNow;
	}
    if (img[id].src)
    {
		document.getElementById(id).src = img[id].src;
	}
}

/** Po nacteni obrazku do cache funkce rozhodne, zda zobrazit obrazek okamzite a nebo s prodlenim
 */
function delayedRepaint(id)
{
	setWatchDog(id);
	if (delay[id] >= 50)
		repaintHandler[id] = setTimeout("repaintNow('"+id+"')",delay[id]);
	else
		repaintNow(id);
}

/** Nacteni obrazku do cache
 */
function preload(id)
{
	setWatchDog(id);
	if (url[id].indexOf("?") == -1)
		img[id].src = url[id] + "?count=" + count[id]++;
	else
		img[id].src = url[id] + "&count=" + count[id]++;

	img[id].onLoad = delayedRepaint(id);
}

