downloader = null;

if (window.XMLHttpRequest)	 		// Mozilla, Safari,...
{
    	downloader = new XMLHttpRequest();
    	isExploder = false;
}
else if (window.ActiveXObject)		// IE
{
    	try 
    	{
        	downloader = new ActiveXObject("Msxml2.XMLHTTP.3.0");
        	isExploder = true;
        }
        catch (e)
        {
        	try 
        	{
            	downloader = new ActiveXObject("Microsoft.XMLHTTP");
            	isExploder = true;
            }
            catch (e)
            {
			    alert('Impossibile creare una istanza XMLHTTP');
            }
        }
}
else
	    alert('Impossibile creare una istanza XMLHTTP per questo browser');

try 
{
    downloader = new ActiveXObject("Msxml2.XMLHTTP");
    isExploder = true;
} 
catch (e) 
{
    try
    {
        downloader = new XMLHttpRequest();
        isExploder = false;
   }
    catch (e)
    {
        alert("Il browser corrente non e' compatibile con Servizi Impresa. Usare un browser piu' recente");
    }
}
   
function processRequest(richiesta)
{
	//applico un timestamp per disabilitare la cache degli url
	var notCachedUrl = richiesta;
	notCachedUrl += (notCachedUrl.indexOf("?") == -1) ? "?" : "&";
	notCachedUrl += "timestamp=" + new Date().getTime();

    try
    {
        downloader.open("GET", notCachedUrl, false);
        downloader.send(null);    
        var risposta= downloader.responseXML;
        var elements = risposta.getElementsByTagName('response');
 
        return elements[0].firstChild.nodeValue;
    }
    catch(e)
    {

        try
        {
          var temp = downloader.responseText.split("response>");
          var str = temp[1].split("</")[0];
          
          return str;
        }
        catch ( ee)
        {
            alert("Ci sono stati problemi nel caricamento della pagina, provare a ricaricare la pagina. \n"+
            "Se il problema persiste contattare l'amministratore");
        }
    }
}

var stati = undefined;
var toponimi = undefined;
var province_attive = undefined;
var province_tutte = undefined;
var cciaa_attive = undefined;
var cciaa_tutte = undefined;
function riempiStati(controlloName, defaultValue, statiKey)
{
    _riempiStati(controlloName, defaultValue, 0, statiKey);
}

function _riempiStati(controlloName, defaultValue, formIndex, statiKey)
{
//alert("-riempiStati-begin");
    combo = document.forms[formIndex][controlloName];

    if (combo == undefined)
        alert("riempiStati - Controllo '"+controlloName+"' inesistente");

    if (stati == undefined)
        caricaStati(statiKey);

    combo.options.length = stati.length + 1;
    combo.options[0] = new Option("","", true, true);
    
    for(t = 1; t <= stati.length; t++)
    {
        combo.options[t] = new Option(stati[t-1].nome , stati[t-1].codice, false, false);
    }

//alert("combo:"+combo);
    combo.value = defaultValue;  
//alert("-riempiStati-end"); 
}

function visualizzaStato(sigla, statiKey)
{
    var stato = undefined;
//    if (stati == undefined)
//    {
//        caricaStati(statiKey);
//    } 
    caricaStati(statiKey);	//va fatto tutte le volte perche' potrei avere, nella stessa pagina stati che hanno chiave diversa
    						//TODO: FIXME: gestire il caso meglio. vanno fatte piu' cache, una per ogni chiave possibile
    
    var padre = document.getElementById(sigla+"_codiceStato");
    
    var codiceStato = padre.childNodes[0].nodeValue;
    
    for(t = 1; t <= stati.length; t++)
    {
     
        if (stati[t-1].codice == codiceStato)
        {
            stato = stati[t-1].nome;
            padre.childNodes[0].nodeValue = stato;
            return;
        }
    }
    if (stato == undefined)
        alert("Stato non trovato!");
    return;  
}

function riempiProvince(controlloName, defaultValue, filtraScaduti)
{
	//il comportamento di default e' che filtra le province
	if (filtraScaduti == undefined)
    	_riempiProvince(controlloName, defaultValue, 0, true);
	else
	_riempiProvince(controlloName, defaultValue, 0, filtraScaduti);
}

function _riempiProvince(controlloName, defaultValue, formIndex, filtraScaduti)
{
//alert("-riempiProvince-begin");
    combo = document.forms[formIndex][controlloName];

    if (combo == undefined)
        alert("riempiProvince - Controllo '"+controlloName+"' inesistente");

    if (filtraScaduti && province_attive == undefined || !filtraScaduti && province_tutte == undefined)
        caricaProvince(filtraScaduti);

    var province = (filtraScaduti) ? province_attive : province_tutte;

    combo.options.length = province.length + 1;
    combo.options[0] = new Option("","", true, true);
    
    for(t = 1; t <= province.length; t++)
    {
        combo.options[t] = new Option(province[t-1].codice , province[t-1].nome, false, false);
    }

    combo.value = defaultValue;
//alert("-riempiProvince-end");    
}

function riempiListaCciaa(controlloName, defaultValue, filtraScaduti)
{
	//il comportamento di default e' che filtra le province
	if (filtraScaduti == undefined)
    	_riempiListaCciaa(controlloName, defaultValue, 0, true);
	else
	_riempiListaCciaa(controlloName, defaultValue, 0, filtraScaduti);
}

function _riempiListaCciaa(controlloName, defaultValue, formIndex, filtraScaduti)
{
//alert("-riempiProvince-begin");
    combo = document.forms[formIndex][controlloName];

    if (combo == undefined)
        alert("riempiListaCciaa - Controllo '"+controlloName+"' inesistente");

    if (filtraScaduti && cciaa_attive == undefined || !filtraScaduti && cciaa_tutte == undefined)
        caricaListaCciaa(filtraScaduti);

    var cciaa = (filtraScaduti) ? cciaa_attive : cciaa_tutte;

    combo.options.length = cciaa.length + 1;
    combo.options[0] = new Option("","", true, true);
    
    for(t = 1; t <= cciaa.length; t++)
    {
        combo.options[t] = new Option(cciaa[t-1].codice , cciaa[t-1].nome, false, false);
    }

    combo.value = defaultValue;
//alert("-riempiProvince-end");    
}


function riempiToponimi(controlloName, defaultValue)
{
    _riempiToponimi(controlloName, defaultValue, 0);
}

function _riempiToponimi(controlloName, defaultValue, formIndex)
{//alert("_riempiToponimi-begin");
    combo = document.forms[formIndex][controlloName];

    if (combo == undefined)
        alert("riempiToponimi - Controllo '"+controlloName+"' inesistente");

    if (toponimi == undefined)
        caricaToponimi();

    combo.options.length = toponimi.length + 1;
    combo.options[0] = new Option("","", true, true);
    
    for(t = 1; t <= toponimi.length; t++)
    {
        combo.options[t] = new Option(toponimi[t-1] , toponimi[t-1], false, false);
    }

    combo.value = defaultValue;
//alert("_riempiToponimi-begin");
}


function caricaStati(statiKey)
{
	var amp = String.fromCharCode(38);
    
    var queryStatiKey = "";
    if (statiKey != null && statiKey != '')
     queryStatiKey = amp + "key=" + statiKey;
    
    tempStati =[0];
    stati = processRequest("indirizzi?request=stati" + queryStatiKey).split('#');
       
    for(t=0; t < stati.length; t++)
    {
        temp = stati[t].split("|");

        tempStati[t] = new Object();
        tempStati[t].nome = trim(temp[0]);
        tempStati[t].codice = trim(temp[1]);
    }
    
    stati = new Object();
    stati = tempStati;

}

function caricaProvince(filtraScaduti)
{
    tempProvince =[0];
    var province = processRequest("indirizzi?request=province&attivi=" + filtraScaduti).split('#');
    
    for(t=0; t < province.length; t++)
    {
        temp = province[t].split("|");
        
        tempProvince[t] = new Object();
        tempProvince[t].nome = trim(temp[0]);
        tempProvince[t].codice = trim(temp[1]);
    }
    
    if (filtraScaduti)
    {
	    province_attive = new Object();
    	province_attive = tempProvince;
    }
	else    
    {
    	province_tutte = new Object();
    	province_tutte = tempProvince;
    }
}

function caricaListaCciaa(filtraScaduti)
{
    tempCciaa =[0];
    var cciaa = processRequest("indirizzi?request=listaCciaa&attivi=" + filtraScaduti).split('#');
    
    for(t=0; t < cciaa.length; t++)
    {
        temp = cciaa[t].split("|");
        
        tempCciaa[t] = new Object();
        tempCciaa[t].nome = trim(temp[0]);
        tempCciaa[t].codice = trim(temp[1]);
    }
    
    if (filtraScaduti)
    {
	    cciaa_attive = new Object();
    	cciaa_attive = tempCciaa;
    }
	else    
    {
    	cciaa_tutte = new Object();
    	cciaa_tutte = tempCciaa;
    }
}

function caricaToponimi()
{
    toponimi = [1];
    tempToponimi = processRequest("indirizzi?request=toponimi").split('#');

    toponimi[0] = 'VIA';
    index = 1;    
    for(t=0; t < tempToponimi.length; t++)
    {
    if (tempToponimi[t] != 'VIA')
        toponimi[index++] = trim(tempToponimi[t]);
    }
}

function recuperaAttivita()
{
  // Funzionamento poco ortodosso, ma va!
    try
    {
        downloader.open("GET", "attivita", false);
        downloader.send(null);    

        var temp = downloader.responseText.split("response>");
        var str = temp[1].split("</")[0];

       return str.split("\n");
    }
    catch ( ee)
    {
        alert("Ci sono stati problemi nel caricamento della pagina, provare a ricaricare la pagina. \n"+
        "Se il problema persiste contattare l'amministratore");
    }
}
