//----------------------------------------------------------------------------
// Code to determine the browser and version.
//----------------------------------------------------------------------------

function Browser() {

  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isNS    = false;  // Netscape
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

//----------------------------------------------------------------------------
// Code for handling the menu bar and active button.
//----------------------------------------------------------------------------

var activeButton = null;

// Capture mouse clicks on the page so any active button can be
// deactivated.

function setPageMousedown(capture) {
  if (!capture) {
    if (browser.isIE)
      document.onmousedown = null;
    else
      document.removeEventListener("mousedown");
  } else {
    if (browser.isIE)
      document.onmousedown = pageMousedown;
    else
      document.addEventListener("mousedown", pageMousedown, true);
  }
}

function pageMousedown(event) {

  var el;

  // If there is no active button, exit.

  if (activeButton == null)
    return;

  // Find the element that was clicked on.

  if (browser.isIE)
    el = window.event.srcElement;
  else
    el = (event.target.tagName ? event.target : event.target.parentNode);

  // If the active button was clicked on, exit.

  if (el == activeButton)
    return;

  // If the element is not part of a menu, reset and clear the active
  // button.

  if (getContainerWith(el, "DIV", "menu") == null) {
    resetButton(activeButton);
    activeButton = null;
  }
}

function buttonClick(event, menuId) {

  var button;

  // Get the target button element.

  if (browser.isIE)
    button = window.event.srcElement;
  else
    button = event.currentTarget;

  // Blur focus from the link to remove that annoying outline.

  button.blur();

  // Associate the named menu to this button if not already done.
  // Additionally, initialize menu display.

  if (button.menu == null) {
    button.menu = document.getElementById(menuId);
    if (button.menu.isInitialized == null)
      menuInit(button.menu);
  }

  // Reset the currently active button, if any.

  if (activeButton != null)
    resetButton(activeButton);

  // Activate this button, unless it was the currently active one.

  if (button != activeButton) {
    depressButton(button);
    activeButton = button;
  }
  else
    activeButton = null;

  return false;
}

function buttonMouseover(event, menuId) {


  var button;

  // Find the target button element.

  if (browser.isIE)
    button = window.event.srcElement;
  else
    button = event.currentTarget;

  // If any other button menu is active, make this one active instead.

  if (activeButton != null && activeButton != button)
    buttonClick(event, menuId);
}

function depressButton(button) {

  var x, y;

  // Update the button's style class to make it look like it's
  // depressed.

  button.className += " menuButtonActive";

  // Position the associated drop down menu under the button and
  // show it.

  x = getPageOffsetLeft(button);
  y = getPageOffsetTop(button) + button.offsetHeight;

  button.menu.style.left = x + "px";
  button.menu.style.top  = y + "px";
  button.menu.style.visibility = "visible";
}

function resetButton(button) {

  // Restore the button's style class.

  removeClassName(button, "menuButtonActive");

  // Hide the button's menu, first closing any sub menus.

  if (button.menu != null) {
    closeSubMenu(button.menu);
    button.menu.style.visibility = "hidden";
  }
}

//----------------------------------------------------------------------------
// Code to handle the menus and sub menus.
//----------------------------------------------------------------------------

function menuMouseover(event) {

  var menu;

  // Find the target menu element.

  if (browser.isIE)
    menu = getContainerWith(window.event.srcElement, "DIV", "menu");
  else
    menu = event.currentTarget;

  // Close any active sub menu.

  if (menu.activeItem != null)
    closeSubMenu(menu);
}

function menuItemMouseover(event, menuId) {

  var item, menu, x, y;

  // Find the target item element and its parent menu element.

  if (browser.isIE)
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
  else
    item = event.currentTarget;
  menu = getContainerWith(item, "DIV", "menu");

  // Close any active sub menu.

  if (menu.activeItem != null)
    closeSubMenu(menu);

  // Set pointers.

  menu.activeItem = item;
  item.subMenu    = document.getElementById(menuId);

  // Highlight the item element.

  item.className += " menuItemHighlight";

  // Initialize the sub menu, if not already done.

  if (item.subMenu == null) {
    item.subMenu = document.getElementById(menuId);
    if (item.subMenu.isInitialized == null)
      menuInit(item.subMenu);
  }

  // Get position for submenu based on the menu item.

  x = getPageOffsetLeft(item) + item.offsetWidth;
  y = getPageOffsetTop(item);

  // Adjust position to fit in view.

  var maxX, maxY;

  if (browser.isNS) {
    maxX = window.scrollX + window.innerWidth;
    maxY = window.scrollY + window.innerHeight;
  }
  if (browser.isIE) {
    maxX = (document.documentElement.scrollLeft   != 0 ? document.documentElement.scrollLeft   : document.body.scrollLeft)
         + (document.documentElement.clientWidth  != 0 ? document.documentElement.clientWidth  : document.body.clientWidth);
    maxY = (document.documentElement.scrollTop    != 0 ? document.documentElement.scrollTop    : document.body.scrollTop)
         + (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
  }
  maxX -= item.subMenu.offsetWidth;
  maxY -= item.subMenu.offsetHeight;

  if (x > maxX)
    x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth
      + (menu.offsetWidth - item.offsetWidth));
  y = Math.max(0, Math.min(y, maxY));

  // Position and show it.

  item.subMenu.style.left = x + "px";
  item.subMenu.style.top  = y + "px";
  item.subMenu.style.visibility = "visible";

  // Stop the event from bubbling.

  if (browser.isIE)
    window.event.cancelBubble = true;
  else
    event.stopPropagation();
}

function closeSubMenu(menu) {

  if (menu == null || menu.activeItem == null)
    return;

  // Recursively close any sub menus.

  if (menu.activeItem.subMenu != null) {
    closeSubMenu(menu.activeItem.subMenu);
    menu.activeItem.subMenu.style.visibility = "hidden";
    menu.activeItem.subMenu = null;
  }
  removeClassName(menu.activeItem, "menuItemHighlight");
  menu.activeItem = null;
}

//----------------------------------------------------------------------------
// Code to initialize menus.
//----------------------------------------------------------------------------

function menuInit(menu) {

  var itemList, spanList;
  var textEl, arrowEl;
  var itemWidth;
  var w, dw;
  var i, j;

  // For IE, replace arrow characters.

  if (browser.isIE) {
    menu.style.lineHeight = "2.5ex";
    spanList = menu.getElementsByTagName("SPAN");
    for (i = 0; i < spanList.length; i++)
      if (hasClassName(spanList[i], "menuItemArrow")) {
        spanList[i].style.fontFamily = "Webdings";
        spanList[i].firstChild.nodeValue = "4";
      }
  }

  // Find the width of a menu item.

  itemList = menu.getElementsByTagName("A");
  if (itemList.length > 0)
    itemWidth = itemList[0].offsetWidth;
  else
    return;

  // For items with arrows, add padding to item text to make the
  // arrows flush right.

  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    textEl  = null;
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], "menuItemText"))
        textEl = spanList[j];
      if (hasClassName(spanList[j], "menuItemArrow"))
        arrowEl = spanList[j];
    }
    if (textEl != null && arrowEl != null)
      textEl.style.paddingRight = (itemWidth 
        - (textEl.offsetWidth + arrowEl.offsetWidth)) + "px";
  }

  // Fix IE hover problem by setting an explicit width on first item of
  // the menu.

  if (browser.isIE) {
    w = itemList[0].offsetWidth;
    itemList[0].style.width = w + "px";
    dw = itemList[0].offsetWidth - w;
    w -= dw;
    itemList[0].style.width = w + "px";
  }

  // Mark menu as initialized.

  menu.isInitialized = true;
}

//----------------------------------------------------------------------------
// General utility functions.
//----------------------------------------------------------------------------

function getContainerWith(node, tagName, className) {

  // Starting with the given node, find the nearest containing element
  // with the specified tag name and style class.

  while (node != null) {
    if (node.tagName != null && node.tagName == tagName &&
        hasClassName(node, className))
      return node;
    node = node.parentNode;
  }

  return node;
}

function hasClassName(el, name) {

  var i, list;

  // Return true if the given element currently has the given class
  // name.

  list = el.className.split(" ");
  for (i = 0; i < list.length; i++)
    if (list[i] == name)
      return true;

  return false;
}

function removeClassName(el, name) {

  var i, curList, newList;

  if (el.className == null)
    return;

  // Remove the given class name from the element's className property.

  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function getPageOffsetLeft(el) {

  var x;

  // Return the x coordinate of an element relative to the page.

  x = el.offsetLeft;
  if (el.offsetParent != null)
    x += getPageOffsetLeft(el.offsetParent);

  return x;
}

function getPageOffsetTop(el) {

  var y;

  // Return the x coordinate of an element relative to the page.

  y = el.offsetTop;
  if (el.offsetParent != null)
    y += getPageOffsetTop(el.offsetParent);

  return y;
}
var turno=0;


function colora (stringa)
{
	var numeri = stringa.split("-");
	pulisciselezione();
	turno = numeri[0];
for (var i = 0; i < numeri.length; i++)
	{
	document.getElementById("t"+numeri[i]).bgColor = "lightblue";
	}
	document.getElementById("infoturno-"+numeri[0]).style.visibility="visible";
	document.getElementById("infoturno-"+numeri[0]).style.height="190px";
	

}

function pulisciselezione()
{
	if (turno != 0)
	{
		document.getElementById("infoturno-"+turno).style.visibility="hidden";
	}
	var treni = Array(
	823,834,
	1931,1933,1930,1932,
	1921,1923,1920,1922,
	1937,1939,1938,1936,
	1925,1927,1924,1926,
	1941,1945,1940,1942,
	792,794,793,795,
	719,721,720,722,
	726,730,725,729);
	for (var i =0; i <treni.length; i++)
	{
		document.getElementById("t"+treni[i]).bgColor = "#c7c4b3";
	}	

}

function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    //var strUrl = "dammi_info.php";
    var self = this;
    var unita = document.getElementById("unita").value;
     // Xhr per Mozilla/Safari/Ie7
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // per tutte le altre versioni di IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.setRequestHeader('Enctype', 'multipart/form-data');
    
    //self.xmlHttpReq.send('unita='+unita);
    //chiudo la connessione
//    self.xmlHttpReq.setRequestHeader("connection", "close");
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    
    self.xmlHttpReq.send('unita='+unita);
    //chiudo la connessione
    //self.xmlHttpReq.setRequestHeader("connection", "close");
}


function updatepage(str){

    var vettore = str.split("|");
document.getElementById("INFO_unita").innerHTML = vettore[0];
document.getElementById("INFO_divisione").innerHTML = vettore[1];
document.getElementById("INFO_deposito").innerHTML = vettore[2];
document.getElementById("INFO_costruttore").innerHTML = vettore[3];
document.getElementById("INFO_scmt").innerHTML = vettore[4];
}

function doSubmitTreno()
{
    var treno = document.getElementById("treno").value;
    if(parseInt(treno) !== 0 && !isNaN(parseInt(treno))) {
      var url = "/orario/treno/"+treno+".html";
      document.getElementById("formSearchTreno").action = url;
      location.href = url;
      return true;
    } else {
      alert("Errore nei dati inseriti");
      return false;
    }
    
    
}

function doSubmitFormStazioni()
{
	var objS = document.getElementById("stazione");
  	var stazione = objS.options[objS.selectedIndex].value;
	location.href="/orario/stazione/"+stazione+".html";
	return false;
}



function coloraTube(object)
{
  
    if (object.className.indexOf("hover")<0)
    {
        object.className = object.className + "-hover";
        
        
        
    }
    else
    {
        object.className = object.className.replace("-hover","");
        
    }
    
}


function chiudi()
{
document.getElementById("loading").style.display = "none";
}
function colora(){
}

function chiudi(id)
{
document.getElementById(id).style.display = "none";

}

function prova()
{
document.getElementById("loading").style.display = "none";

}
var numero = 0;
function contatore(totale)
{
    numero++;
    if (numero == totale)
    {
    document.getElementById("loading").style.display = "none";
    numero = 0;
    }
}



function colora(id,num)
{	
var classe = document.getElementById(id).className;
	if (classe=="icona"){
	document.getElementById(id).className="iconaover";
	}
	else if (classe=="iconaover"){
	document.getElementById(id).className="icona";
	}
}

function coloraR(id,num)
{	
	
	var classe = document.getElementById(id).className;
	if (classe=="riga_info"){
	document.getElementById(id).className="riga_info_over";
	}
	else if (classe=="riga_info_over"){
	document.getElementById(id).className="riga_info";
	}
}

function searchByDenominazione(id,nome)
{
	var url = "/stampamezzi.php?classificazione="+id;
	
	return mostraImpostazioniDaClassificazione(url,nome);
}

function riempi(id)
{
	var newElem =document.createElement("DIV");
	newElem.id="nuovo";
	newElem.className="iconaover";
	var newText = document.createTextNode(id);
	newElem.appendChild(newText);
	document.getElementById("contenitoreicone").appendChild(newElem);
}

function svuotaContenitoreDaId(id)
{
var ci= document.getElementById(id);
	while (ci.childNodes[0]) {
	ci.removeChild(ci.childNodes[0]);
}
}

function cercaStazione()
{
var queryString = document.getElementById("keyword").value;
document.getElementById("status").style.visibility="visible";
var url = "/getStazioni.php?keyword="+queryString;
riempiSelectConAjax(url,"riga_select");
//document.getElementById("status").style.visibility="hidden";
}

function checkFormFotoOspiti()
{
    var messaggio = "";
    //var unita = parseInt(document.getElementById("unita").value);
    var unita = (document.getElementById("unita").value);
    if (unita == "" || isNaN(unita) || (unita < 0 || (unita > 104 && unita < 159) || (unita >307 && unita < 401) || unita > 608 )  )
    {
    	messaggio+="\n- Inserisci una unità valida";
    }
    if (unita < 10)
    {
        unita = "00"+unita;
        while (unita.length > 3)
        {
        unita = unita.substr(1);
        }
        document.getElementById("unita").value = unita;
      
    }
    else if (unita < 100)
    {
        unita = "0"+unita;
        while (unita.length > 3)
        {
        unita = unita.substr(1);
        }
        document.getElementById("unita").value = unita;
    }
    

    var luogo = document.getElementById("luogo").value;
    if (luogo =="" || luogo.length < 4)
    {
	    messaggio+="\n- Inserisci una località per il tuo scatto (Min 3 caratteri)";
    }
    var file1 = document.getElementById("file1").value;
    if (file1.length < 1)
    {
    	messaggio+="\n- E' necessario selezionare un file per l'upload";
    }
    if (messaggio!="")
    {
        alert("Attenzione, si sono verificati degli errori durante la compilazione del form: "+messaggio);
    return false;
    }
//TORNA TRUE
//return true;
return true;
}








var startMenu = function() {
				if (document.all&&document.getElementById) {
				cssmenu = document.getElementById("csstopmenu");
				for (i=0; i<cssmenu.childNodes.length; i++) {
				node = cssmenu.childNodes[i];
				if (node.nodeName=="LI") {
				node.onmouseover=function() {
				this.className+=" over";
				}
				node.onmouseout=function(){                  
				this.className=this.className.replace(" over", "")
				}
				}
				}
				}
				}

//function to start the menu
if (window.attachEvent) {
	window.attachEvent("onload", startMenu)
} else {
	window.onload=startMenu;
}


function viewPrestazione()
{
var id = document.getElementById("linea").value;
var url = "/getDatiFcl.php?id="+id;
       getWithAjax(url,"mostraprestazioni");
}


 
	function scriviDati(tabella,campi)
	{
	var querystring="tabella="+tabella;
	var arraycampi = campi.split('-');
	var i = 0;
	for (;i< arraycampi.length-1; i++)
	{
		var valore = document.getElementById(arraycampi[i]).value;
		if (valore!="")
		{
		querystring+="&"+arraycampi[i]+"="+valore;
		}
	}
	
	postWithAjax('/inserisciRiga.php','mostrastruttura',querystring);
	
	
	}
        function cancellaRiga(variabile,tabella)
	{
		setLoading('loading');
		postWithAjax('/cancellaRiga.php','statusrichiesta',variabile);
		postWithAjax('/getDatiTabella.php','mostradati','tabella='+tabella);
		setLoading('loading');
	
	}
	function setLoading(id)
	{
	if (document.getElementById(id).style.visibility=='visible')
		{
			document.getElementById(id).style.visibility='hidden';
		}
		else if (document.getElementById(id).style.visibility=='hidden')
		{
			document.getElementById(id).style.visibility='visible';
		}
	
	}
        function selectTabella()
	{
		setLoading('loading');
		var tabella = "tabella="+document.getElementById("tabelle").value;
		postWithAjax('/disegnaStruttura.php','mostrastruttura',tabella);
		postWithAjax('/getDatiTabella.php','mostradati',tabella);
		setLoading('loading');
	}
	function deleteArticolo(id)
	{
	setLoading('loading');
	var dati = "id="+id;
	alert("ciao");
	postWithAjax('/deleteArticolo.php','miodiv',dati)
	setLoading('loading');
	}
	
	function inviaDati(pagina,contenitorefinale)
	{
	setLoading('loading');
	var dati = "data="+document.getElementById('data').value+"&titolo="+document.getElementById('titolo_art').value+"&articolo="+document.getElementById('articolo').value;
	//alert(dati);
	postWithAjax(pagina,contenitorefinale,dati)
	//alert(document.getElementById("miatabella").innerHTML);
	setLoading('loading');
	}

	// 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;
		};
    
    // funzione per cambiare dinamicamente il contenuto di un contenitore
        function getWithAjax(nomefile,contenitore) { 
        var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
		  
                        document.getElementById(contenitore).innerHTML = ajax.responseText;
		     }
                    else
                        document.getElementById(contenitore).innerHTML = "ERRORE IN QUALCOSA";   
                }
            }
            ajax.send(null);
           
        }
        return usalink;

}

        function postWithAjax(nomefile,contenitore,infotosend) { 
	   
	   //Creo un nuovo oggetto XMLHTTPRequest
            var req = assegnaXMLHttpRequest(); 
            if(req)
            {
                  //Invio la richiesta
				req.open("POST", nomefile, true);
				req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				
                //Invio i dati POST
				req.send(infotosend);
				
				//Gestore dell'evoluzione dello stato dell'oggetto req
				req.onreadystatechange = function() 
                {
                    if(req.readyState === 4) 
                    {
                        if(req.status == 200)
                        {    
			
                            document.getElementById(contenitore).innerHTML = req.responseText;
			    
			 
                        }
                        else
                            document.getElementById(contenitore).innerHTML = "ERRORE IN QUALCOSA";   
                    }
                }   
                
            }
          
}


	// 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 showDeposito(id,nome) { 
	       if (document.getElementById("anteprima_assegnazioni").style.display=="block")
        {
        document.getElementById("anteprima_assegnazioni").style.display="none";
        document.getElementById("report_assegnazioni").style.display="block";
        }
        document.getElementById("dep_name").innerHTML=nome;
        var ajax = assegnaXMLHttpRequest(); 
        var nomefile = "/deposito_printer.php?cod_deposito="+id;
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
               if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
                        var splittaggio = ajax.responseText.split("#-#");
                        
                        var unita = splittaggio[0].split("#@#");
                        document.getElementById("elenco_unita").innerHTML="";
                        for (var i=0; i < unita.length-1; i++)
                        {
                            var valori=unita[i].split("-");
                            var nodo = document.createElement("DIV");
                            var classe = "t_1";
                          
                            nodo.className=classe;
                            var valore = document.createTextNode(valori[0]);
                            nodo.appendChild(valore);
                            nodo.onclick =function () {
                            alert(this.className);
                            }
                            nodo.setAttribute("title",valori[1]);
                            document.getElementById("elenco_unita").appendChild(nodo);
                        }
                        document.getElementById("num_tot").innerHTML=splittaggio[1];
                        document.getElementById("num_656").innerHTML=splittaggio[2];
                        document.getElementById("num_655").innerHTML=splittaggio[3];
                        document.getElementById("num_scmt_si").innerHTML=splittaggio[4];
                        document.getElementById("num_scmt_no").innerHTML=splittaggio[5];
                        document.getElementById("num_pax").innerHTML=splittaggio[6];
                        document.getElementById("num_cargo").innerHTML=splittaggio[7];
                        document.getElementById("num_tmr").innerHTML=splittaggio[8];
		            }
                    else
                    {
                        alert("errore");
                    }
                }
            }
            ajax.send(null);
           
        }
    }















function initLoader()
{
document.getElementById("loading").style.display = "block";
}
function stopLoader()
{
document.getElementById("loading").style.display = "none";
}
function cambiaGIF(object)
{
    if (object.className=="icona_close_risultati2")
    {
    object.className="icona_close_risultati";
    }
    else
    {
    object.className="icona_close_risultati2";
    }
}
function goTo(url)
{
location.href=url;
}
function colora(object)
{
   }
function linker(object)
{
    if (object.className.indexOf("hover")==-1)
    {
    var nome = object.className;
    object.className = nome+"hover";
    }
    else
    {
    object.className=object.className.replace("hover","");
    }
}


  // 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;
		};
        
         
    // funzione per cambiare dinamicamente il contenuto di un contenitore
        function getWithAjax(nomefile,contenitore) { 
         var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
               if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
                    
		            document.getElementById(contenitore).innerHTML = ajax.responseText;		
		            }
                    else
                    {
                        document.getElementById(contenitore).innerHTML = "ERRORE IN QUALCOSA";   
                    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;

}



function stampaTreni(staz)
{
    var start_i=0;
    var x=setInterval(function() {
     var ajax = assegnaXMLHttpRequest(); 
     var nomefile="/getter_treni.php?limite="+start_i+"&where="+staz;
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
               if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
                        if(ajax.responseText!="     " || start_i > 100)
                        {   
                            var tmp =ajax.responseText.split("@");
                            if(tmp.length >1)
                            {
                            document.getElementById("num_treni").innerHTML = parseInt(document.getElementById("num_treni").innerHTML)+tmp.length;
                            
                            for(var i=0; i < tmp.length; i++)
                            {   
                                var tr = document.createElement("TR");
                                tr.style.border="1px solid #8AA8E6";
                                if(i%2==0) tr.style.backgroundColor="white"; else tr.style.backgroundColor="rgb(208,218,234)";
                                var tmp2=tmp[i].split("#");
                                if(tmp2.length > 1)
                                {
                                    for(var j=0; j<tmp2.length; j++)
                                    {
                                        if(tmp2[j]!="")
                                        {
                                            var td = document.createElement("TD");
                                            td.innerHTML=tmp2[j];
                                            tr.appendChild(td);
                                        }
                                    }
                                }
                                document.getElementById("tabella_treni").appendChild(tr);
                            }
		                //    document.getElementById("tabella_treni").innerHTML += ajax.responseText;	
                            start_i+=10;   
                            }
                            else
                            {
                            document.getElementById("caricatore").innerHTML="";
                            }
                            
                        }
                        else
                        {
							document.getElementById("caricatore").innerHTML="";
    	                    clearInterval(x);
                        }
		            }
                    else
                    {
                        document.getElementById("tabella_treni").innerHTML = "ERRORE IN QUALCOSA";   
                    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;
    
    },800);
}

function riempiRicercaConAjax(cond)
{
var nomefile = "/ricercaWriter.php?cond="+cond;
getWithAjax(nomefile,"risultato_ricerca")
}

function ricercaConAjax(e)
{

 document.getElementById("risultati").innerHTML ="Ricerca in corso..";
 
    if (document.getElementById("blocco_risultati").style.display=="none")
    {
        document.getElementById("blocco_risultati").style.display = "block";
    }
    var chiave = document.getElementById("keyword").value;
    var keynum;
    var keychar;
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
    keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    chiave = chiave+keychar;   
    var url = "/searcher.php?key="+chiave;
    getWithAjax(url,"risultati");
}

function ricercaConAjax2()
{

 document.getElementById("risultati").innerHTML ="Ricerca in corso..";
 
    if (document.getElementById("blocco_risultati").style.display=="none")
    {
        document.getElementById("blocco_risultati").style.display = "block";
    }
    var chiave = document.getElementById("keyword").value;
    if(chiave.length > 3)
    {
    chiave = document.getElementById("keyword").value = chiave.substr(0,3);
    }
    var url = "/searcher.php?key="+chiave;
    getWithAjax(url,"risultati");
    
}



function getPaginaWithAjax(url,contenitore)
{
 return getPaginaWithAjax(url,contenitore,"450px")
}




function getPaginaWithAjax(url,contenitore,dimensione,style,pagina)
{
document.getElementById("loading").style.display = "block";
   document.getElementById(contenitore).innerHTML = "";
    var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",url,true);
            ajax.setRequestHeader("connection", "close");
            ajax.onreadystatechange = function(){
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
		                document.getElementById(contenitore).style.height=dimensione;
                        document.getElementById("local_style").href=style;
                        document.getElementById(contenitore).innerHTML = ajax.responseText;
                        var titolo = document.title;
                        if (titolo.indexOf("pagina: ")==-1)
                        {
                        titolo = titolo + " pagina: "+pagina;
                        document.title = titolo;
                        }
                        else
                        {
                        var esploso = titolo.split(":");
                        document.title = esploso[0]+": "+pagina;
                        }
			        }
                    else
                        document.getElementById(contenitore).innerHTML = "ERRORE IN QUALCOSA";   
                }
            }
            ajax.send(null);
                
        }
        
      
        return usalink;



}


function pulisciNodi(id)
{
var to = document.getElementById(id).childNodes[0];
	
	//for (j=to.length-1; j >= 1; j--) 
	for (j=to.length-1; j >= to.length-10; j--) 
	{
	to[j].parentNode.removeChild(to[j]);
	}

}
 function riempiSelectConAjax(nomefile,contenitore) { 
        var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
			var risposta = ajax.responseText;
			
			if (risposta=="")
			{
				alert("ATTENZIONE!!!  \nNessuna stazione trovata secondo questa chiave di ricerca");
			}
			else
			{
			
				var risp = risposta.split("#");
				//svuoto il contenitore attuale
				pulisciNodi(contenitore);
				
				for (var i = 0; i < risp.length-1; i++)
				{
				
					var risp_tmp = risp[i].split("-");
					var nuovo = document.createElement("OPTION");
					nuovo.setAttribute("value",risp_tmp[0]);
					nuovo.innerHTML =risp_tmp[1];
					document.getElementById(contenitore).childNodes[0].appendChild(nuovo);
				}
				document.getElementById("status").style.visibility="hidden";
			}
				
		     }
                    else
		    {
                        document.getElementById(contenitore).innerHTML = "ERRORE IN QUALCOSA";   
		    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;

}



function noCache(uri){return uri.concat(/\?/.test(uri)?"&":"?","noCache=",(new Date).getTime(),".",Math.random()*1234567)};



function mostraPosTreno(treno,tipo,da,a)
{ 

var iniziale = "<img src = '/gfx/gif.gif' alt = 'ciao' />     Attendere Prego,<br />Rilevamento informazioni sulla posizione in corso...";
document.getElementById("provatreno").innerHTML=iniziale;
  var ajax = assegnaXMLHttpRequest(); 
  var nomefile = "/dammiritardo.php?treno="+treno;
  usalink=true;   
  if(ajax)
    {
      usalink=false;     
      ajax.open("GET",noCache(nomefile),true);
      ajax.setRequestHeader("connection", "close");
      ajax.onreadystatechange = function() {
        if(ajax.readyState === 4) 
        {
          if(ajax.status == 200)
          {
                  
            var risposta = ajax.responseText;
            
            if (risposta=="")
              {
                alert("ATTENZIONE!!!  \nNessun treno trovato con questa classificazione");
              }
              else
              {			
              var risp = risposta.split("#");
              if (risp[2]=="ND")
              {
                document.getElementById("provatreno").innerHTML="Informazione non disponibile per il treno <b>"+treno+"</b>";
              }
              else
              {
                var testo = "Il treno "+tipo+" <b>"+treno+"</b> da "+da+" a "+a+" viaggia ";
                if (risp[2]==0){
                testo = testo+ "in orario.<br />";
                }
                else if (risp[2]<1)
                {
                  if (parseInt((risp[2]*-1))==1)
                  {
                    testo = testo+ "con <b>"+parseInt(risp[2])*-1+"</b> minuto di anticipo.<br />";
                  }
                  else 
                  {
                   testo = testo+ "con <b>"+parseInt(risp[2])*-1+"</b> minuti di anticipo.<br />";
                  }
                }
                else if (risp[2]>0)
                {
                  if (parseInt(risp[2])==1)
                  {
                    testo = testo + "con <b>"+parseInt(risp[2])+"</b> minuto di ritardo.<br />";
                  }
                  else
                  {
                    testo = testo + "con <b>"+parseInt(risp[2])+"</b> minuti di ritardo.<br />";
                  }
                }
                testo = testo + "Ultimo Rilevamento: <b>"+risp[1]+"</b> alle ore: <b>"+risp[3]+"</b>";
                document.getElementById("provatreno").innerHTML=testo;
                }
              }
          }
          else
          {
            alert("Errore generale");  
          }
        }
      }
      ajax.send(null);
    }
  return usalink;
}























function mostraImpostazioniDaClassificazione(nomefile,nome)
{ 
	    var contenitore = document.getElementById("localita_container");
	    var numNodi = contenitore.childNodes.length;
		var nuovoSpan =document.createElement("SPAN");
		nuovoSpan.className="dovesei";
		var newText = document.createTextNode(" >> ");
		nuovoSpan.appendChild(newText);
		var nuovoLink = document.createElement("A");
		nuovoLink.setAttribute("href","#");
		var newText = document.createTextNode(nome);
		nuovoLink.appendChild(newText);
		nuovoLink.onclick=function() {
		return mostraImpostazioniDaClassificazione(nomefile,nome);
		}
	
	if (numNodi > 1)
	{
		
		var j = numNodi-1;
		while (j > 0) {
		contenitore.removeChild(contenitore.childNodes[j]);
		j--;
		}
	}
	nuovoSpan.appendChild(nuovoLink);
	contenitore.appendChild(nuovoSpan);
	
	
        var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {
                      var risposta = ajax.responseText;
                    
                        var risposta = ajax.responseText;
                        if (risposta=="")
                        {
                            alert("ATTENZIONE!!!  \nNessun treno trovato con questa classificazione");
                        }
                        else
                        {
                            //document.getElementById("contenitoreicone").innerHTML = ajax.responseText;
                            var risp = risposta.split("@");
                            svuotaContenitoreDaId("contenitoreicone");
                            for (var i=0 ; i <risp.length-1; i++)
                            {
                                
                                var prova = risp[i].split("#");
                                if (prova.length==2)
                                {
                                var id_riga= "info_"+prova[0];
                                }
                                else if (prova.length==3)
                                {
                                var id_riga= "info_"+prova[0]+"_"+prova[2];
                                }
                                var newElem =document.createElement("DIV");
                                newElem.id=id_riga;
                                newElem.className="riga_info";
                                
                                if (prova.length > 0)
                                {
                                var newText = document.createTextNode(prova[1]);
                                newElem.appendChild(newText);
                                newElem.onmouseover=function(){return coloraR(this.id,"1");}
                                newElem.onmouseout=function(){ return coloraR(this.id,"2");}
                                newElem.onclick=function()
                                    {
                                        var identificativo = (this.id).split("_");
                                        var url;
                                        
                                        if (identificativo[2]!=undefined)
                                        {
                                        url = "/stampaimpostazioni.php?like="+identificativo[2];
                                        mostraImpostazioniDaLocomotore(url,identificativo[2]);
                                        }
                                        else
                                        {
                                        url = "/stampaimpostazioni.php?composizione="+identificativo[1];
                                        mostraImpostazioniDaLocomotore(url,this.innerHTML);
                                        }
                                        
                                        
                                    }
                                document.getElementById("contenitoreicone").appendChild(newElem);
                                }
                                
                            }
                            
                              //window.prompt("pigiatelo",document.getElementById("contenitoreicone").innerHTML);
                            
                        }
				
		        }
                    else
		    {
                        alert("Errore generale");  
		    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;
}



function mostraImpostazioniDaLocomotore(nomefile,nome)
{ 

	var contenitore = document.getElementById("localita_container");
	var numNodi = contenitore.childNodes.length;
		var nuovoSpan =document.createElement("SPAN");
		nuovoSpan.className="dovesei";
		var newText = document.createTextNode(" >> ");
		nuovoSpan.appendChild(newText);
		var nuovoLink = document.createElement("A");
		nuovoLink.setAttribute("href","#");
		var newText = document.createTextNode(nome);
		nuovoLink.appendChild(newText);
		nuovoLink.onclick=function() {
		return mostraImpostazioniDaLocomotore(nomefile,nome);
		}
		
	if (numNodi > 2)
	{
		
		var j = numNodi-1;
		while (j > 1) {
		contenitore.removeChild(contenitore.childNodes[j]);
		j--;
		}
	}
	nuovoSpan.appendChild(nuovoLink);
	contenitore.appendChild(nuovoSpan);
	
	
        var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
			var risposta = ajax.responseText;
			
			if (risposta=="")
			{
				alert("ATTENZIONE!!!  \nNessun treno trovato con questa classificazione");
			}
			else
			{
			
				var risp = risposta.split("@");
				svuotaContenitoreDaId("contenitoreicone");
				for (var i=0 ; i <risp.length-1; i++)
				{
						var prova = risp[i].split("#");
						var id_riga= "info_"+prova[0]+"_"+prova[1];
							var newElem =document.createElement("DIV");
							newElem.id=id_riga;
							newElem.className="riga_info";
							
							var newText = document.createTextNode(prova[1]);
							newElem.appendChild(newText);
							
							newElem.onmouseover=function(){return coloraR(this.id,"1");}
							newElem.onmouseout=function(){ return coloraR(this.id,"2");}
							newElem.onclick=function(){
							var identificativo = (this.id).split("_");
							var url = "/stampatreni.php?impostazione="+identificativo[1];
							
							return mostraTreni(url,identificativo[2]);
							
							
							}
							
							
						document.getElementById("contenitoreicone").appendChild(newElem);
				}
				
				
				
			}
				
		     }
                    else
		    {
                        alert("Errore generale");  
		    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;
}



function mostraTreni(nomefile,nome)
{
	var contenitore = document.getElementById("localita_container");
	var numNodi = contenitore.childNodes.length;
		var nuovoSpan =document.createElement("SPAN");
		nuovoSpan.className="dovesei";
		var newText = document.createTextNode(" >> ");
		nuovoSpan.appendChild(newText);
		var nuovoLink = document.createElement("A");
		nuovoLink.setAttribute("href","#");
		var newText = document.createTextNode(nome);
		nuovoLink.appendChild(newText);
		nuovoLink.onclick=function() {
		return mostraTreni(nomefile,nome);
		}
	if (numNodi > 3)
	{
		var j = numNodi-1;
		
		while (j > 2) {
		contenitore.removeChild(contenitore.childNodes[j]);
		j--;
		}
	}
	nuovoSpan.appendChild(nuovoLink);
	contenitore.appendChild(nuovoSpan);
	document.getElementById("waiting").style.display="block";
        var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
		if(ajax.readyState === 4) 
                {
			if(ajax.status == 200)
			{    
				var risposta = ajax.responseText;
				if (risposta=="")
				{
					alert("ATTENZIONE!!!  \nNessun treno trovato con questa classificazione");
				}
				else
				{
					var risp = risposta.split("@");
					document.getElementById("waiting").style.display="none";
					svuotaContenitoreDaId("contenitoreicone");
					if (risp.length > 1)
						{
							var divContainer =document.createElement("DIV");
							divContainer.className="riga_treno";
							var tabella = document.createElement("TABLE");
							tabella.className="table_treni";
							var tbody = document.createElement("TBODY");
							for (var i=0 ; i <risp.length-1; i++)
							{
								var prova = risp[i].split("#");
								var riga = document.createElement("TR");
								riga.id="treno-"+prova[1];
								riga.className="normal";
								
								riga.onmouseover=function(){
								this.className="over";
								}
								riga.onmouseout=function(){
								this.className="normal";
								}
								
								riga.onclick=function(){
								var aa = this.id.split("-");
								window.open("/orario/treno/"+aa[1]+".html","");
								}
								
								for (var j = 0; j < prova.length-1 ; j++)
								{
								var tmp = document.createElement("TD");
								if (prova[j]=="") prova[j]=" ";
								var newText = document.createTextNode(prova[j]);
								tmp.appendChild(newText);
								riga.appendChild(tmp);
								}
								tbody.appendChild(riga);
							}
							tabella.appendChild(tbody);
							divContainer.appendChild(tabella);
							document.getElementById("contenitoreicone").appendChild(divContainer);
						}
						else
						{
							alert("Non ci sono treni per l'opzione selezionata");
						}
				}
			}
				
		     
                    else
		    {
                        alert("Errore generale");  
		    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;
}












function stampaIndice(nomefile)
{ 
	var contenuto = '<span id = "dovesei"><a href = "#" onclick = "stampaIndice(\'/printIndex.php\');">indice</a>';
	document.getElementById("localita_container").innerHTML=contenuto;
        var ajax = assegnaXMLHttpRequest(); 
        usalink=true;   
        if(ajax)
        {
            usalink=false;     
            ajax.open("GET",nomefile,true);
            ajax.setRequestHeader("connection", "close");
            
            ajax.onreadystatechange = function() 
            {
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
			var risposta = ajax.responseText;
			
			if (risposta=="")
			{
				alert("ATTENZIONE!!!  \nErrore durante la stampa dell'indice");
			}
			else
			{
			
				var risp = risposta.split("@");
				svuotaContenitoreDaId("contenitoreicone");
				var impostazioni = new Array(risp.length);
				var i =0;
				for (; i <risp.length-1; i++)
				{
					var indice = i;
					var tmp = risp[i].split("#");
					impostazioni[i]= tmp[1];
					var newElem =document.createElement("DIV");
					newElem.id=tmp[0]+"_"+tmp[3];
					newElem.className="icona";
					var stringa = "<img src = '/images/icone/"+tmp[2]+"' alt = 'icona' /><br />"+tmp[3];
					newElem.innerHTML=stringa;
							
							newElem.onmouseover=function(){return colora(this.id,"1");}
							newElem.onmouseout=function(){ return colora(this.id,"2");}
							newElem.onclick=function(){
							var numero = this.id;
							var esplosione = numero.split("_");
							var num = parseInt(esplosione[1]);
							num=num+1;
							
							searchByDenominazione(num,esplosione[2]);
							}
					document.getElementById("contenitoreicone").appendChild(newElem);
				}
				
				
				
			}
				
		     }
                    else
		    {
                        alert("Errore generale");  
		    }
                }
            }
            ajax.send(null);
           
        }
        return usalink;
}



function svuotaContenitoreDaId(id)
{
	var ci= document.getElementById(id);
	while (ci.childNodes[0]) {
	ci.removeChild(ci.childNodes[0]);
	}
}




        function postWithAjax(nomefile,contenitore,infotosend) { 
	   
	   //Creo un nuovo oggetto XMLHTTPRequest
            var req = assegnaXMLHttpRequest(); 
            if(req)
            {
                  //Invio la richiesta
				req.open("POST", nomefile, true);
				req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				
                //Invio i dati POST
				req.send(infotosend);
				
				//Gestore dell'evoluzione dello stato dell'oggetto req
				req.onreadystatechange = function() 
                {
                    if(req.readyState === 4) 
                    {
                        if(req.status == 200)
                        {    
			
                
                            document.getElementById(contenitore).innerHTML = req.responseText;
			}
                        else
                            document.getElementById(contenitore).innerHTML = "ERRORE IN QUALCOSA";   
                    }
                }   
                
            }
          
}


function mostraOspiti(val,autore)
{
    var pagina = document.getElementById("pagina").value;
    var page = "";
    if (val >0)
    {
        page = parseInt(parseInt(pagina)+1);
    }
    else
    {
        page = parseInt(parseInt(pagina)-1);
    }
    var url = "/printUnita.php?pagina="+page+"&autore="+autore;
    alert(url);
    getWithAjax(url,"cont_last_corpo")
    document.getElementById("pagina").value = "";
    document.getElementById("pagina").value = parseInt(0+page);    
}


function doAutoSuggest()
{
	var value = (document.getElementById("staz").value).toLowerCase();
	if(value.length < 3) 
	{
		var node = document.getElementById("autosuggestion");
		if(node.childNodes.length > 0)
		{
			removeChildrenFromNode(node);
		}
	}
	else if(value.length == 3)
	{
		autoSuggesterStazioni(value);
	}
	else if(value.length > 3)
	{
		showMatches(value);
	}
}

function autoSuggesterStazioni(staz)
{
	arrayMatches = new Array();
	var ajax = assegnaXMLHttpRequest(); 
    if(ajax)
        {
			var url = "/autosuggestion_stazioni.php?staz="+staz;
            ajax.open("GET",url,true);
            ajax.setRequestHeader("connection", "close");
            ajax.onreadystatechange = function() 
            {
                if(ajax.readyState === 4) 
                {
                    if(ajax.status == 200)
                    {    
						var result = ajax.responseText;
						if(result.indexOf("NoResults") > 0 || result.indexOf("NoMatches") > 0)
						{
							addTextItemToList("Nessuna stazione corrispondente.");
						}
						else
						{
							var str = result.split("@");
							for(var i = 0; i < str.length; i++)
							{
								var strFinded = str[i].split("#");
								arrayMatches.push(strFinded);	
							}
							showMatches(staz);
						}

					}
			     }
                else
			    {

			    }	
             }
            ajax.send(null);
        }
}

function showMatches(keyWord)
{
	var autosuggestion = document.getElementById("autosuggestion");
	removeChildrenFromNode(autosuggestion);
	document.getElementById("autosuggestion").removeChild
	var printed = 0;
	for(var i = 0; i < arrayMatches.length && printed < 8; i++)
	{
		if((arrayMatches[i][0].toLowerCase()).indexOf(keyWord) > -1)
		{
			addItemToList(arrayMatches[i]);
			printed++;
		}
	}
	if(printed >= 8)
	{
		addTextItemToList("... e altri "+(arrayMatches.length-8)+" risultati");
	}
	else if(printed==0)
	{
		addTextItemToList("Nessuna stazione corrispondente.");
	}

}

function removeChildrenFromNode(node)
{
   var len = node.childNodes.length;
	while (node.hasChildNodes())
	{
	  node.removeChild(node.firstChild);
	}
}

function addItemToList(aItem)
{
	var div = document.createElement("DIV");
	var link = document.createElement("a");
	var testo = document.createTextNode(aItem[0]);
	link.setAttribute("href", "/orario/stazione/"+aItem[1]+".html");
	link.appendChild(testo);
	div.appendChild(link);	
	div.onmouseover = function() { div.setAttribute("style", "background-color: #C7C4B3;"); }
	div.onmouseout = function() { div.removeAttribute("style"); }		
	document.getElementById("autosuggestion").appendChild(div);
}

function addTextItemToList(strItem)
{
	var div = document.createElement("DIV");
	var text = document.createTextNode(strItem);
	div.appendChild(text);
	document.getElementById("autosuggestion").appendChild(div);
}





	// 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";

