/** (C) HTML.IT - insieme di funzioni ed oggetti utili per interagire con ajax */

/** FUNZIONI */

	// funzione per prendere un elemento con id univoco
		function prendiElementoDaId(id_elemento) {
			var elemento;
			if(document.getElementById)
				elemento = document.getElementById(id_elemento);
			else
				elemento = document.all[id_elemento];
			return elemento;
		};
	
	// funzione per assegnare un oggetto XMLHttpRequest
		function assegnaXMLHttpRequest() {
			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;
		};



/** OGGETTI / ARRAY */

	// oggetto di verifica stato
		var readyState = {
			INATTIVO:	0,
			INIZIALIZZATO:	1,
			RICHIESTA:	2,
			RISPOSTA:	3,
			COMPLETATO:	4
		};

	// array descrittivo dei codici restituiti dal server
	// [la scelta dell' array è per evitare problemi con vecchi browsers]
		var statusText = new Array();
		statusText[100] = "Continue";
		statusText[101] = "Switching Protocols";
		statusText[200] = "OK";
		statusText[201] = "Created";
		statusText[202] = "Accepted";
		statusText[203] = "Non-Authoritative Information";
		statusText[204] = "No Content";
		statusText[205] = "Reset Content";
		statusText[206] = "Partial Content";
		statusText[300] = "Multiple Choices";
		statusText[301] = "Moved Permanently";
		statusText[302] = "Found";
		statusText[303] = "See Other";
		statusText[304] = "Not Modified";
		statusText[305] = "Use Proxy";
		statusText[306] = "(unused, but reserved)";
		statusText[307] = "Temporary Redirect";
		statusText[400] = "Bad Request";
		statusText[401] = "Unauthorized";
		statusText[402] = "Payment Required";
		statusText[403] = "Forbidden";
		statusText[404] = "Not Found";
		statusText[405] = "Method Not Allowed";
		statusText[406] = "Not Acceptable";
		statusText[407] = "Proxy Authentication Required";
		statusText[408] = "Request Timeout";
		statusText[409] = "Conflict";
		statusText[410] = "Gone";
		statusText[411] = "Length Required";
		statusText[412] = "Precondition Failed";
		statusText[413] = "Request Entity Too Large";
		statusText[414] = "Request-URI Too Long";
		statusText[415] = "Unsupported Media Type";
		statusText[416] = "Requested Range Not Satisfiable";
		statusText[417] = "Expectation Failed";
		statusText[500] = "Internal Server Error";
		statusText[501] = "Not Implemented";
		statusText[502] = "Bad Gateway";
		statusText[503] = "Service Unavailable";
		statusText[504] = "Gateway Timeout";
		statusText[505] = "HTTP Version Not Supported";
		statusText[509] = "Bandwidth Limit Exceeded";




function leggiContenuto(item, nomeNodo) {
	if(item.getElementsByTagName(nomeNodo).item(0).firstChild){
		var str = item.getElementsByTagName(nomeNodo).item(0).firstChild.nodeValue;
  	return str;//.replace('<',"&lt;").replace('>',"&gt;");
  }
  else
  	return "";
};



var arrSMS, arrWEB, smsOK, webOK, luoghi, cont;

var smile = new Array();

	smile[0] =  new Array(';)', ":ah:",":wow",":wohhh:",":vom:",":up:",":testate:",":sun:",":smack:",":si:",":saint:",":rotolo:",":rosso:",":roll:",":reyes:",":regol:",":regan:",":P",":o",":no:",":met:",":mad:",":kal:",":italy:",":help:",":dj:",":D",":cul:",":crybaby:",":cool:",":comp:",":arg:",":aff:",":ador:",":?:",":)",":(");
	smile[1] =  new Array("wink.gif", "lol.gif", "wow.gif", "ohhh.gif", "barfy.gif", "up.gif", "testate.gif", "sun.gif", "bisou.gif", "yes.gif", "saint2.gif", "rotolo.gif", "arb.gif", "roll.gif", "rolleyes.gif", "regolamento.gif", "regan.gif", "tongue.gif", "shocked.gif", "no.gif", "metallica.gif", "mad.gif", "smile_kal.gif", "italy.gif", "help.gif", "dj.gif", "biggrin.gif", "cul.gif", "crybaby.gif", "cool.gif", "computer.gif", "arg.gif", "affogo.gif", "prostrazione.gif", "puzzled.gif", "smile.gif", "sad.gif");

// Legge i messaggi da XML e restituisce un array [1] data, [2] testo

function leggiMex(xml) {

 var
 	
	mex = new Array(),
	
	items = xml.getElementsByTagName("item"),
	
	testo, descrizione, mitt, data;
	

 for(var a = 0, b = items.length; a < b; a++) {
 
 	mex[a] = new Array(2);

	descrizione = unescape(leggiContenuto(items[a], "description"));
	
	testo = unescape(leggiContenuto(items[a], "title"));
	
	mitt = unescape(leggiContenuto(items[a], "link"));
	
	data = leggiContenuto(items[a], "pubDate");
	
	for (var i = 0; i < smile[0].length; i++){
		testo = testo.replace(smile[0][i], '<img src="./images/smilies/'+smile[1][i]+'" style="border:none" alt="'+smile[0][i]+'" />');
	}
	
	if(mitt != "")
		mitt = data+' - <a href="'+mitt+'" target="_blank"><b>'+testo+'</b></a>';
	
	mex[a][1] = data.substr(5,21);//.split(' ').join('').split(':').join('').split('-').join('');
  
  if(cont)
  	mex[a][2] = descrizione;
  else
		mex[a][2] = "&nbsp;"+mitt;

 }
	
 return mex;
}



function ordina(sms, web){

	var s = 0, 
	w = 0,
	ordine = new Array();

	for (var i = 0; s < sms.length && w < web.length; i++){

		if(sms[s][1] < web[w][1]){
			if (sms[s][1].substr(3,3) == web[w][1].substr(3,3)){
				ordine[i] = web[w][2];
				w++;
			}
			else{
				ordine[i] = sms[s][2];
				s++;
			}
			
			continue;
		}
		else{
			if (sms[s][1].substr(3,3) == web[w][1].substr(3,3)){
				ordine[i] = sms[s][2];
				s++;
			}
			else{
				ordine[i] = web[w][2];
				w++;
			}
		}	
	}
	
	for (var k = i; s == sms.length && w < web.length; k++, w++)
		ordine[k] = web[w][2];
		
	for (var j = k; s < sms.length && w == web.length; j++, s++)
		ordine[j] = sms[s][2];	
		
	return ordine;
}




function caricaTesto(nomeFile) {

	var kalaMex = prendiElementoDaId("cCMar");
	
  var arrTmp;
  
  var kajax = assegnaXMLHttpRequest();


  if(kajax) {

    kajax.open("GET", nomeFile, true);

    kajax.setRequestHeader("connection", "close");
		kajax.setRequestHeader("Content-Type", "text/xml");
 		kajax.setRequestHeader("Cache-Control", "no-cache");

 
    kajax.onreadystatechange = function() {

		  if(kajax.readyState === readyState.COMPLETATO) {
    
    		if(statusText[kajax.status] === "OK") {

      		if(kajax.responseXML){

        		arrTmp = leggiMex(kajax.responseXML);

      		}
      		else{
      		
        		arrTmp[0][2] = kajax.responseText;
        	
      		}
      
      		current = 0;
      
      		if (arrTmp[0][1] === "0"){
      			
        		nodechange(kalaMex, "<nobr>"+contents.toString()+"</nobr>");
        		caric();
      		}
      		else{
      		
      			//if(running == false)
						//	tickerstart();
						//var kalaMex = prendiElementoDaId("cCMar");
						nodechange(kalaMex, "<nobr>"+contents.toString()+"</nobr>");
      		}
    		}
    		else{
    
      		arrTmp[0][2] = "Impossibile effettuare l'operazione richiesta. " + "Errore riscontrato: " + statusText[kajax.status];
    		}
    		
    		if (nomeFile.substr(0,8) == "/calvera"){
    			arrSMS = arrTmp;
    			smsOK = true;
    		}
    		else if (nomeFile.substr(0,6) == "/leggi"){
      		arrWEB = arrTmp;
      		webOK = true;
    		}
    		if(smsOK && webOK){
    			
    			contents = ordina(arrSMS, arrWEB);
    		
					nodechange(kalaMex, "<nobr>"+contents.toString()+"</nobr>");
					document.getElementById("cMar").style.height = (objetto.offsetHeight+5)+"px";
					
					if(cont)
						scriviNews();
						
    			smsOK = false;
    			webOK = false;
    		}
    	
  		}
		}

 
    kajax.send(null);
  }
   
  return null;
} 




function scrivi(questo) {

	if (document.getElementById) {
	
		var newmess = document.getElementById("newmex");
		
		if(document.getElementById(questo).style.display == "none"){
		
			nodechange(newmess, "Nascondi");
			document.getElementById(questo).style.display = "block";
		}
		else{
		
			nodechange(newmess, "New Message");
			document.getElementById(questo).style.display = "none";
		}
  }
}


function vai(pos){

var newpos = current+pos-1;

if(newpos == -1)
	current = contents.length-1;
else if(newpos == -2)
	current = contents.length-2;
else if(newpos >= contents.length)
	current = 0;
else	
	current = newpos;
	
tickerrun();
window.clearInterval(runid);
runid = window.setInterval(tickerrun, delay, '');
}

function newMessage(){

var nick = prendiElementoDaId("nick").value;
var testo = prendiElementoDaId("testo").value;

if(nick.toUpperCase() == "SMS" || nick == "Nome")
	alert("Nome non valido!");
else{
	caricaTesto("/newMessage.php?nick="+escape(nick)+"&testo="+escape(testo)+"&r="+Math.random());
	alert("Messaggio inviato!");
}
	
}



function aggiorna(){

caricaTesto("/calvera_leggiNews.php?t="+Math.random());
caricaTesto("/leggiNews.php?t="+Math.random());

objetto.style.left=(cWid+offset)+"px";
}


function caric(){

if(luoghi)
load();


	startMarquee();

caricaTesto("/calvera_leggiNews.php?t="+Math.random());
caricaTesto("/leggiNews.php?t="+Math.random());

}
