$(document).ready(function(){

	// popAlpi HELP
	jQuery('.popAlpiSearch').popAlpiSearch();
	jQuery('#poaltoSearch').livequery(function(){
		jQuery(this).bgiframe();
	});	


	//	variabili utilizzate nel parsing dell'xml
	var messaggi = [];
	
	var chiamaWs = function(tipoVg){

		$.ajax({
			url: '/EBookingWeb/SEASOVO',
			type: 'post',
			data: 'tipoVg='+tipoVg ,
			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.') {
					$('P000001', data).each(function(i){
						xmlDoc=this;
						// funzione per inserimento livello T = 1
						loadLev(this);
						loadDest('partenza','','1',tipoVg);
						setComboPar('form_charter');
					});
					$('R000001', data).each(function(i){
						xmlDoc=this;
						// funzione per inserimento livello T = 1
						//loadLev(this);
						
						// DA modificare con allineamento WS MARY DESTINATION BOXES AEROPORTI ITALIANI
						//String nameNode = "";
						if (tipoVg == 'OWR'){
							var node=xmlDoc.getElementsByTagName("P000001")[0];
							if (document.forms['form_charter'].keydP.value != null && document.forms['form_charter'].keydP.value != "")
								nameNode = "P" + document.forms['form_charter'].keydP.value.substring(7);
							else
								nameNode = "P";
						} else {
							var node=xmlDoc.getElementsByTagName("P000276")[0];
							nameNode = node.nodeName;
						}
						loadAllDest('destin',nameNode,'1');
						setComboAllArr('form_charter');
						if (nameNode != "P")
							setHiddenKeydArr('destin','form_charter');						
					});				
				}	//	fine if (messaggi.code && messaggi.text)
				
					//	se si ricevono messaggi diversi da "0" e "Completed." dalla servlet
				else alert("Errore nella ricezione dei dati.");
			},	// fine success
			error: function(){
				alert("ERRORE: Impossibile contattare il server. Provare a ricaricare la pagina.");
			}	// fine error
		});
	};

	$('.tipoVg').click(impostaRitorno);

	function impostaRitorno() {

		var valTipoVg = $(this).val(); 
        
        if(valTipoVg=="RT"){
	       jQuery($('#charter_div_ritorno')).attr('style','clear: left;');
           return;
        }else{
           jQuery($('#charter_div_ritorno')).attr('style','visibility: hidden;');
           return;        
        }
	};




	// popAlpi HELP
//	jQuery('.popAlpi').popAlpi();
//	jQuery('#poalto').livequery(function(){
//		jQuery(this).bgiframe();
//	});	

	//	variabili utilizzate nel parsing dell'xml
	var messaggi	= [];
	
	//	datepicker
	//	inizializzo le variabili per il calcolo delle date
	var laData = new Date();
	var gg = laData.getDate();
	var mm = laData.getMonth();
	var aaaa = laData.getFullYear();
	var oggi = gg + '/' + mm + '/' + aaaa;

	var fraUnAnno = new Date();
	fraUnAnno.setDate(laData.getDate() + 365);

	var ggOggi = gg;
	var mmOggi = mm+1;
	var ggOggiStr = ggOggi.toString();
	var mmOggiStr = mmOggi.toString();

	if (ggOggiStr.length==1) 
		ggOggiStr = '0' + ggOggiStr;
	if (mmOggiStr.length==1) 
		mmOggiStr = '0' + mmOggiStr;
	
	var maOggi = mmOggiStr  + '/' + aaaa;

	var ggVoloA = $('#v_g_a').val(); 
	var mmVoloA = $('#volo_m_a').val(); 
	var aaVoloA = $('#volo_a_a').val(); 
	
	//	popolo le select per giorno e mese/anno
	//	gg
	for (var t = 1; t < 32; t++) {
		
		var day, valday;
		if (t < 10) day = valday = '0' + t;
		else day = valday = t;
		
		var optVoloA = '<option value="' + valday + '">' + day + '</option>';
		
		if (ggVoloA=='' && ggOggiStr==day) {
			$(optVoloA).attr('selected','selected').appendTo('#volo_g_a');
			$('#v_g_a').val(day); 
		}
		else if(valday==ggVoloA)
			$(optVoloA).attr('selected','selected').appendTo('#volo_g_a');
		else
			$(optVoloA).appendTo('#volo_g_a');
		
	}
	//	mm/aaaa
	for (var t = 1; t < 14; t++) {
		var mese = mm;
		var anno = ((mese + t) > 12) ? (aaaa + 1) : (aaaa);
		mese = ((mese + t) > 12) ? (mese + t - 12) : (mese + t);
		if (mese < 10) mese = '0' + mese;
		var ma = mese  + '/' + anno;
		
		var optVoloA = '<option value="' + anno  + mese + '">' + ma + '</option>';

		if (aaVoloA=='' && mmVoloA=='' && maOggi==ma) {
			$(optVoloA).attr('selected','selected').appendTo('#volo_ma_a');
			$('#volo_m_a').val(mese); 
			$('#volo_a_a').val(anno); 
		}
		else if (anno==aaVoloA && mese==mmVoloA)
			$(optVoloA).attr('selected','selected').appendTo('#volo_ma_a');
		else
			$(optVoloA).appendTo('#volo_ma_a');

	}
	
	//Se la data di arrivo in Hotel č vuota
	if (ggVoloA=='' && aaVoloA=='' && mmVoloA=='')
		$('#volo_h_data_a').val(ggOggiStr + "/" + mmOggiStr + "/" + aaaa);

	// Prevent selection of invalid dates through the select controls 
	function checkLinkedDays() {
		var mese = jQuery(this).val().substring(4);
		var anno = jQuery(this).val().substring(0,4);
		
		$('#volo_m_a').val(mese); 
		$('#volo_a_a').val(anno); 
		
		var daysInMonth = 32 - new Date(anno, mese - 1, 32).getDate(); 
		$(this).prev('select').find('option').attr('disabled', ''); 
		$(this).prev('select').find('option:gt(' + (daysInMonth) +')').attr('disabled', 'disabled'); 
		if ($(this).prev('select').val() > daysInMonth) { 
			$(this).prev('select').val(daysInMonth); 
			$('#v_g_a').val(daysInMonth); 
		} 
		
	};
	
	$('#volo_ma_a').change(checkLinkedDays);
	
	$('#volo_g_a').change(function(){
		$('#v_g_a').val($('#volo_g_a').val());
	});
	
	function readLinked() { 
		var _temp_id = this.id.split('_');
		var ma = jQuery('#' + _temp_id[0] + '_ma_' + _temp_id[3]).val();
		var g = jQuery('#' + _temp_id[0] + '_g_' + _temp_id[3]).val();

		if(ma!="" && g!=""){
			jQuery('#' + this.id).val( 
				g + '/' + ma.substr(4) + '/' + ma.substr(0,4)  
			); 
		}
		return {}; 
	};
	function updateLinked(date) {
		var _temp_id = this.id.split('_');
		var _anno = + date.substring(6, 10);
		var _mese = date.substring(3, 5);

		jQuery('#' + _temp_id[0] + '_ma_' + _temp_id[3]).val(date.substring(3, 5) + '/' + date.substring(6, 10)).change(); 
		jQuery('#' + _temp_id[0] + '_g_' + _temp_id[3]).val(date.substring(0, 2));
		jQuery('#v_g_' + _temp_id[3]).val(date.substring(0, 2));

		$('#volo_m_a').val(_mese);
		$('#volo_a_a').val(_anno)
	};
	
	try {
		$('#volo_h_data_a').attachDatepicker({
			minDate: oggi,
			maxDate: fraUnAnno,
			buttonImage: '/ResEBook/img/sf/calendario.gif',
			beforeShow: readLinked,
			onSelect: updateLinked
		});
		//	fine sezione datepicker
	}
	catch(e) {
		// non fare nulla
	}
	
	jQuery("input[name^='tipoVg']").each(
		function()
		{
			if (this.checked) {
				chiamaWs(this.value);
			}
		}
	)



	$('#form_charter').submit(function(){
		$('#form_check').remove();
		var messaggio = '<p>Form incompleto:</p>'
		var g_a = + $('#volo_g_a').val();
		var ma_a = + $('#volo_ma_a').val();
		
		var dateSelected = new Date($('#volo_a_a').val(),$('#volo_m_a').val()-1,g_a,23,59,59);
		var today = new Date();
		
		if ($('#partenza').val() == null || $('#partenza').val() == "-1")
			messaggio += '</BR> - Devi selezionare un aeroporto di partenza.';

		if (ma_a == '0' || g_a == '0') {
			messaggio += '</BR> - Devi scegliere una data di partenza valida.';
		} else if (dateSelected < today) {
			messaggio += '</BR> - La data di partenza non puņ essere minore di oggi.';
		} else if (!isValidDate(g_a + "/" + $('#volo_m_a').val() + "/" + $('#volo_a_a').val()))
			messaggio += '</BR> - Devi scegliere una data di partenza valida.';

		if (messaggio == '<p>Form incompleto:</p>'){
		    
		    var nDivTrovaLayer = $("#trova_layer").length;
		    
		    if(nDivTrovaLayer > 0){
		    	HideDIV('alpitourPAGEcontent'); DisplayDIV('trova_layer');
		    }else{
			    viewPaginaAttesa(); 
			}
			return true;
		}
		else {
			$('<div id="form_check" class="formBox"></div>')
			.html(messaggio)
			.insertAfter('#form_charter');
			return false;
		}
	});

	function isValidDate(strDate)
	{
  		var date_array = strDate.split('/');
  		var day = date_array[0];

  		var month = date_array[1] - 1;
  		var year = date_array[2];

  		source_date = new Date(year,month,day);

  		if(year != source_date.getFullYear())
     		return false;

  		if(month != source_date.getMonth())
     		return false;

  		if(day != source_date.getDate())
	 		return false;

   		return true;
	};

    jQuery("input[name^='tipoVg']").bind('click',function(e){
    	chiamaWs(jQuery(this).attr("value"));
	});

	// Visualizzo Pagina di Attesa dopo aver premuto il tasto TROVA 
	function viewPaginaAttesa() {
	
	    var coordinate = jQuery('#searchBox').offset();

        if ($('#divContentDX').attr('id') !=undefined){
	        jQuery($('#divContentDX')).attr('style','display: none;');
	    }     

	    if ($('#footer').attr('moveFooter') != undefined){
	         var obj = $('#divContDXSearch');
	         var offset = obj.offset();
	         var h = obj.outerHeight();
	         jQuery($('#footer')).attr('style','position: absolute; top:'+ (220 + h) +'px;');    
	    }

        var style_params = null;
        var other_params = null;

		var styleBar = {
			'position': 'absolute',
			'top': coordinate.top + 'px',
			'left': coordinate.left + 300 + 'px',
			'border': '0',
			'padding': '10px',
			'width': '611px',
			'height': '10px',
			'cursor': 'pointer',
			'background-position': 'center',
			'background-image': 'url(/ResEBook/img/pb/progress_bar.gif)',
			'background-repeat': 'no-repeat'
		}
		
		var configBar = {
			'closeOnClick': false,
			'id': '#progressBarSOHO'
		}
		
		jQuery.extend(styleBar, style_params);
		jQuery.extend(configBar, other_params);
		jQuery('#' + configBar.id).remove();
		
		jQuery('<div id="' + configBar.id + '"></div>')
			.css(styleBar)
			.appendTo('body')
			.click(function(){
				if (configBar.closeOnClick) {
					jQuery(this).remove();
				}
			});
		
        document.body.scrollTop=0;
		return;
	} 




	
});