var xmlDocApt = null;
var collectionApt = new Array();
var myDays= ["Dom","Lun","Mar","Mer","Gio","Ven","Sab","Dom"];

function aeroportiPart(a,b,c){
	this.apt = a
	this.maPart = b
	this.gPart = c
}

	function selUnselFilter(obj){
	    if (obj.checked){ 
			obj.value = "Y";
		}
	    else {
			obj.value = "N";
		}
	};	

function loadCollApt(n){
	
	collectionApt = new Array();
	var y = 0;
	
	for(var i=0;i<n.childNodes.length;i++){
		var x = n.childNodes[i];
		if (x.nodeName == 'APT') {
			var aeroporto = x.firstChild.nodeValue;
			var code = x.firstChild.nodeValue.substring(0,x.firstChild.nodeValue.indexOf(';')).trim();
			
			for(var p=0;p<n.childNodes.length;p++){
				if ( code == n.childNodes[p].nodeName) {
				    maArray = new Array();
				    gArray = new Array();
				    var count = 0;
				    for (var node=0;node<n.childNodes[p].childNodes.length;node++) {			    	
				    	//Workaround per Mozilla
				    	if (n.childNodes[p].childNodes[node].nodeName != '#text') {
					    	for(var z=0;z<n.childNodes[p].childNodes[node].attributes.length;z++){
					     		var atrib = n.childNodes[p].childNodes[node].attributes[z];
					     		if (atrib.nodeName == 'ID') {
					     			maArray[count] = atrib.nodeValue;
					     		}
					     		else if (atrib.nodeName == 'DD') {
					     			gArray[count] = atrib.nodeValue;
					     		}
					    	}
					    	count++;
					    }
					}
				    var aptP = new aeroportiPart;
				    aptP.apt = aeroporto;
				    aptP.maPart = maArray;
				    aptP.gPart = gArray;
					collectionApt[y] = aptP;					
					break;
				}
			}
			y++;
		}
	}

	$('#aptPar').removeOption(/./); 
	$('#giornoP').removeOption(/./); 
	$('#meseAnnoP').removeOption(/./); 
	$('#durata').removeOption(/./);

	var aptSelected = document.RqDatiVGTOForm.aptPar.value;
	var gSelected = document.RqDatiVGTOForm.giornoP.value;
	var maSelected = document.RqDatiVGTOForm.meseAnnoP.value;
	var durataSelected = document.RqDatiVGTOForm.durata.value;

	for(var p=0;p<collectionApt.length;p++){
		var code = collectionApt[p].apt.substring(0,collectionApt[p].apt.indexOf(';')).trim();
		var text = collectionApt[p].apt.substring(collectionApt[p].apt.indexOf(';')+1);
		text = text.substr(0,1) + text.substr(1).toLowerCase();
		document.form_vacanze.aptPar.options[p] = new Option(text, code);

		//if (code == 'ALL') {
		if (code == document.RqDatiVGTOForm.aptPar.value) {
			
			$('#aptPar').val(code); 
			
			var idx = 0;
			for(var k=0;k<collectionApt[p].maPart.length;k++){

				//Workaround per Mozilla
				if (collectionApt[p].maPart[k] == undefined)
					k++;
				else if (collectionApt[p].maPart[k] == '') {
					k++;
				}
					
				var code = collectionApt[p].maPart[k].substring(0,collectionApt[p].maPart[k].indexOf(';'));
				var text = collectionApt[p].maPart[k].substring(collectionApt[p].maPart[k].indexOf(';')+1);
				
				var sAnno = "20" + code.substring(2);
				var sMese = code.substring(0,2);
				document.form_vacanze.meseAnnoP.options[k] = new Option(text + " " + sAnno, code);
				
				if (code == maSelected) {
					$('#meseAnnoP').val(code);

					var dd = collectionApt[p].gPart[k].split("|");
					for (var h=0;h<dd.length;h++) {
						var d = dd[h].split(";");
						for (var m=0;m<d.length;m++) {
							if (m==0) {
								var dtI = new Date(sAnno, sMese-1, d[m]); 						
								thisDay=myDays[dtI.getDay()];
								document.form_vacanze.giornoP.options[h] = new Option(thisDay + " " + d[m], d[m]);
								if (d[m] == gSelected)
									$('#giornoP').val(d[m]); 
							}
							else { 
								if (d[0] == gSelected) {									
									document.form_vacanze.durata.options[m-1] = new Option(d[m] + " Giorni", d[m]);
									if (d[m] == durataSelected)
										$('#durata').val(d[m]); 
								}
							}
						}
					}
				} else if (maSelected==0) {
					if (idx == 0) {
						$('#meseAnnoP').val(code);
						var dd = collectionApt[p].gPart[k].split("|");
						for (var h=0;h<dd.length;h++) {
							var d = dd[h].split(";");
							for (var m=0;m<d.length;m++) {
								if (m==0) {
									var dtI = new Date(sAnno, sMese-1, d[m]); 						
									thisDay=myDays[dtI.getDay()];
									document.form_vacanze.giornoP.options[h] = new Option(thisDay + " " + d[m], d[m]);
									$('#giornoP').val(d[m]); 
								}
								else { 
									document.form_vacanze.durata.options[m-1] = new Option(d[m] + " Giorni", d[m]);
									$('#durata').val(d[m]); 
								}
							}
						}
					}
				}
				idx = idx+1;
			}
			if (maSelected==0) {
				document.form_vacanze.meseAnnoP.selectedIndex = 0;
				$('#meseAnnoP').change();
			}
		}
	}

}

$(document).ready(function() {

	// popAlpi HELP
	jQuery('.popAlpiSearch').popAlpiSearch();
	jQuery('#poaltoSearch').livequery(function(){
		jQuery(this).bgiframe();
	});
	
	document.RqDatiVGTOForm.filtriSel.value = "";
	jQuery("span[name^='val_box_']").each(
		function()
		{
			var keyItem = this.getAttribute("keyItem");
			document.RqDatiVGTOForm.filtriSel.value = document.RqDatiVGTOForm.filtriSel.value + keyItem + "|";
		}
	)

	    var chiamaWsApt = function(){
			var messaggi = [];

			if (document.RqDatiVGTOForm.marchio.value != null)
				var param= "/EBookingWeb/SEAAPTVGTO?tipoScelto=" + document.RqDatiVGTOForm.marchio.value + "&keyd=" + document.form_vacanze.keyd.value + "&tipoFlusso=" + document.form_vacanze.flusso.value;
			else
				var param= "/EBookingWeb/SEAAPTVGTO?tipoScelto=" + document.RqDatiVGTOForm.tipoVacanza.value + "&keyd=" + document.form_vacanze.keyd.value + "&tipoFlusso=" + document.form_vacanze.flusso.value;
	
			$.ajax({
				url: param,
				type: 'get',
				dataType: 'xml',
				success: function(xmlData){
				
					//$('#blocker, #loader').remove();
					data = xmlData;
					// msg-list
					$(data).find('msg-list > msg').each(function(i){
						messaggi[i] = {};
						messaggi[i]['code'] = $(this).find('code').text();
						messaggi[i]['text'] = $(this).find('text').text();
					});
					
					if (messaggi[0].code == '0' && messaggi[0].text == 'Completed.') {
						$('RELATIONS_VGTO', data).each(function(i){
							xmlDocApt=this;
							loadCollApt(xmlDocApt);
						});
						//jQuery($('#PARTENZE')).attr('style','display: block;');
						document.getElementById("VIAGGIATORI").style.display = 'block';
						if ($('#under18').val()==1) {
							document.getElementById("eta_under_1").style.display = 'block';
							document.getElementById("eta_under_2").style.display = 'none';
						} else if ($('#under18').val()==2) {
							document.getElementById("eta_under_1").style.display = 'block';
							document.getElementById("eta_under_2").style.display = 'block';
						} else {
							document.getElementById("eta_under_1").style.display = 'none';
							document.getElementById("eta_under_2").style.display = 'none';
						}						
					}	//	fine if (messaggi.code && messaggi.text)
						//	se si ricevono messaggi diversi da "0" e "Completed." dalla servlet
					else {
						//jQuery($('#PARTENZE')).attr('style','display: none;');
						jQuery($('#VIAGGIATORI')).attr('style','display: none;');
						document.getElementById("eta_under_1").style.display = 'none';
						document.getElementById("eta_under_2").style.display = 'none';
						//alert("Errore nella ricezione dei dati.");
						//alert("Destinazione non valida.");
						$('#aptPar').removeOption(/./); 
						$('#giornoP').removeOption(/./); 
						$('#meseAnnoP').removeOption(/./); 
						$('#durata').removeOption(/./);
						alert("Errore nella ricezione dei dati.");
					}
				},	// fine success				
				error: function(){
					//jQuery($('#PARTENZE')).attr('style','display: none;');
					jQuery($('#VIAGGIATORI')).attr('style','display: none;');
					document.getElementById("eta_under_1").style.display = 'none';
					document.getElementById("eta_under_2").style.display = 'none';
					alert("ERRORE: Impossibile contattare il server. Provare a ricaricare la pagina.");
					$('#aptPar').removeOption(/./); 
					$('#giornoP').removeOption(/./); 
					$('#meseAnnoP').removeOption(/./); 
					$('#durata').removeOption(/./);				
					alert("ERRORE: Impossibile contattare il server. Provare a ricaricare la pagina.");
				}	// fine error
			});
		};

	jQuery("div[id^='eta_under_']").each(
		function()
		{
			if ( jQuery($('#under18')).val() == 1 ) {
				jQuery($('#eta_under_1')).attr('style','display: block;');
				//jQuery($('#eta_under_1')).attr('style','margin: 0 0 0 10px;');
				}
			else if ( jQuery($('#under18')).val() == 2 ) {
				jQuery($('#eta_under_1')).attr('style','display: block;');
				//jQuery($('#eta_under_1')).attr('style','margin: 0 0 0 10px;');
				jQuery($('#eta_under_2')).attr('style','display: block;');
			}
		}
	)
	
    jQuery("div[name^='applicaFiltri']").bind('click',function(e){
	    var itemKey = jQuery(this).attr("paramItemKey");
	    var grKey   = jQuery(this).attr("paramGrKey");
		
		
		var strFiltriRq = "";
		var strSepDettFiltri = "$";		
		
		strFiltriRq = grKey + strSepDettFiltri + itemKey; 
		
		scroll(0,0);
	 	setOpacityVG('#containerOpacity');

		$('#divLoader').attr('style','display: inline;');	

		document.RqDatiVGTOForm.method.value="applicaFiltri";	
		document.RqDatiVGTOForm.filtri.value = strFiltriRq;
				
		document.RqDatiVGTOForm.submit();	

	});

    jQuery("img[name^='clearFilter']").bind('click',function(e){
	    
	    var itemKey = jQuery(this).attr("paramItemKey");
	    var grKey   = jQuery(this).attr("paramGrKey");
		
	    var strFiltriRq = "";
		var strSepDettFiltri = "_";		
		
		strFiltriRq = grKey + strSepDettFiltri + itemKey; 
		
		document.RqDatiVGTOForm.filtriSel.value = document.RqDatiVGTOForm.filtriSel.value.replace(strFiltriRq + '|','');
		
		scroll(0,0);
	 	setOpacityVG('#containerOpacity');

	 	$('#divLoader').attr('style','display: inline;');
	 	
	 	if (document.RqDatiVGTOForm.filtriSel.value == '') {
			document.RqDatiVGTOForm.method.value="rimuoviFiltri";	
			document.RqDatiVGTOForm.filtri.value = "";	 		
	 	} else {
			document.RqDatiVGTOForm.method.value="applicaFiltri";	
			document.RqDatiVGTOForm.filtri.value = document.RqDatiVGTOForm.filtriSel.value;
	 	}
		
		document.RqDatiVGTOForm.submit();	

	});
    
	$('#hotelFilter').change(function(){
	    var itemKey = $(this).val();
	    var grKey   = jQuery(this).attr("paramGrKey");
		
		var strFiltriRq = "";
		var strSepDettFiltri = "$";		
		
		strFiltriRq = grKey + strSepDettFiltri + itemKey; 
		
		scroll(0,0);
	 	setOpacityVG('#containerOpacity');

		$('#divLoader').attr('style','display: inline;');	

		document.RqDatiVGTOForm.method.value="applicaFiltri";	
		document.RqDatiVGTOForm.filtri.value = strFiltriRq;
		document.RqDatiVGTOForm.submit();	

	});

	$('#clearAllFilter').click(function(){
		scroll(0,0);
	 	setOpacityVG('#containerOpacity');

		$('#divLoader').attr('style','display: inline;');	

		document.RqDatiVGTOForm.method.value="rimuoviFiltri";	
		document.RqDatiVGTOForm.filtri.value = "";
		document.RqDatiVGTOForm.submit();	

	});
	
	$('#aptPar').change(function(){
	
		$('#descrAptPart').val(document.form_vacanze.aptPar.options[document.form_vacanze.aptPar.selectedIndex].text);
		$('#giornoP').removeOption(/./); 
		$('#meseAnnoP').removeOption(/./); 
		$('#durata').removeOption(/./); 
		for(var p=0;p<collectionApt.length;p++){
			var code = collectionApt[p].apt.substring(0,collectionApt[p].apt.indexOf(';'));
			if (code == this.value){
				for(var k=0;k<collectionApt[p].maPart.length;k++){
					var code = collectionApt[p].maPart[k].substring(0,collectionApt[p].maPart[k].indexOf(';'));
					var text = collectionApt[p].maPart[k].substring(collectionApt[p].maPart[k].indexOf(';')+1);

					var sAnno = "20" + code.substring(2);
					var sMese = code.substring(0,2);
					$('#meseAnnoP').addOption(code, text + " " + sAnno,false);
					
					if (k==0) {
						var dd = collectionApt[p].gPart[k].split("|");
						for (var h=0;h<dd.length;h++) {
							var d = dd[h].split(";");
							for (var m=0;m<d.length;m++) {
								if (m ==0) {
									var dtI = new Date(sAnno, sMese-1, d[m]); 						
									thisDay=myDays[dtI.getDay()];
									$('#giornoP').addOption(d[m], thisDay + " " + d[m],false);
								}
								else { 
									if (h==0) {
										$('#durata').addOption(d[m], d[m] + " Giorni",false);
									}
								}
							}
						}
					}
				}
			}
		}
	});

	$('#giornoP').change(function(){
		$('#durata').removeOption(/./); 
		for(var p=0;p<collectionApt.length;p++){
			var code = collectionApt[p].apt.substring(0,collectionApt[p].apt.indexOf(';'));
			if (code == $('#aptPar').val() ){
				for(var k=0;k<collectionApt[p].maPart.length;k++){
					var code = collectionApt[p].maPart[k].substring(0,collectionApt[p].maPart[k].indexOf(';'));
					if (code == $('#meseAnnoP').val()) {			
						var dd = collectionApt[p].gPart[k].split("|");
						for (var h=0;h<dd.length;h++) {
							var d = dd[h].split(";");	
							for (var m=0;m<d.length;m++) {
								if (d[0]==this.value) {
									if (m>0)
										$('#durata').addOption(d[m], d[m] + " Giorni",false);
								}
							}
						}
					}
				}
			}
		}
	});

	$('#meseAnnoP').change(function(){
		$('#giornoP').removeOption(/./); 
		$('#durata').removeOption(/./); 
		for(var p=0;p<collectionApt.length;p++){
			var code = collectionApt[p].apt.substring(0,collectionApt[p].apt.indexOf(';'));
			if (code == $('#aptPar').val()){
				for(var k=0;k<collectionApt[p].maPart.length;k++){
					var code = collectionApt[p].maPart[k].substring(0,collectionApt[p].maPart[k].indexOf(';'));
					var sAnno = "20" + code.substring(2);
					var sMese = code.substring(0,2);
					if (code==this.value) {
						var dd = collectionApt[p].gPart[k].split("|");
						for (var h=0;h<dd.length;h++) {
							var d = dd[h].split(";");
							for (var m=0;m<d.length;m++) {
								if (m ==0) {
									var dtI = new Date(sAnno, sMese-1, d[m]); 						
									thisDay=myDays[dtI.getDay()];
									$('#giornoP').addOption(d[m], thisDay + " " + d[m],false);
								}
								else { 
									if (h==0) {
										$('#durata').addOption(d[m], d[m] + " Giorni",false);
									}
								}
							}
						}
					}
				}
			}
		}
	});

	
	$('#btn_trova').click(function(){
		$('#form_check').remove();
		var messaggio = '<div class="spacer35boxModRicErr"> <p>Errori nella compilazione del form:</p>';
		
		var adt = parseInt($('#adulti').val());
		var und = parseInt($('#under18').val());
		var undeu1 = parseInt($('#eu1').val());
		var undeu2 = parseInt($('#eu2').val());

		/*if ( $('#aptPar').val() == '') 
			messaggio += '</BR> - Inserire l\'Aeroporto di partenza.';
		if ( $('#giornoP').val() == '') 
			messaggio += '</BR> - Inserire il Giorno di partenza.';
		if ( $('#meseAnnoP').val() == '') 
			messaggio += '</BR> - Inserire il Mese e l\'Anno di partenza.';
		if ( $('#durata').val() == '') 
			messaggio += '</BR> - Inserire la durata della vacanza.';		*/
		if ( adt+und > 4)
			messaggio += '</BR> - I viaggiatori non possono essere pi&ugrave; di 4.';
			
		if ( und==2 && (undeu1 < 0 || undeu2 < 0)) {
			if (undeu1 < 0 && undeu2 < 0) {
				messaggio += '</BR> - Inserire le et&agrave; mancanti.';
			} else {
				messaggio += '</BR> - Inserire l\'et&agrave; mancante.';
			}
		}
		if ( und==1 && undeu1 < 0)
			messaggio += '</BR> - Inserire l\'et&agrave; mancante.';


/*
		if ( und==2 && (undeu1 < 0 || undeu2 < 0)) {
			if (undeu1 < 0 && undeu2 < 0) {
				messaggio += '</BR> - Inserire le et&agrave; mancanti.</div>';
			} else {
				messaggio += '</BR> - Inserire l\'et&agrave; mancante.</div>';
			}
		}
		if ( und==1 && undeu1 < 0)
			messaggio += '</BR> - Inserire l\'et&agrave; mancante.</div>';
*/
		
		if (messaggio == '<div class="spacer35boxModRicErr"> <p>Errori nella compilazione del form:</p>') {
			messaggio = '<p>Form incompleto:</p>';
		} else {
			messaggio += '</div>';
		}

		if (messaggio == '<p>Form incompleto:</p>'){
		
			//Gestendo il scegli = -1 questo valore non posso passarlo alla form sucessiva 
			if ( und==0) {
				$('#eu1').val("0");
				$('#eu2').val("0");
			} else {
				if (und==1) {
					$('#eu2').val("0");
				}
			}	
			
			document.RqDatiVGTOForm.method.value = "ricerca";	
			document.RqDatiVGTOForm.flusso.value = "VGTO";
			if ($('#marchio').val() != null) {
				document.RqDatiVGTOForm.marchio.value = $('#marchio').val();
			}
			if ($('#budget').val() != null) {
				document.RqDatiVGTOForm.budget.value = $('#budget').val();
			}			
			document.RqDatiVGTOForm.aptPar.value = $('#aptPar').val();
			document.RqDatiVGTOForm.descrAptPart.value = $('#descrAptPart').val();
			document.RqDatiVGTOForm.giornoP.value = $('#giornoP').val();
			document.RqDatiVGTOForm.meseAnnoP.value = $('#meseAnnoP').val();
			document.RqDatiVGTOForm.durata.value = $('#durata').val();
			
			document.RqDatiVGTOForm.adulti.value = $('#adulti').val();
			document.RqDatiVGTOForm.under18.value = $('#under18').val();			
			if ($('#eu1').val() != '-1') {
				document.RqDatiVGTOForm.eu1.value = $('#eu1').val();
			}
			if ($('#eu2').val() != '-1') {
				document.RqDatiVGTOForm.eu2.value = $('#eu2').val();
			}		

			createCookie("provenienzaNavigatore","Motorino",1);
			
			document.RqDatiVGTOForm.submit();	
					
			return true;
		}
		else {
			$('<div id="form_check"></div>') 
			//('<div id="form_check" class="formBox"></div>') 
			.html(messaggio)
			.insertAfter('#VIAGGIATORI');
			return false;
		}
	});

	$('#under18').change(function(){
		var $this = $(this);
		var n = + $this.val();
		if (n == 0) {	
			$('#eta_under_1').hide();
			$('#eta_under_2').hide();
			$('#eu1').val("-1");
			$('#eu2').val("-1");
		} else if (n==1) {
			$('#eta_under_1').show();
			$('#eta_under_2').hide();
			$('#eu2').val("-1");
		} else {
			$('#eta_under_1').show();
			$('#eta_under_2').show();
		}
	});
	
	/* Gestendo il scegli = -1 questo valore viene risettato a -1 quando ritorno indietro col browser */        
	var backunder18 = parseInt($('#under18').val());
	
	if ( backunder18==0) {
		$('#eu1').val("-1");
		$('#eu2').val("-1");
		$('#eta_under_1').hide();
		$('#eta_under_2').hide();		
	} else {
		if (backunder18==1) {
			$('#eu2').val("-1");
			$('#eta_under_2').hide();			
		}
	}		
	
	chiamaWsApt();
});

