// GESTISCE LA CHIAMATA AJAX
// url = indirizzo da chiamare
// idElemento = id dell'elemento html in cui inserire il contenuto (default = 'ajax')
// tipo:	s = sfondo trasparente cliccabile, con loading, no aggiungi (default)
//			l = messaggio statico testuale in idElemento
//			n = no sfondo, no loading, no aggiungi; 
//			a = no sfondo, no loading, aggiungi
// metodo: GET o POST
// modulo: nome del form inviato
function sk(url,idElemento,tipo,metodo,modulo) {
	if(!idElemento) idElemento = 'ajax';
	if(!tipo) tipo = 's';
	if(!metodo) metodo = 'GET';

	// se usa il metodo POST, legge i campi del modulo inviato e li registra in stringa
	if(metodo == 'POST') var stringa = leggiModulo(modulo);

	var
    ajax = XMLHttp(),
    e = document.getElementById(idElemento),
    usaLink = true;

	// eventuale div#ats dove compare un messaggio di attesa, da cancellare alla fine
	if(document.getElementById('ats')) var ats = document.getElementById('ats');

	e.style.display = 'block';

	if(tipo == 's')
		e.innerHTML = '<div id="ajax_sotto" onclick="chiudi(idElemento)"><img src="/img2/loading/loading2.gif" id="loading" alt="" /></div>';
	if(tipo == 'l')
		e.innerHTML = '<div id="loading_txt">CARICAMENTO IN CORSO...</div>';
	
	if(ajax) {	
		usaLink = false;
		ajax.open(metodo, url, true);
		if(metodo == 'POST') 
			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
		else
			ajax.setRequestHeader("connection", "close");
		
		ajax.onreadystatechange = function() {
			if(ajax.readyState === readyState.COMPLETATO) {
				if(statusText[ajax.status] === "OK") {
					if(tipo == 'a') e.innerHTML += ajax.responseText;
					else e.innerHTML = ajax.responseText;					
				} else {
					e.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
					e.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
        		}
        		// cancella eventuale div#ats
        		if(ats) ats.style.display = 'none';
      		} 
    	}
		if(metodo == 'GET') ajax.send(null); else ajax.send(stringa);
	}
	return usaLink;
}
//// FINE GESTISCE CHIAMATA AJAX



// assegna un oggetto XMLHttpRequest
function XMLHttp() {
	var
	XHR = null,
	browserUtente = navigator.userAgent.toUpperCase();
	if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
		XHR = new XMLHttpRequest();
	else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
		if(browserUtente.indexOf("MSIE 5") < 0)
			XHR = new ActiveXObject("Msxml2.XMLHTTP");
		else
			XHR = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return XHR;
};



// oggetto di verifica stato
var readyState = {
	INATTIVO:	0,
	INIZIALIZZATO:	1,
	RICHIESTA:	2,
	RISPOSTA:	3,
	COMPLETATO:	4
};



// array descrittivo dei codici restituiti dal server
var statusText = new Array();
statusText[200] = "OK";
statusText[204] = "No Content";
statusText[400] = "Bad Request";
statusText[401] = "Unauthorized";
statusText[403] = "Forbidden";
statusText[404] = "Not Found";
statusText[408] = "Request Timeout";
statusText[500] = "Internal Server Error";
statusText[503] = "Service Unavailable";
statusText[504] = "Gateway Timeout";




function leggiModulo(idModulo) {
	var stringa = '';
	var form = document.getElementById(idModulo);
	var numeroElementi = form.elements.length;
	
	for(var i = 0; i < numeroElementi; i++){
		if(i < numeroElementi-1){
		stringa += form.elements[i].name+"="+encodeURIComponent(form.elements[i].value)+"&";
		}else{
		stringa += form.elements[i].name+"="+encodeURIComponent(form.elements[i].value);
		} 
	}
	return stringa;
}




function chiudi(idElemento) {
	if(!idElemento) idElemento = 'ajax';

	var e = document.getElementById(idElemento);
	e.innerHTML = '';
	e.style.display = "none";
}



window.onload = function() {
	var
	nomeFile = '/vst.php',
	b = document.getElementsByTagName('body'),
	w = b[0].offsetWidth,
	p = document.URL,
	scr = screen.width + 'x' + screen.height + ' (' + w + ')',
	ref = document.referrer;
	
	p = p.replace(/^http:\/\/www\.fabule\.it/, '');
	
	if(navigator.userAgent.search(/msie/i) >= 0)
		var lng = navigator.userLanguage;
	else
		var lng = navigator.language;

	var ck = getCookie();
	if(ck == null) var ck = 1;

	var ajax = XMLHttp();
  
	if(ajax) {				
		ajax.open("post", nomeFile, true);
		ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
		ajax.send('p=' + escape(p) + '&scr=' + scr + '&l=' + lng + '&ref=' + escape(ref) + '&ck=' + ck);
	}
}


// legge cookie
function getCookie() {
	var cookies = document.cookie.split('; ');
	for(var i = 0; i < cookies.length; i++) {
		var c = cookies[i];
		var pos = c.indexOf('=');
		var n = c.substring(0,pos);
		if(n == 'vst') return c.substring(pos+1);
	}
	return null;
}
