var xmlhttp;
var retries = 0;
function stateChange ()
{
	if (xmlhttp.readyState == 4)
		{
		// 4 = "loaded"
		if (xmlhttp.status == 200)
			{
				// 200 = "OK"
				return true
			} else {
				// alert("Problem retrieving XML data");
				return false
			}
		}
	}
function refreshBanner ( linkId, imgId, grp, type )
	{
		var url = '/tuononews.nsf/RefreshObjURL?OpenAgent&GRP=' + grp + '&Type=' + type;
		var retStr;
		var BnrA = document.getElementById( linkId );
		var BnrI = document.getElementById( imgId );
		
		// se il conta tentativi è maggiore di 10, rinuncio e esco dalla function
		if ( retries > 10 ) {
			retries = 0;
			return false;
		}
		
		xmlhttp = null;
		
		if (window.XMLHttpRequest) {
			// code for all new browsers
 			xmlhttp = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			// code for IE5, IE6, etc.
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (xmlhttp != null) {
			xmlhttp.onreadystatechange = stateChange;
			xmlhttp.open("GET", url, false);
			xmlhttp.send(null);
			retStr = xmlhttp.responseText;
			
		} else {
			// alert("Your browser does not support XMLHTTP.");
			return false;
		}
		
		lista = retStr.split('~~~');
		
		if( lista[2] == '' ) {
			// si è verificato un problema e non ha restituito un indirizzo immagine valido, riprovo
			retries = retries +1;
			refreshBanner ( linkId, imgId, grp, type )
		} else if ( lista[2] == BnrI.src ) {
			// l'immagine restituita è LA STESSA attualmente visualizzata, quindi la cambio
			retries = retries +1;
			refreshBanner ( linkId, imgId, grp, type )
		} else {
			// verifica dell'URL dell'immagine restituita, se è valido (restituisce HTTPCode=200) allora lo uso, se non è valido riprovo
			if ( checkImg( lista[2] ) ) {
				// è valido, resetto il contatore
				retries = 0;
				
				BnrA.href = lista[1];
				BnrI.src = lista[2];
				BnrI.alt = '';
			} else {
				// non è valido, riprovo
				retries = retries +1;
				refreshBanner ( linkId, imgId, grp, type )
			}
		}
	}
function checkImg( url ) {
	xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (xmlhttp != null) {
		xmlhttp.onreadystatechange = stateChange;
		xmlhttp.open("GET", url, false);
		xmlhttp.send(null);
		
		if (xmlhttp.status == 200) {
			return true
		} else {
			return false
		}
	}
}

