// JavaScript Document
var XMLHTTP;
var url
var combodaimpostare=""
var predP
var predA
function impostaicampi(partenza, arrivo){
	LocByNaz(document.getElementById("id_nat").value);
}

function cambia_tipoviaggio(tipo, partenza, arrivo){
	predP=partenza.toUpperCase();
	predA=arrivo.toUpperCase();
	if (tipo=='U'){
		document.getElementById("txtTU").value="U";
		//imposto italia
		for (var nn=0; nn<document.getElementById("id_nat").options.length; nn++){
			
			var element=document.getElementById("id_nat").options[nn];

			if (element.value==13){
				document.getElementById("id_nat").selectedIndex=nn;
				}
		}
		
		svuota("txta");
		document.getElementById("campiarrivo").style.display="none";
		document.getElementById("menuricerca01").src="/immagini/menu_ricerca_off_01.gif";
		document.getElementById("menuricerca02").src="/immagini/menu_ricerca_on_02.gif";
		//document.getElementById("id_nat").selectedIndex=0;
		LocByNaz(document.getElementById("id_nat").value);
	}else{
		document.getElementById("txtTU").value="T";
		document.getElementById("campiarrivo").style.display="block";
		document.getElementById("menuricerca01").src="/immagini/menu_ricerca_on_01.gif";
		document.getElementById("menuricerca02").src="/immagini/menu_ricerca_off_02.gif";
		LocByNaz(document.getElementById("id_nat").value);
	}
}

function cambiaggmm(){
	var meseanno=document.getElementById("txtmmaa").value;
	document.getElementById("txtmm").value=meseanno.substr(0,2);
	document.getElementById("txtaa").value=meseanno.substr(2,4);
}

function submit_ricerca(){
	if (document.getElementById("txtTU").value=="U"){
		document.getElementById("txta").options[document.getElementById("txta").options.length] = new Option(document.getElementById("txtp").value, document.getElementById("txtp").value);
	}
	var meseanno=document.getElementById("txtmmaa").value;
	var datatosend;
	datatosend=document.getElementById("txtgg").value + "/" + meseanno.substr(0,2) + "/" + meseanno.substr(2,4);
	//alert (datatosend);
	
	document.getElementById("txtdata").value=datatosend;
	document.getElementById("megaform").submit();
}

function chiama_http(){
	//XMLHTTP = processRequestAsync(serverPage, impostacombo, "get",xmlDoc, str);
	//XMLHTTP.open("GET", url, true);
	//XMLHTTP.send();
}

function LocByNaz(id_nazione){
	var data = new Date();
	strtime=data.getTime();
	url = "/comuni/ajax/utiajax.asp";
	parametri="strtime=" + strtime + "&tiporichiesta=LocByNaz&id_nazione=" + id_nazione + "&tipoviaggio=" + document.getElementById("txtTU").value + "&txtgg=" + document.getElementById("txtgg").value + "&txtmm=" + document.getElementById("txtmm").value + "&txtaa=" + document.getElementById("txtaa").value;
	combodaimpostare="txtp";
	XMLHTTP = processRequestAsync(url, impostacombo, "get",false, parametri);
	//chiama_http();
}

function DestByPart(partenza){
	var data = new Date();
	strtime=data.getTime();
	url = "/comuni/ajax/utiajax.asp";
	parametri="strtime=" + strtime + "&tiporichiesta=DestByPart&partenza=" + partenza + "&tipoviaggio=" + document.getElementById("txtTU").value + "&txtgg=" + document.getElementById("txtgg").value + "&txtmm=" + document.getElementById("txtmm").value + "&txtaa=" + document.getElementById("txtaa").value;
	combodaimpostare="txta";
	XMLHTTP = processRequestAsync(url, impostacombo, "get",false, parametri);
	//chiama_http();
}

function PutNazioni(){
	var data = new Date();
	strtime=data.getTime();
	url = "/comuni/ajax/utiajax.asp";
	parametri="strtime=" + strtime + "&tiporichiesta=PutNazioni&tipoviaggio=" + document.getElementById("txtTU").value + "&txtgg=" + document.getElementById("txtgg").value + "&txtmm=" + document.getElementById("txtmm").value + "&txtaa=" + document.getElementById("txtaa").value;
	combodaimpostare="id_nat";
	XMLHTTP = processRequestAsync(url, impostacombo, "get",false, parametri);
	//chiama_http();
}


function impostacombo(robaricevuta){
	var objcombo = document.getElementById(combodaimpostare);
	var risposta=robaricevuta;
	svuota(combodaimpostare);
	riempi(combodaimpostare, risposta);
}

function svuota(idobj){
	num_option=document.getElementById(idobj).options.length;
	for(a=num_option;a>=0;a--){
		document.getElementById(idobj).options[a]=null;
	}
}

function riempi(idobj, testo){
	var arrValori;
	var valcurr;
	var selectP=0;
	arrValori=testo.split("|");
	oggettocombo=document.getElementById(idobj);
	oggettocombo.options.length=0;
	for(i=0;i<arrValori.length;i++){
		valcurr=arrValori[i];
		oggettocombo.options[oggettocombo.options.length] = new Option(valcurr,valcurr);
		if (idobj=="txtp"){
			if (predP==valcurr.toUpperCase()){
				selectP=i;
				//alert(selectP);
				//DestByPart(valcurr);
			}
		}
		if (idobj=="txta"){
			if (predA==valcurr.toUpperCase()){oggettocombo.selectedIndex=i}
		}
	}
	if (idobj=="txtp"){
		//alert (selectP);
		oggettocombo.selectedIndex=selectP;
		DestByPart(document.getElementById("txtp").options[selectP].value)
	}
}

/*function RicercaTratte(Stringa, tipotratta, strtrattap, tastopigiato)
{
	if ((tastopigiato==9) || (tastopigiato==38) || (tastopigiato==40))
	{
		spostalista(tastopigiato, tipotratta);
		return;
	}else{
		indexselezionato=-1;
	}
    if (Stringa.length > 0)
    {
		spostaElement(tipotratta)
        var url = "/comuni/ajax/utiajax.asp?tiporichiesta=RicercaTratte&valToSearch=" + Stringa.toUpperCase() + "&tipotratta=" + tipotratta + "&trattap=" + strtrattap;
        XMLHTTP = RicavaBrowser(CambioStato);
        XMLHTTP.open("GET", url, true);
        XMLHTTP.send(null);
		mostraById("risultati");
    }
    else
    {
        document.getElementById("risultati").innerHTML = "";
    } 
}


function spostaElement(strtipotratta){
	if (strtipotratta=='A'){
		document.getElementById('risultati').style.left="300px";
	}else{
		document.getElementById('risultati').style.left="170px";
	}
}

function aggiornacampo(nomecampo, valtoset){
		document.getElementById(nomecampo).value=valtoset;
}
function nascondiById(nomecampo){
		document.getElementById(nomecampo).style.display='none'
}
function mostraById(nomecampo){
		document.getElementById(nomecampo).style.display='block'
}

function spostalista(keycode, strtipotratta){
//var KEY_CODE_RETURN=13;

	if (keycode==38){
		//freccia su
		var divve=document.getElementById("risultati")
		var table= divve.getElementsByTagName("table")[0];
		if (indexselezionato!=-1) table.rows[indexselezionato].cells[0].className="evidenzia";
		indexselezionato--;
		if(indexselezionato<=-1 ) indexselezionato=table.rows.length-1;
		table.rows[indexselezionato].cells[0].className="evidenziato";
	}else{
		if (keycode==40){
			var divve=document.getElementById("risultati")
			var table= divve.getElementsByTagName("table")[0];
			if (indexselezionato!=-1) table.rows[indexselezionato].cells[0].className="evidenzia";
			indexselezionato++;
			if(indexselezionato==table.rows.length ) indexselezionato=0;
			table.rows[indexselezionato].cells[0].className="evidenziato";
		}else if (keycode==9){
			var divve=document.getElementById("risultati")
			var table= divve.getElementsByTagName("table")[0];
			if (strtipotratta=='A'){
				document.getElementById('txtA').value=table.rows[indexselezionato].cells[0].innerHTML;
			}else{
				document.getElementById('txtP').value=table.rows[indexselezionato].cells[0].innerHTML;
			}
		}
	}
	return;
}
function CambioStato()
{
    if (XMLHTTP.readyState == 4)
    {
        var R = document.getElementById("risultati");
        R.innerHTML = XMLHTTP.responseText;
    }
}

*/

// da comincia la roba x il browser
function RicavaBrowser(QualeBrowser)
{
    if (navigator.userAgent.indexOf("MSIE") != (-1))
    {
        var Classe = "Msxml2.XMLHTTP";
        if (navigator.appVersion.indexOf("MSIE 5.5") != (-1));
        {
            Classe = "Microsoft.XMLHTTP";
        } 
        try
        {
            OggettoXMLHTTP = new ActiveXObject(Classe);
            OggettoXMLHTTP.onreadystatechange = QualeBrowser;
            return OggettoXMLHTTP;
        }
        catch(e)
        {
            alert("Errore: l'ActiveX non verrà eseguito!");
        }
    }
    else if (navigator.userAgent.indexOf("Mozilla") != (-1))
    {
        OggettoXMLHTTP = new XMLHttpRequest();
        OggettoXMLHTTP.onreadystatechange = QualeBrowser;
        //OggettoXMLHTTP.onerror = QualeBrowser;
        return OggettoXMLHTTP;
    }
    else
    {
        alert("Browser non supportato!");
    }
}

	/** Function to create an XMLHttp Object.
	 * 
	 *     This function provide to createa valid instance of XMLHttpRequest object.
	 *     First, check the browser and then choices which kind of object has to create.
	 *
	 *     parameters: void
	 */
	 /*
	  * xmlhttprequest exception code 0x80004005:
	  * si verifica quando si passa come serverPage solo il nome della pagina, è meglio passare tutta la url completa
	  */
var XHRObjects=new Array();
	function getXMLHttp (){
		//Create a boolean variable to check for a valid microsoft active X instance.
		var xmlhttp = false;
		
		//Check if we are using internet explorer.
		try {
			//If the javascript version is greater than 5.
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			//If not, then use the older active x object.
			try {
				//If we are using internet explorer.
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				//Else we must be using a non-internet explorer browser.
				xmlhttp = false;
			}
		}
		
		//If we are using a non-internet explorer browser, create a javascript instance of the object.
		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
			xmlhttp = new XMLHttpRequest();
		}
		
		return xmlhttp;
	}
	
	

//fa una richiesta è mette il risultato in innerHTML di un oggetto HTML
	function processRequest(serverPage, obj, getOrPost, str){
		xmlhttp = getXMLHttp ();
		if(serverPage.slice(0,1)!="/") serverPage="/"+serverPage;
		try{BASE_HOST;serverPage=BASE_HOST+serverPage;}catch(e){}
		if (getOrPost.toUpperCase() == "GET"){
			xmlhttp.open("GET", serverPage+'?'+str, true);
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					obj.innerHTML = xmlhttp.responseText;
				}
			}
		
		xmlhttp.send(null);
		} else {
			xmlhttp.open("POST", serverPage, true);
			xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4) {
					if(xmlhttp.responseText != 'ok') {
						eval(xmlhttp.responseText);
					} else {
						window.location.reload();
						
					}
				}
			}
		xmlhttp.send(str);
		}
	}
	
	function processRequestAsync(serverPage, callbackfunc, getOrPost,xmlDoc, str){	
		if(xmlDoc==null) xmlDoc=true;
		var xmlhttp=getXMLHttp();
		var tmp_res;
		if(serverPage.slice(0,1)!="/") serverPage="/"+serverPage;
		try{BASE_HOST;serverPage=BASE_HOST+serverPage;}catch(e){}
		if (getOrPost.toUpperCase() == "GET"){
			xmlhttp.open("GET", serverPage+'?'+str, true);
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					if(xmlDoc){
						tmp_res = xmlhttp.responseXML;
					}else{
						tmp_res = xmlhttp.responseText;
					}
					callbackfunc(tmp_res);
				}
			}
		
		xmlhttp.send(null);
		} else {
			try{
				xmlhttp.open("POST", serverPage, true);
			}catch(e){
				alert(e.message);
				
			}
			xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4) {
					if(xmlDoc){
						tmp_res = xmlhttp.responseXML;
					}else{
						tmp_res = xmlhttp.responseText;
					}
					callbackfunc(tmp_res);
				}
			}
		xmlhttp.send(str);
		}
	}
	
/*
 * fa una richiesta [GET(method="GET") o POST(method="POST")] alla PAGINA serverPage
 * in MODALITA' SINCORNA e restituisce l'XML di risposta
 * 
 */
	function processRequestSync(serverPage, data, method, xmlDoc,debug){
		if(xmlDoc==null) xmlDoc=true;
		if(serverPage.slice(0,1)!="/") serverPage="/"+serverPage;
		try{BASE_HOST;serverPage=BASE_HOST+serverPage;}catch(e){}
		xmlhttp = getXMLHttp ();
		var tmp_res;
		switch(method.toUpperCase()){
			case "POST":
				try{
					xmlhttp.open("POST", serverPage, false);
				}catch(e){
					alert(e.message);
				}
				xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
				xmlhttp.send(data);
				break;
			
			case "GET":
				xmlhttp.open("GET", serverPage+"?"+data, false);
				xmlhttp.send(null);
				break;
			
			default:alert("method in XHR not valid");break;
		}
				
		if(xmlDoc){
			tmp_res=xmlhttp.responseXML;
		}else{
			tmp_res=xmlhttp.responseText;
		}
		if(debug) mk_debugger(xmlhttp.responseText);
		
		return tmp_res;
	}
	
	
	

function mk_debugger(responseData){
	var D=document.createElement('div');
	var A=document.createElement('a');
	A.href='javascript:void(0);';
	A.innerHTML='chiudi';
	A.setAttribute('onclick','javascript:kill_debugger(this.parentNode);');
	
	D.style.position='absolute';
	D.style.width='350px';
	//D.style.height='600px';
	D.style.top='50px';
	D.style.left='600px';
	D.style.border='1px solid';
	D.style.overflow='hidden';
	D.style.zIndex=200;
	D.appendChild(A);
	D.innerHTML+='<br>'+responseData;
	D=document.getElementsByTagName('body')[0].appendChild(D);
	return D;
}

function kill_debugger(D){
	document.getElementsByTagName('body')[0].removeChild(D);
}


function getParamsValues(params){
	var strData="";
	for(p_name in params) strData+=p_name+"="+eval("params."+p_name)+"&";
	return strData;
}

function getFormValues(theform){
		switch(typeof(theform)){
			case "string":
			var form = window.document.forms[theform];
			if(!form) form=document.getElementById(theform);
			break;
			
			case "object":
			var form=theform;
			break;
		}
		if(!form) {
			alert("ERROR in GetFormValues: Form not identified!");
			return 0;
		}
		
		var formData = '';
		
		try {
			for(var i= 0; i < form.length; i++) {
				if(form.elements[i].name)
					switch(form.elements[i].getAttribute("type")) {
						case "checkbox":
						if(form.elements[i].checked) {
							form.elements[i].value = "checked";
						} else {
							form.elements[i].value = "unchecked";
						}	
						formData += form.elements[i].name + "=" + form.elements[i].value + "&";
						break;
						
						case "radio":
						if(!form.elements[i].checked || form.elements[i].disabled) break;
						formData += form.elements[i].name + "=" + form.elements[i].value + "&";
						break;
						
						default:
						formData += form.elements[i].name + "=" + form.elements[i].value + "&";
						break;
					}
				
							
	//		formData += form.elements[i].name + "=" + escape(form.elements[i].value) + "&";
			
			}			
		}catch(e) {
			var str = "<br /><b>Catch into getFormValues function </b><br />";
			document.getElementById('error').innerHTML = str;
		}
	/*
		if(checkURL(formData)) {
			return removeBlankSpace(formData);	
		} else {
			document.getElementById('error').innerHTML = '<br>sended url is not valid<br />';			
		}	
		*/
		return formData;	
	}