//variable global que indica la opcion
var vuelos = "N";

var TEMPORADA_VERANO = 0;
var TEMPORADA_INVIERNO = 1;

function form_param_calendar(fechas_param,obj_destino,dia,mes,any,num_mes,idioma,id_pinta,titulo,despl) {
	param_calendar(fechas_param,obj_destino,dia,mes,any,num_mes,idioma,id_pinta,titulo,despl);
}

/** 
	Establece el número de noches del formulario de reservas.Si el numero de noches no es númerico, o no se encuentra dentro del rango de noches posibles, o esta vacío, se establece a 7. 
	
	@param Noches: string.	 Indica el número de noches. Debe estar contenido entre nochesMin y nochesMax.
	
	@return boolean. Indica si se a producido algun error, por lo que, se ha establecido el valor por defecto.
*/
function setNoches(nNoches,mostrarError)
{
	var error = false;
	var iNoches = parseInt(nNoches,10);
	if(nNoches!=null && nNoches!="" && !isNaN(iNoches)){
		if(iNoches <= nochesMax && iNoches >= nochesMin){
			document.getElementById("p_noches").value = iNoches;
		}
		else{
			error = true;
			if(mostrarError)
				alert("El n\u00FAmero de noches permitidas es entre " + nochesMin + " y " + nochesMax + " noches.");
			document.getElementById("p_noches").value = "7";
		}
	}
	else{
		error = true;
		if(mostrarError){
			alert("El n\u00FAmero de noches no es v\u00E1lido.");
		}
		document.getElementById("p_noches").value = "7";
	}
	return error;
}

/**
	obj_destino: id del objeto HTML en el que se guardara la fecha seleccionada del calendario del formulario de reserva.
*/
function calendario_callBack(obj_destino) {
	var fecha = document.getElementById(obj_destino).value;
	if(obj_destino == "p_fecent"){
		setFechaEntrada(toDate(fecha),true);
	}
	else{ // obj_destino == "p_fecsal" => fecha = toDate(document.getElementById("p_fecsal").value);
		var error = false;
		var noches = calcula_numero_noches(document.getElementById("p_fecent").value,fecha);
		if(noches < 1){
			alert( "La fecha de regreso no puede ser inferior a la fecha de salida.");
			error = true;
		}
		error = setNoches(noches,!error) || error;
		fecha = toDate(fecha);
		fecha.setDate(fecha.getDate()- parseInt(noches,10));
		error = setFechaEntrada(fecha,!error) || error;
	}
	oculta_calendario();
	if(error){
		setTimeout(function() {document.getElementById(obj_destino).focus()},200);
	}
}

var nochesMax = 30;
var nochesMin = 1;

/**
	Establece la fecha de entrada con el valor del parámetro de entrada; y la fecha de salida con el valor
	del parámetro de entrada más el número de noches.
	
	@param data: Date.				Fecha a partir de la cual se calculará la fecha de salida.
	@param mostrarError: boolean. 	Indica si al producirse un error debe mostrarse el mensaje de alerta.
	
	Si data es menor a la fecha actual más los días de release, se establece la fecha de entrada con la fecha menor seleccionable dentro del calendario.
	Si es mayor a la fecha actual, se establece la fecha de entrada con la fecha actual más dos meses.
*/
function setFechaEntrada(data,mostrarError)
{
	var error = false;
	var novaData = data;//fecha introducida por el usuario
	var dataActual;//fecha a partir de la que se puede realizar una reserva.
	if(calendar_tipo_usa == "N")
		dataActual = f_entrada[0].split('/')[0] + "/" + f_entrada[0].split('/')[1] + "/" + f_entrada[0].split('/')[2];
	else
		dataActual = f_entrada[0].split('/')[1] + "/" + f_entrada[0].split('/')[0] + "/" + f_entrada[0].split('/')[2];
	dataActual = toDate(dataActual);
	var dataMax = new Date(dataActual);
	dataMax.setMonth(dataMax.getMonth() + 24);//fecha maxima de la que se puede realizar una reserva.
	//alert("data: " + data + "\nnova data: " + novaData + "\ndata max: " + dataMax + "\ndata actual: " + dataActual);
	
	if(dataActual>novaData){
		data = dataActual;
		error = true;
		if(mostrarError)
			alert("La fecha introducida no puede ser inferior a la fecha: " + DateToString(dataActual) + ".");
	}
	if(novaData>dataMax){
		data = dataMax;
		error = true;
		if(mostrarError)
			alert("La fecha introducida no puede ser superior a la fecha: " + DateToString(dataMax) + ".");
	}
	document.getElementById("p_fecent").value = DateToString(data);
	var noches = parseInt(document.getElementById("p_noches").value,10);
	data.setDate(data.getDate()+ noches);
	document.getElementById("p_fecsal").value = DateToString(data);
	return error;
}

/**
	Calcula la fecha de entrada y de salida.
	Si el parámetro de entrada corresponde a la fecha de salida y es valida, calcula la fecha de regreso a partir 
	del valor del parámetro más el núm. de noches. Si el parámetro de entrada corresponde a la fecha de regreso y
	es valido, calcula el nuevo núm. de noches. 
	Si durante la ejecución se produce algun error y el el parámetro de entrada corresponde a la fecha de salida
	ésta se recalcula a partir de la fecha de regreso menos el número de noches. Si por el contrario corresponde 
	a la fecha de regreso, ésta se recalcula a partir de la fecha de salida más el número de noches.
	Solo se informa al usuario del primer error que se produce.
	
	@param inputFecha: input de HTML correspondiente a la fecha modificada. 
*/
function cambiaInputFecha(inputFecha){
	var fechaEntrada,fechaSalida;
	var error = false;
	try{
		fechaEntrada = traduceTextoFecha(document.getElementById("p_fecent").value,true);
		fechaSalida = traduceTextoFecha(document.getElementById("p_fecsal").value,true);
		if(fechaEntrada == "" || fechaSalida ==""){
			error = true;
		}
		if(inputFecha.id == "p_fecent"){
			fechaEntrada = toDate(fechaEntrada);
			error = setFechaEntrada(fechaEntrada,!error) || error;
		}
		else{
			var noches = calcula_numero_noches(fechaEntrada,fechaSalida);
			if(noches < 1 && !error){
				alert( "La fecha de regreso no puede ser inferior a la fecha de salida.");
				error = true;
			}
			error = setNoches(noches,!error) || error;
			fechaEntrada = toDate(fechaSalida);
			fechaEntrada.setDate(fechaEntrada.getDate()- parseInt(noches,10));
			error = setFechaEntrada(fechaEntrada,!error) || error;
		}
	}catch(e){
		if(inputFecha.id == "p_fecent"){
			fechaEntrada = toDate(document.getElementById("p_fecsal").value);
			var noches = parseInt(document.getElementById("p_noches").value,10);
			fechaEntrada.setDate(fechaEntrada.getDate() - noches);
			setFechaEntrada(fechaEntrada,false);
		}
		else{
			setNoches(document.getElementById("p_noches").value);
			setFechaEntrada(toDate(document.getElementById("p_fecent").value),false);
		}
	}
	finally{
		if(error){
			setTimeout(function() {inputFecha.focus()},200);
		}
	}
}

/**
	Añade los dígitos necesarios para que la fecha que recibe como parámetro de entrada sea un string de 10 dígitos.
	
	@param fecha: string. 			Fecha a la que se quiere dar formato.
	@param mostrarError: boolean. 	Indica si debe mostrarse el mensaje de alerta si el resultado no es un fecha.
	
	@return string. Fecha de diez digitos separada por "/", o string vacío, si el resultado de la transformación no
	es un fecha. 
*/
function traduceTextoFecha(fecha,mostrarError)
{
	try{
		var nFecha = fecha.split('/');
		if (nFecha[0].length < 2) nFecha[0] = '0'+nFecha[0];
		if (nFecha[1].length < 2) nFecha[1] = '0'+nFecha[1];
		if (nFecha[2].length == 2) nFecha[2] = '20'+nFecha[2];
		nFecha = nFecha[0] + "/" + nFecha[1]+ "/" + nFecha[2]
		if(valFecha(nFecha)){
			return nFecha;
		}
		else{
			if(mostrarError)
				alert("La fecha introducida no es v\u00E1lida.");
			return "";
		}
	}
	catch(e){
		if(mostrarError)
			alert("La fecha introducida no es v\u00E1lida.");
		return "";
	}
}

/**
	Cambia el valor de la fecha de regreso del formulario de reserva mediante la fecha de salida más el número de noches
	del formulario. 
*/
function cambiaNumNoches(){
	var error = false;
 	var noches = document.getElementById("p_noches").value;
	error = setNoches(parseInt(noches,10),true);
	error = error || setFechaEntrada(toDate(document.getElementById("p_fecent").value),!error);//Informará de los errores producidos dentro de la funcion setFechaEntrada si no se ha producido ninguno al ejecutar setNoches.
	if(error)
		setTimeout(function() {document.getElementById("p_noches").focus()},200);
}

function cambiaFechas(select) {
	if (select.selectedIndex != 0) {
		var zoncod = select.value.split("-");
	}
}

var loaded_rooms = 1;

/**
	Carrega el formulari amb els valors emmagatzemats dins la cookie, si aquesta existeix i la data de entrada
	emmagatzemada encara és valida, és a dir, és major o igual a la data a partir de la qual es pot seleccionar
	dins el calendari.
*/
function form_reset(cookies, zona) {
	if(document.cookie.indexOf("form_"+zona)!=-1)//si existeix cookie
	{
		var soloHotel = form_var_cookie("p_regimen",zona);
		var fechaEntrada = form_var_cookie("p_fecent",zona);
		var fechaSelec;
		if(soloHotel!="")//solo hotel
		{
			fechaSelec = afegirDiesRelease(fechaHoy,0,"ES");
		}
		else // hotel + vuelo
		{
			fechaSelec = afegirDiesRelease(fechaHoy,3,"ES");
		}
		if( toDate(fechaEntrada) >= toDate(fechaSelec) ) //Si la data de entrada es major o igual a la data a partir de la que es permet seleccionar dins el calendari carregam la cookie.
		{
			document.getElementById("p_hotcod").value=form_var_cookie("p_hotcod",zona);
			cambiaRegimen();//cargamos los regimenes que corresponden al hotel seleccionado
			if(soloHotel!="")//solo hotel
			{
				document.getElementById("solohotel").checked="true";
				if(document.getElementById("contenedorFormularioReservasHorizontal")== null)//formulario de reservas Vertical
					cambiaOpcion(document.getElementById("solohotel"));//Marcamos opcion solo hotel y ocultamos el input de origen
				else //formulario de reservas Horizontal
					cambiaOpcionHorizontal("solohotel");//Activamos pestaña Hotel y desactivamos la pestaña Hotel + Vuelo y ocultamos el input origen
				document.getElementById("p_regimen").value=form_var_cookie("p_regimen",zona);//marcamos el regimen almacenado dentro de la cookie
			}
			else //hotel + vuelo
			{
				document.getElementById("paquetes").checked="true";
				document.getElementById("p_aptcod").value=form_var_cookie("p_aptcod",zona);
				if(document.getElementById("contenedorFormularioReservasHorizontal")== null)//formulario de reservas Vertical
					cambiaOpcion(document.getElementById("paquetes"));//Marcamos opcion hotel + vuelo y ocultamos el input de regimen
				else //formulario de reservas Horizontal
					cambiaOpcionHorizontal("paquetes");//Activamos pestaña Hotel y desactivamos la pestaña Hotel + Vuelo y ocultamos el input de regimen
			}
			document.getElementById("p_fecent").value= fechaEntrada;
			document.getElementById("p_fecsal").value= form_var_cookie("p_fecsal",zona);
			document.getElementById("p_noches").value=form_var_cookie("p_noches",zona);
			document.getElementById("p_pax").value=form_var_cookie("p_pax",zona);
			document.getElementById("hab1_a").value=form_var_cookie("p_pax",zona);
			var nroninos = form_var_cookie("p_nroninos",zona);
			document.getElementById("p_nroninos").value = nroninos;
			document.getElementById("p_nrobebes").value=form_var_cookie("p_nrobebes",zona);
			for(var i = 1; i <= nroninos; i++)
			{
				document.getElementById("hab1_n" + i).value = form_var_cookie("hab1_n" + i,zona);
				muestraNins(1);
			}
		}
	}
	//reset valores guardados por el navegador
}

function form_crea_cookie(zona) {
	var cookie = "form_"+zona+"=";
	if((document.getElementById("contenedorFormularioReservas")!= null && document.getElementById("solohotel").checked)||
		(document.getElementById("contenedorFormularioReservasHorizontal")!= null && document.getElementById("solohotel").className == "botonPestana activa")){
		cookie += escape("|p_regimen=" + document.getElementById("p_regimen").value);
	}
	else{
		cookie += escape("|p_aptcod=" + document.getElementById("p_aptcod").value);
	}
	cookie += escape("|p_hotcod=" + document.getElementById("p_hotcod").value);
	cookie += escape("|p_fecent=" + document.getElementById("p_fecent").value);
	cookie += escape("|p_fecsal=" + document.getElementById("p_fecsal").value);
	cookie += escape("|p_noches=" + document.getElementById("p_noches").value);
	cookie += escape("|p_pax=" + document.getElementById("p_pax").value);
	var nroninos = document.getElementById("p_nroninos").value;
	cookie += escape("|p_nroninos=" + nroninos);
	for(var i = 1; i <= nroninos; i++)//si hay algún niño guardamos sus edades
	{
		cookie += escape("|hab1_n" + i + "=" + document.getElementById("hab1_n" + i).value);
	}	
	cookie += escape("|p_nrobebes=" + document.getElementById("p_nrobebes").value);
	cookie += "|";
	
	var temp = new Date();
	temp.setTime(temp.getTime() + (86400000*30) + (temp.getTimezoneOffset()*60000*-1));
	cookie += ";expires=" + temp.toGMTString() + ";path=/";
	document.cookie = cookie;
}

function form_var_cookie(id, zona) {
	var res = "";
	var cookie = document.cookie;
	var index = cookie.indexOf("form_"+zona);
	if (index != -1) {
		index = index + ("form_"+zona).length + 1;
		var index_end = cookie.indexOf(";",index) != -1 ? cookie.indexOf(";",index) : cookie.length;
		cookie = unescape(cookie.substring(index, index_end));
		var index_id = cookie.indexOf(id);
		if (index_id != -1) {
			index_id = index_id + id.length + 1;
			res = cookie.substring(index_id, cookie.indexOf("|",index_id) );
		}
	}
	return res;
}

function cambiaRegimen(){
	var hotcod= document.getElementById("p_hotcod").value;
		var combo = "R&eacute;gimen<select name='p_regimen' id='p_regimen'>";
		if (hotcod == "3" || hotcod == "5" || hotcod == "2" || hotcod == "7" || hotcod == "8" || hotcod == "1" || hotcod == "4" || hotcod == "10" || hotcod == "11" || hotcod == "12" || hotcod == "14" || hotcod == "15" || hotcod == "17" || hotcod == "19" || hotcod == "20"){
			combo += '<option value=TI>Todo Incluido</option>';
		}else if (hotcod == "57" || hotcod == "53"){
			combo += '<option value=TI>Todo Incluido</option><option value=MP>Media Pensi&oacute;n</option><option value=PC>Pensi&oacute;n Completa</option>';
		}else if (hotcod == "54" || hotcod == "56" || hotcod == "59"){
			combo+='<option value=MP>Media Pensi&oacute;n</option><option value=PC>Pensi&oacute;n Completa</option>';
		}else if (hotcod == "18"){
			combo+='<option value=MP>Media Pensi&oacute;n</option><option value=TI>Todo Incluido</option>';
		}else{
			combo+='<option value="">Seleccione un hotel</option>';
		}
		combo+="</select>";
		document.getElementById("td_regimen").innerHTML=combo;
}

function linkVacaciones(){
	location.href = "javascript:__utmLinker('http://www.viajesgti.es/viajes/vacaciones.jsp?p_zona=GTI&amp;p_idioma=es');";	
	__utmLinkPost("javascript:__utmLinker('http://www.viajesgti.es/viajes/vacaciones.jsp?p_zona=GTI&amp;p_idioma=es');");
}

function reservar_hotel() {
	p_fechaent = document.getElementById("p_fecent").value;
	if (p_fechaent != "" && p_fechaent != "__/__/____") {
		if ((document.getElementById("p_hotcod").value != 0)&&(document.getElementById("p_hotcod").value != "")){
		
			i = document.getElementById("p_hotcod").selectedIndex;
			document.getElementById("p_hotdesc").value=document.getElementById("p_hotcod").options[i].text;
			i = document.getElementById("p_regimen").selectedIndex;
			document.getElementById("p_regdesc").value=document.getElementById("p_regimen").options[i].text;

			if ((typeof( window['p_zona'] ) != "undefined") && document.getElementById("p_zona")) {
				document.getElementById("p_zona").value = p_zona;
			}
			if ((typeof( window['p_idioma'] ) != "undefined") && document.getElementById("p_idioma")) {
				document.getElementById("p_idioma").value = p_idioma;
			}
			form_crea_cookie("GTI");
			document.param_paquetes.submit();
		}else{
			alert('Seleccione el hotel al que desea viajar.');
		}
	} else {
		alert('Seleccione en el calendario el día de entrada en el Hotel.');
	}
}

function setAcomod(){
	document.getElementById("hab1_a").value = document.getElementById("p_pax").value;
	if(parseInt(document.getElementById("p_nroninos").value)> 0)
	{
		muestraAcomod(document.getElementById("p_pax"));
	}
}

/*** FUNCIONES DE ACOMODACIÓN ***/
function ocultaAcomod() {
	//alert("ocultaAcomod()");
	if((document.getElementById("problema0").style.display == "block")||
		(document.getElementById("problema1").style.display == "block")||
		(document.getElementById("problema2").style.display == "block")||
		(document.getElementById("problema3").style.display == "block")||
		(document.getElementById("problema4").style.display == "block")){
		alert("El formulario presenta errores.\nRellenelo de manera correcta para continuar")
	} else {
		document.getElementById("p_pax").value = document.getElementById("hab1_a").value;
		document.getElementById("acomodacion_pos").style.display = "none";
		document.getElementById("num_hab").style.visibility = "visible";
		document.getElementById("p_noches").style.visibility = "visible";
		document.getElementById("p_pax").style.visibility = "visible";
		document.getElementById("p_hotcod").style.visibility = "visible";
		if(document.getElementById("p_regimen")){
			document.getElementById("p_regimen").style.visibility = "visible";
		}
		if(document.getElementById("origen")){
			document.getElementById("origen").style.visibility = "visible";
		}
		if(document.getElementById("mes")){
			document.getElementById("mes").style.visibility = "visible";
		}
		if(document.getElementById("p_mes")){
			document.getElementById("p_mes").style.visibility = "visible";
		}
	}
}

function muestraAcomod() {
	//alert("muestraAcomod()");
	document.getElementById("hab1_a").value = document.getElementById("p_pax").value;
	/*document.getElementById("num_hab").style.visibility = "hidden";*/
	if(!document.getElementById("contenedorFormularioReservasHorizontal")){
		document.getElementById("p_noches").style.visibility = "hidden";
		document.getElementById("p_hotcod").style.visibility = "hidden";
		if(document.getElementById("p_regimen")){
			document.getElementById("p_regimen").style.visibility = "hidden";
		}
		if(document.getElementById("origen")){
			document.getElementById("origen").style.visibility = "hidden";
		}
		if(document.getElementById("mes")){
			document.getElementById("mes").style.visibility = "hidden";
		}
		if(document.getElementById("p_mes")){
			document.getElementById("p_mes").style.visibility = "hidden";
		}
	}
	document.getElementById("p_pax").style.visibility = "hidden";
	var i=1;
	while (document.getElementById("hab"+i)!=null) {
		document.getElementById("hab"+i).style.display = "none";
		i++;
	}
	var cond = false;
	var condnin = false;
	var habs = parseInt(document.getElementById("num_hab").value);
		cambia_pax(document.getElementById("p_pax"));
		document.getElementById("hab1").style.display = "block";
		//niños
		var nins = parseInt(document.getElementById("p_nroninos").value);
		if (nins > 0 && !cond) {
			document.getElementById("hab_nt").style.display = "block";
			document.getElementById("hab1_nc").style.display = "block";
			document.getElementById("acomodacion").style.width = "450px";/*"433px";480*/
			document.getElementById("acomod_cen").style.width = "432px";
			cond = true;
		} else if (nins > 0) {
			document.getElementById("hab1_nc").style.display = "block";
		}
		for (j=1; j<=nins; j++) {
			document.getElementById("hab1_nc"+j).style.visibility = "visible";
			document.getElementById("hab_nt"+j).style.visibility = "visible";
			condnin = true;
		}
	if (!condnin) {
		document.getElementById("hab_nt").style.display = "none";
		document.getElementById("acomodacion").style.width = "280px";/*"220px";320*/
		document.getElementById("acomod_cen").style.width = "262px";
	}
	document.getElementById("acomodacion_pos").style.display = "block";
}

function muestraNins(index) {
	//alert("muestraNins(index)");
	cambia_pax(document.getElementById("p_nroninos"));
	var visualiza = false;
	var habs = parseInt(document.getElementById("num_hab").value);
	// Si no se muestran los niños, cambia el tamaño y muestra los seleccionados
	if (document.getElementById("hab_nt").style.display != "block") {
		document.getElementById("acomodacion").style.width = "450px";/*"433px";480*/
		document.getElementById("acomod_cen").style.width = "432px";
		document.getElementById("hab_nt").style.display = "block";
		visualiza = true;
	} else {
	// Si se estaban mostrando niños, y todavia queda alguno seleccionado, contarlos
		var cont = 0;
		if (parseInt(document.getElementById("p_nroninos").value) != 0) cont++;
		if (cont!=0) visualiza = true;
	}
	// Esconde todos los selects de niños y titulos
	var i=1;
	while (document.getElementById("hab_nt"+i)!=null) {
		document.getElementById("hab_nt"+i).style.visibility = "hidden";
		document.getElementById("hab1_nc"+i).style.visibility = "hidden";
		i++;
	}
	// Muestra todos los niños seleccionados y el titulo
	if (visualiza) {
		var nins = parseInt(document.getElementById("p_nroninos").value);
		for (j=1; j<=nins; j++) {
			if (index==1) {
				document.getElementById("hab1_nc"+j).style.visibility = "visible";
				document.getElementById("hab_nt"+j).style.visibility = "visible";
			} else {
				if (document.getElementById("hab1_nc"+j).style.visibility == "visible") {
					document.getElementById("hab_nt"+j).style.visibility = "visible";
				}
			}
		}
		document.getElementById("hab"+index+"_nc").style.display = "block";
	} else {
	// No hay niños seleccionados, se esconde y se cambia el tamaño
		i=1;
		document.getElementById("hab1_nc").style.display = "none";
		document.getElementById("acomodacion").style.width = "280px";/*"220px";320*/
		document.getElementById("acomod_cen").style.width = "262px";
		document.getElementById("hab_nt").style.display = "none";
	}
}

function muestra_problema(hab,texto){
	//alert("muestra_problema(hab,texto)");
	hab=1;
	hab_problema=eval("document.getElementById('problema"+1+"');");
	tipo_habit[hab]="error";
	hab_problema.style.display="block";
	hab_problema.innerHTML="&nbsp;&nbsp;&nbsp;<img src='img/ocupa_exclama.gif' align='absmiddle' /> "+texto+"<br /><br />";
}

function oculta_problema(hab){
	//alert("oculta_problema(hab)");
	hab=1;
	hab_problema=eval("document.getElementById('problema"+hab+"');");
	if (hab_problema.style.display=="block")hab_problema.style.display="none";
}

function cambia_pax(selec){
	//alert("cambia_pax(selec)");
	hab = selec.name;
	hab = hab.substring(0,5);
	hab_num = hab.substring(3,4);
	adultos = document.getElementById("hab1_a").value;
	nins =  document.getElementById("p_nroninos").value;
	bebes = document.getElementById("p_nrobebes").value;
	total_pax = Number(adultos)+Number(nins);
	if (total_pax == 1){
		oculta_problema(hab_num);
		tipo_habit[hab_num]="L1";
	}else if (total_pax == 2){
		oculta_problema(hab_num);
		tipo_habit[hab_num]="L2";
	}else if (total_pax == 3){
		oculta_problema(hab_num);
		tipo_habit[hab_num]="L3";
	}else if (total_pax == 4){
		oculta_problema(hab_num);
		tipo_habit[hab_num]="L4";
	}else if (total_pax == 0){
		muestra_problema(1,lahabitacion+nopuedeestarvacia);
	}else{
		muestra_problema(1,demasiadosocupantes+".");
	}
	if(	(document.getElementById("problema0").style.display == "block")|| (document.getElementById("problema1").style.display == "block")||
		(document.getElementById("problema2").style.display == "block")|| (document.getElementById("problema3").style.display == "block")||
		(document.getElementById("problema4").style.display == "block")){
		document.getElementById("acomodacion_pos").style.display="block";
		document.getElementById("acomodacion").style.display="block";
		document.getElementById("num_hab").style.visibility = "hidden";
		document.getElementById("p_noches").style.visibility = "hidden";
		document.getElementById("p_pax").style.visibility = "hidden";
	}
}
/*** FIN DE FUNCIONES DE ACOMODACIÓN ***/

function cambiaOpcion(elem){
	var claseViaje = new Array("","vacaciones");
	var actionViaje = new Array("javascript:reservar_hotel('');","javascript:buscar_vuelos()");
	var selector = 0;
	if (elem.id == "paquetes"){
		selector=1;
		var fecha;
		fecha = afegirDiesRelease(fechaHoy,3,"ES");
		calendar_dia_muestra = fecha.split("/")[0];
		calendar_mes_muestra = fecha.split("/")[1];
		calendar_any_muestra = fecha.split("/")[2];
		f_entrada = new Array(fecha);
		if (get("p_fecent").value!=""){
			var fechaSelec = toDate(get("p_fecent").value);
			var fechaActual = toDate(f_entrada[0]);
			if(fechaSelec < fechaActual)
				alert("Seleccione una fecha a partir del "+ DateToString(fechaActual));
		}
	}
	else{
		var fecha = afegirDiesRelease(fechaHoy,0,"ES");
		calendar_dia_muestra = fecha.split("/")[0];
		calendar_mes_muestra = fecha.split("/")[1];
		calendar_any_muestra = fecha.split("/")[2];
		f_entrada = new Array(fecha);
	}
	document.getElementById("formularioGti").className = claseViaje[selector];
	document.getElementById("botonBusqueda").href = actionViaje[selector];
}

function cambiaOpcionHorizontal(elemName){
	var claseViaje = new Array("formularioGtiHorizontal","formularioGtiHorizontal vacaciones");
	var actionViaje = new Array("javascript:reservar_hotel('');","javascript:buscar_vuelos()");
	var selector = 0;
	var pestanaSoloHotel = document.getElementById("solohotel");
	var pestanaPaquetes = document.getElementById("paquetes");
	if (elemName == "paquetes"){
		selector=1
		pestanaSoloHotel.className = pestanaSoloHotel.className.replace(" activa","");
		pestanaSoloHotel.className = pestanaSoloHotel.className.replace("activa","");
		if(pestanaPaquetes.className.indexOf("activa") == -1){
			pestanaPaquetes.className = pestanaPaquetes.className + " activa";	
		}
		var fecha = afegirDiesRelease(fechaHoy,3,"ES");
		calendar_dia_muestra = fecha.split("/")[0];
		calendar_mes_muestra = fecha.split("/")[1];
		calendar_any_muestra = fecha.split("/")[2];
		f_entrada = new Array(fecha);
		if (get("p_fecent").value!=""){
			var fechaSelec = toDate(get("p_fecent").value);
			var fechaActual = toDate(f_entrada[0]);
			if(fechaSelec < fechaActual)
				alert("Seleccione una fecha a partir del "+ DateToString(fechaActual));
		}
	}
	else{
		pestanaPaquetes.className = pestanaPaquetes.className.replace(" activa","");
		pestanaPaquetes.className = pestanaPaquetes.className.replace("activa","");
		if(pestanaSoloHotel.className.indexOf("activa") == -1){
			pestanaSoloHotel.className = pestanaSoloHotel.className + " activa";	
		}
		var fecha = afegirDiesRelease(fechaHoy,0,"ES");
		calendar_dia_muestra = fecha.split("/")[0];
		calendar_mes_muestra = fecha.split("/")[1];
		calendar_any_muestra = fecha.split("/")[2];
		f_entrada = new Array(fecha);		
	}
	document.getElementById("formularioCampos").className = claseViaje[selector];
	document.getElementById("botonBusqueda").href = actionViaje[selector];
}

function buscar_vuelos() {
	fecini = document.getElementById("p_fecent").value;//fecini = document.getElementById("p_fecsal").value; - BIEL
	auxFec = fecini.split("/");

	var mesSeleccionado = Number(auxFec[1]);
	var anySeleccionado = Number(auxFec[2]);
	
	//Temporada a la que pertenece la fecha de la busqueda
	var codTemporada;
	if (mesSeleccionado >= 5) codTemporada = TEMPORADA_VERANO;
	else codTemporada = TEMPORADA_INVIERNO;



	//variables para el control de la capacidad de las habitaciones
	var individuales = 0;
	var dobles	 	 = 0;
	var triples      = 0;
	var cuadruples   = 0;
	var adultos      = 0;
	var ninos1       = 0;
	var ninos2       = 0;
	var bebes        = 0;
	
	var habitaciones = 1;//get("num_hab").value; - BIEL
	var p_paxes = "";
	var p_acomod = "";
	
	var i_paxes = 1;
	//var maximo = calcula_max_ocup();
	
	//if (maximo == false){
		
		//for (i=1; i<=habitaciones; i++){
			var ocupado = "";
			var totalPasajerosEnHabitacion = 0;
			//adultos
			hab_a = Number(eval("get('hab1_a').value"));
			totalPasajerosEnHabitacion+=hab_a;
			if ( hab_a > 0){
				adultos+=hab_a;
				for (j=1; j<=hab_a; j++){
					p_paxes+=i_paxes+"-A--";
					ocupado+="-"+i_paxes;
					i_paxes++;
				}
			}
			
			//ninos
			hab_n = Number(eval("get('p_nroninos').value"));
			totalPasajerosEnHabitacion+=hab_n;
			if ( hab_n > 0){
				for (j=1; j<=hab_n; j++){
					edad = Number(eval("get('hab1_n"+j+"').value"));
					p_paxes+=i_paxes+"-C-"+edad+"-";
					ocupado+="-"+i_paxes;
					i_paxes++;
					if (edad < 9) ninos1++;
					else ninos2++;
				}
			}
			
			//bebes
			hab_b = Number(eval("get('p_nrobebes').value"));
			if ( hab_b > 0){
				bebes+=hab_b;
				for (j=1; j<=hab_b; j++){
					p_paxes+=i_paxes+"-I--";
					ocupado+="-"+i_paxes;
					i_paxes++;
				}
			}
			
			//tipo
			if ( totalPasajerosEnHabitacion==2){
				p_acomod+="&p_acomod=L2"+ocupado;
				dobles++;
			}else if (totalPasajerosEnHabitacion==3){
				p_acomod+="&p_acomod=L3"+ocupado;
				triples++;
			}else if (totalPasajerosEnHabitacion==4){
				p_acomod+="&p_acomod=L4"+ocupado;
				cuadruples++;
			}else if (totalPasajerosEnHabitacion==1){
				p_acomod+="&p_acomod=L1"+ocupado;
				individuales++;
			}else{
				p_acomod="error";
			}
			
		//}
		
		if (p_acomod == "error"){
			
			alert("Ha seleccionado una combinación no permitida.");
			
		}else{
		
			var parametrillos;
			parametrillos="p_paxes="+p_paxes+p_acomod;
			
			var hotcod = Number(document.getElementById("p_hotcod").value);
			
			vAux = new Array();
			
			vAux = getProductoCod(hotcod,codTemporada,fecini);
			
			//alert("hotcod: " + hotcod + "\ncodTemporada: " + codTemporada + "\n\n\nvAux: " + vAux);
			
			if (!vAux){
				
				alert ("Seleccione el destino al que desea viajar");
			
			} else {
			
				document.getElementById("p_producto").value = vAux[0];
				document.getElementById("p_adecod").value = vAux[1];
				
				parametrillos += "&p_producto="+get("p_producto").value;
				parametrillos += "&p_adecod="+get("p_adecod").value;
				
				//alert ("&p_producto="+get("p_producto").value + "\n&p_adecod="+get("p_adecod").value);
				
				parametrillos += "&p_l1="+individuales;
				parametrillos += "&p_l2="+dobles;
				parametrillos += "&p_l3="+triples;
				parametrillos += "&p_l4="+cuadruples;
				parametrillos += "&p_numpax="+(adultos+bebes+ninos1+ninos2);
				parametrillos += "&p_ningra="+ninos1;
				parametrillos += "&p_ninpeq="+ninos2;
				parametrillos += "&p_bebes="+bebes;
				parametrillos += "&p_regdesc=Todo+Incluido";
				parametrillos += "&p_regimen=TI";
				parametrillos += "&p_fecent="+get("p_fecent").value;//parametrillos += "&p_fecent="+get("p_fecsal").value; - BIEL
				parametrillos += "&p_numnoc="+get("p_noches").value;//get("p_numnoc") - BIEL
				parametrillos += "&p_noches="+get("p_noches").value;//get("p_numnoc") - BIEL
				parametrillos += "&p_aptcod="+get("p_aptcod").value;
				parametrillos += "&p_ap="+get("p_ap").value;
				if (get("p_sprind"))
				parametrillos += "&p_sprind="+get("p_sprind").value;
				if (get("p_ofecod"))
				parametrillos += "&p_ofecod="+get("p_ofecod").value;
				
				// Cargamos las noches de los hoteles del combinado seleccionado.
				var t_nocsal = "";
				var p_aloj = "";
				
				var fechaSelec = toDate(get("p_fecent").value);
				var fechaActual = toDate(f_entrada[0]);
				if (get("p_fecent").value != ""){//if (get("p_fecsal").value != ""){ - BIEL
					if(fechaSelec >= fechaActual){
						document.getElementById("num_hab").value="1";	
						form_crea_cookie("GTI");					
						self.location="/es/BUSCADOR/BUSCADOR_VACACIONES/index.htm?"+parametrillos+t_nocsal;
					}else
						alert("Seleccione una fecha a partir del " + DateToString(fechaActual));
				}else{
					alert("Seleccione una fecha de salida");
				}
				
			}
			
		}
		
	//} else {
		//máxima ocupación
		//alert('Está intentando reservar más viajeros de los permitidos');
	//}
	
}

function getProductoCod(hotcod,codTemporada,fecini){

	//codTemporada == 1 -- Invierno
	//codTemporada == 0 -- Verano

	vAux = new Array();
	
	switch(hotcod){
		case 3: case 5: case 18:	//TENERIFE
			vAux[0]=(codTemporada == TEMPORADA_INVIERNO)?"F_I8TF":"F_V8TF";
			vAux[1] = "TCI";
			break;
		case 7: case 8: case 20: //PUNTA CANA, BAVARO, AMBAR
			vAux[0]=(codTemporada)?"F_I8PU":"F_A9PU";
			vAux[1] = "PUJ";
			break;

		case 1: case 4: case 10:	//MEXICO
			vAux[0]=(codTemporada == TEMPORADA_INVIERNO)?"F_I8RM":"F_A9RM";
			vAux[1] = "CUN";
			break;
		
		case 2:						//SAN JUAN
			vAux[0]=(codTemporada == TEMPORADA_INVIERNO)?"F_I8RD":"F_A9RD";
			vAux[1] = "POP";
			break;
			
		case 17:					//JAMAICA
			vAux[0]=(codTemporada == TEMPORADA_INVIERNO)?"F_I8JA":"F_A9JA";
			vAux[1] = "MBJ";
			break;
			
		case 15: case 14: case 12: case 11:		//SAMANA, PORTILLO, CAYO LEVANTADO, CAYACOA
			vAux[0]=(codTemporada == TEMPORADA_INVIERNO)?"F_I8SA":"F_A9SA";
			vAux[1] = "AZS";
			break;
		
		case 53: case 54: case 57: case 59: 	//HOTELES PIÑERO
			vAux[0]=(codTemporada == TEMPORADA_INVIERNO)?"F_I8PM":"F_V8PM";
			vAux[1] = "PMI";
			break;
			
		case 19:        //LA ROMANA
			vAux[0]=(codTemporada)?"F_I8LR":"F_A9LR";
			vAux[1] = "LRM";
			break;
		   
		default:
		
			return null;
		
	}
	
	return vAux;

}

function get(id){
	return document.getElementById(id);
}