// Carga un desplegable con información proveniente de un XML
var primeraVez = 'S';
function cargaXML( ruta, id, etiqueta, codigo, descripcion, texto, esAtributo, seleccion, esOrdenado ) {
	$.ajax({
		type: 'GET',
		url: ruta,
		dataType: 'xml',
		success: function(xml) {
			var select = $(id);
			var opciones = '';
			$(xml).find(etiqueta).each(function() {
				if (esAtributo) {
					var cod = $(this).attr(codigo);
					var desc = $(this).attr(descripcion);
				} else {
					var cod = $(this).find(codigo).text();
					var desc = $(this).find(descripcion).text();
				}
				opciones += '<option value="' + cod + '">'
				+ desc + '</option>';
			});

			select.append(opciones);

			select.children(':first').remove();

			if (esOrdenado) {
				var optsOrdenadas = $.makeArray($(id + ' option')).sort(function(a, b) {
					if ($(a).text() > $(b).text()) {
						return 1;
					} else if ($(a).text() == $(b).text()) {
						return 0;
					} else {
						return -1;
					}

				});
				select.empty().html(optsOrdenadas);
			}

			if (texto != '') {
				select.children(':first').before('<option value="">' + texto + '</option>');
			}

			// El bloque try/catch se emplea para que funcione en IE 6.0
			// Ya que este navegador da problemas en la carga del DOM

			try {
					select.val(seleccion).attr('selected', true);
			} catch(ex) {
				//setTimeout(select + ".val('" + seleccion + "').attr('selected', true)", 1);
				setTimeout( function(){
					select.val(seleccion).attr('selected', true);
				}, 1);
					
			}

		}
	});
}

function cargaMeses()
{
	$( '#mesAnyo' ).html( '' );
	var meses = "";
	//meses = "<option value=''>Seleccione un mes</option>";
	var hoy = new Date();
	var dia = hoy.getDate();
	var mes = hoy.getMonth();
	var anyo = hoy.getFullYear();
	mes++;
	for( var i = 0; i < 12; i++ )
	{
		meses += "<option value='" + ( dia < 10 ? "0" + dia : dia ) + "/" + 
					( mes < 10 ? "0" + mes : mes )  + "/" + anyo + "'>" +
					( mes < 10 ? "0" + mes : mes ) + "/" + anyo +
				"</option>";
		mes++;
		dia = 1;
		if( mes == 13 )
		{
			mes = 1;
			anyo++;
		}
	}
	$( '#mesAnyo' ).append( meses );

}

// Cargamos el desplegable de destinos y zonas
var destinosZonas = null;
var primeraZonaGlobal = null;
function cambiarZona() {
	$('#zona').html('');
	var opciones = '';
	if( primeraZonaGlobal != null )
	{
		opciones += '<option value="">' + primeraZonaGlobal + '</option>';
	}

	$(destinosZonas).find('areanegocio destinos destino').each(function() {
		if ($(this).find('> codigo').text() == $('#destino').val()) {
			$(this).find('> zonas zona').each(function() {
				opciones += '<option value="' + $(this).find('zon_cod').text() + '">' + $(this).find('zon_desc').text() + '</option>';
			});
			return false;
		}
	});
	$('#zona').append(opciones);
}

function cargarDestinosZonas(destinoSelec, zonaSelec, hotelSelec, primerDestino, primerHotel, primeraZona ) {
	primeraZonaGlobal = primeraZona;
	$.ajax({
		type: 'GET',
		url: '/parametros/pedestin.xml',
		dataType: 'xml',
		success: function(xml) {
			destinosZonas = xml;
			var opciones = '';
			$(xml).find('areanegocio').each(function() {
//				opciones += '<option value="' + $(this).find('> codigo').text() + '">';
				opciones += '<option value="">';
				opciones += $(this).find('> descripcion').text() + '</option>';
				$(this).find('> destinos destino').each(function() {
					opciones += '<option value="' + $(this).find('codigo').text() + '">';
					opciones += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + $(this).find('descripcion').text() + '</option>';
				});
			});

			$('#destino').append(opciones);
			$('#destino option:first').text( primerDestino );
			$('#zona option:first').text( primeraZona );
			$('#destino').change(cambiarZona);
			if (destinoSelec == '' && zonaSelec == '' && hotelSelec == '') {
				$('#destino option:first').attr('selected', true);
			} else {
				// El bloque try/catch se emplea para que funcione en IE 6.0
				// Ya que este navegador da problemas en la carga del DOM
				try {
					$('#destino').val(destinoSelec).attr('selected', true);
				} catch(ex) {
					setTimeout("$('#destino').val('" + destinoSelec + "').attr('selected', true)", 1);
				}
				$('#destino').change();
				$('#zona').val(zonaSelec);
				//obtenerHoteles( hotelSelec, primerHotel );
			}
			/*$('#destino').change(function() {
				obtenerHoteles( '', primerHotel );
			});
			$('#zona').change(function() {
				obtenerHoteles( '', primerHotel );
			});*/
		}
	});
}

function cargarDestinosZonas2(destinoSelec, zonaSelec, hotelSelec, primerDestino, primerHotel, primeraZona ) {
	primeraZonaGlobal = primeraZona;
	$.ajax({
		type: 'GET',
		url: '/parametros/pedestin.xml',
		dataType: 'xml',
		success: function(xml) {
			destinosZonas = xml;
			var opciones = '';
			opciones += '<dl>';
			$(xml).find('areanegocio').each(function() {
					opciones +='<dt class="" id="24283"><img src="/www/img/iconoSeleccionDest.gif" width="10px" height="10px">&nbsp;&nbsp;<a href="#">' + $( this ).find('> descripcion').text() + '</a></dt>';
				$( this ).find( '> destinos destino' ).each( function() {
					opciones += '<dd style="display: none;"><a target="_self" href="#" onclick="menu(\'' + $( this ).find( 'descripcion' ).text() + '\', \'' + $(this).find('codigo').text() + '\')">' + $( this ).find( 'descripcion' ).text() + '</a></dd>';
				});
			});
			opciones +='</dl>';

			$('#ctl00_PHBody_Menu1_divMenu').html(opciones);
			//$('#destino option:first').text( primerDestino );
			$('#zona option:first').text( primeraZona );
			//$('#destino').change(cambiarZona);
			$('.EmpresasLeft dt img').click(function(){
				$(this).parent().toggleClass('select');
				if($(this).parent().hasClass('select')){
					$(this).attr('src','/www/img/less-icon.gif');
				}else{
					$(this).attr('src','/www/img/iconoSeleccionDest.gif');
				}
				$(this).parent().nextAll().each(function(){if($(this).is('dd')){$(this).slideToggle(200);}else{return false;}});
				return false;
			});
			$('.EmpresasLeft dt a').click(function(){
				$(this).parent().nextAll().each(function(){if($(this).is('dd')){$(this).slideToggle(200);}else{return false;}});
				return false;
			});
			$('#destino').change(function() {
				obtenerHoteles( '', primerHotel );
			});
			$('#zona').change(function() {
				obtenerHoteles( '', primerHotel );
			});
		}
	});
}

// Cargamos el desplegable de hoteles en función de los
// desplegables de destinos y zonas
function obtenerHoteles(seleccion, primerHotel) {
	$('#hotel').html('');
	$('#hotel').append('<option value="">' + car + '</option>');
	if ($('#destino').val() != '') {
		HotelesPorDestinoZona.recuperarHoteles($('#destino').val(),
			$('#zona').val(),
			{callback : function(hotelesJSON) {
				var hoteles = eval('(' + hotelesJSON + ')');
				$.each(hoteles, function(i, item) {
					$('#hotel').append('<option value="' + item.hot_cod + '">' + item.hot_desc + '</option>');
				});
				if( primerHotel != null )
				{
					$('#hotel option:first').text( primerHotel );
				}
				$('#hotel').val(seleccion).attr('selected', true);
			}
		});
	} else {
		if( primerHotel != null )
		{
			$('#hotel option:first').text( primerHotel );
		}
		$('#hotel').val(seleccion).attr('selected', true);
	}
}

// Si se ha seleccionado un origen y un destino,
// habilitamos el cuadro de comprobación 'vueloDirecto'
cambiarEstadoVueloDirecto = function() {
	if ($('#origen').val() != '' && $('#destino').val() != '') {
		$('#vueloDirecto').removeAttr('disabled');
	} else {
		$('#vueloDirecto').attr('disabled', true);
	}
}

// Convierte una fecha en formato AAAA-MM-DD a DD/MM/AAAA
function convertirFecha(fecha) {
var elementosFecha = fecha.split('-');
return elementosFecha[2] + '/' + elementosFecha[1] + '/' + elementosFecha[0];
}

// Comprobamos si existen vuelos directos para el origen, destino, fecha y
// producto seleccionados. Opcionalmente también podemos introducir el hotel 
// la zona.
verificarVueloDirecto = function() {
	if ($('#vueloDirecto').attr('checked')) {
		VueloDirecto.compruebaVueloDirecto(getCookie('p_ideses'), $('#fechaSalida').val(),
			$('#origen').val(), $('#destino').val(), $('#zona').val(),
			$('#hotel').val(), $('#tipoProducto').val(),
			{callback : function( resultadoJSON ) {
				var resultado = eval('(' + resultadoJSON + ')');
				if (resultado.P_result == 'OK2') {
					alert( hvdfs );
					$('#fechaSalida').val(convertirFecha(resultado.P_fechas_dev[0].FECHA));
				} else if (resultado.P_result == 'KO') {
					$('#vueloDirecto').attr('checked', false);
					$('#vueloDirecto').attr('disabled', true);
					alert( nhvdfs );
				}
			}
		});
	}
}

var numHabitacionesAnterior = 1;

function conmutarHabitacionesEdades() {

	var numHabitaciones = $('#numHabitaciones').val();
	var campos = [ 'numAdultos', 'numNinyos', 'numBebes' ];
	var conjuntoCamposHabita = '#formHabitacionesEdades #habitaciones';
	if (numHabitaciones >= numHabitacionesAnterior) {
		var habitacionInicio = numHabitacionesAnterior;
		if (habitacionInicio != 1) {
			habitacionInicio++;
	 	}
		if( primeraVez == 'N' && habitacionInicio == 1 && $('habitacion1') )
		{
			habitacionInicio = 2;
		}
	 	for (var i = habitacionInicio; i <= numHabitaciones; i++) {
			var etiqueta = $('<div id="habitacion' + i + '" class="habi"><label>' + habac +  i + ':</label>');
			etiqueta.appendTo(conjuntoCamposHabita);
				$.each(campos, function() {
				var desplegable = $('<select id="' + this + i + '" name="' + this + i + '">');
				desplegable.appendTo(conjuntoCamposHabita);
				for (var j = 0; j <= 4; j++) {
					$('<option value="' + j + '">' + j + '</option>').appendTo(desplegable);
				}
				$('</select></div>').appendTo(conjuntoCamposHabita);
				if (this == 'numAdultos') {
					$('#' + this + i).val(2);
				}
				if (this == 'numNinyos') {
					$('#' + this + i).change(function() {
						var indice = $(this).attr('id').substring(9);
						$('#edades' + indice).remove();
						for (var j = 1; j <= $(this).val(); j++) {
							$('#edadNinyo' + indice + '_' + j).remove();
						}
						if (numHabitacionesAnterior == 1 && $(this).val() == 0) {
							$.each(campos, function() {
								$('#' + this + '1').remove();
							});
							$('#habitacion1').remove();
							$('#numNinyos').val(0);

							$('#formHabitacionesEdades').fadeOut('slow');
							$('#formPie #adultos').fadeIn('slow');
							$('#formPie #ninyos').fadeIn('slow');
							$('#formPie #bebes').fadeIn('slow');
							primeraVez = 'S';
						}
						if ($(this).val() > 0) {
							var edades = '<div id="edades' + indice + '" class="edad"><label>' + edadnin +':</label>';
							for (var j = 1; j <= $(this).val(); j++) {
								edades += '<select id="edadNinyo' + indice + '_' + j + '" name="edadNinyo' + indice + '_' + j + '">';
								for (var k = 2; k <= 12; k++) {
									if( k == 2 )
									{
										edades += '<option selected="selected" value="' + k + '">' + k + '</option>';
									}
									else
									{
										edades += '<option value="' + k + '">' + k + '</option>';
									}
								}
								edades += '</select>';
							}
							edades += '</div>';
							//$(edades).insertBefore('#habitacion' + indice);
							$(edades).insertAfter('#numBebes' + indice);
						}
					});
				}
			});
		}
		if (numHabitacionesAnterior == 1) {
			$('#numAdultos1 option:eq(' + $('#numAdultos').val() + ')').attr('selected', true);
			$('#numNinyos1 option:eq(' + $('#numNinyos').val() + ')').attr('selected', true);
			if ($('#numNinyos1').val() > 0) {
				$('#numNinyos1').change();
			}

			$('#numBebes1 option:eq(' + $('#numBebes').val() + ')').attr('selected', true);
			$('#formHabitacionesEdades').fadeIn('slow');
			$('#formPie #adultos').fadeOut('slow');
			$('#formPie #ninyos').fadeOut('slow');
			$('#formPie #bebes').fadeOut('slow');
			primeraVez = 'N';
		}

	} else {
		var habitacionInicio = numHabitaciones;
		if (habitacionInicio != 1) {
			habitacionInicio++;
		}
		for (var i = habitacionInicio; i <= numHabitacionesAnterior; i++) {
			if ($('#numNinyos' + i).val() > 0) {
				$('#edades' + i).remove();
				for (var j = 1; j <= $('#numNinyos' + i).val(); j++) {
					$('#edadNinyo' + i + '_' + j).remove();
				}
			}
				$.each(campos, function() {
					$('#' + this + i).remove();
				});
				$('#habitacion' + i).remove();
		}
		if (numHabitaciones == 1) {
			$('#formHabitacionesEdades').fadeOut('slow');
			$('#formPie #adultos').fadeIn('slow');
			$('#formPie #ninyos').fadeIn('slow');
			$('#formPie #bebes').fadeIn('slow');
			$('#numNinyos').val(0);
			primeraVez = 'S';
		} 			 	

	}

	numHabitacionesAnterior = numHabitaciones;
}
function conmutarHabitacionesEdadesInicio() {
	var numHabitacionesActual = $( '#numHabitacionesInicio' ).val();
	var opciones = 	'<option value="0">0</option>' +
					'<option value="1">1</option>' +
					'<option value="2">2</option>' +
					'<option value="3">3</option>' +
					'<option value="4">4</option>';
	var opcionesAdulto = 	'<option value="0">0</option>' +
							'<option value="1">1</option>' +
							'<option value="2" selected="selected">2</option>' +
							'<option value="3">3</option>' +
							'<option value="4">4</option>';
	var htmlHabitaciones = '';
	for( var i = 1; i <= numHabitacionesActual; i++ )
	{
		htmlHabitaciones +=	//'<div id="divHabitacion' + i + '" style="width:100%" ' +
								'<div class="habi" id="habitacion' + i +'">' +
									'<label>Habitación ' + i + ':</label>' +
								'</div>' +
								'<select name="numAdultos' + i + '" id="numAdultos' + i + '">' +
									opcionesAdulto +
								'</select>' +
								'<select name="numNinyos' + i + '" id="numNinyos' + i + '">' +
									opciones +
								'</select>' +
								'<select name="numBebes' + i + '" id="numBebes' + i + '">' +
									opciones +
								'</select>' +
								'<br>';
							'';//'</div>';
	}

	$( '#habitaciones' ).html( htmlHabitaciones );
}
// Asociamos la funcionalidad a los eventos de cada componente del formulario.
$(document).ready(function() {
	$('#destino').change(cambiarEstadoVueloDirecto);
	$('#destino').change(verificarVueloDirecto);	
	$('#origen').change(cambiarEstadoVueloDirecto);
	$('#origen').change(verificarVueloDirecto);
	$('#vueloDirecto').click(verificarVueloDirecto);
	$('#fechaSalida').blur(cambiarEstadoVueloDirecto);

// Evento para que aparezcan y desparezca las personas por habitación y las 
// edades de los niños.
	$('#numHabitaciones').change(conmutarHabitacionesEdades);
	$('#numHabitacionesInicio').change(conmutarHabitacionesEdadesInicio);
	$('#numNinyos').change(conmutarHabitacionesEdades);
});
