var n_habitaciones = 1;
var hab_seleccionadas = 0;

/*** Funcion para poner o quitar habitaciones ***/
function control_num_habs(numero){
	var max_habitaciones = 4;
	
	//Si tengo que añadir habitaciones
	if (numero > n_habitaciones) {
		for (i=parseInt(n_habitaciones, 10)+1; i<=numero; i++) {
			var clonedRow = $("#habitacion1").clone();
			clonedRow.attr("id", "habitacion"+i);
			
			//Cambio los elementos <span>
			$("span", clonedRow).each( function (k) {
				if (k == 0) $(this).html("Habitaci&oacute;n "+i);
				if (k == 1) {
					$(this).attr("value", "");
					$(this).attr("id", "edades-"+i);
					$(this).css("display", "none");
				}
			});
			
			//Y ahora cambio los <selects>
			$("select", clonedRow).each( function (k) {
				$(this).attr("value", "");
				if (k == 0) {
					$(this).attr("id", "adultos-"+i);
					$(this).attr("name", "adultos-"+i);
					//alert($(this).attr("name"));
					$(this).attr("disabled", false);
				}
				if (k == 1) {
					$(this).attr("id", "ninos-"+i);
					$(this).attr("name", "ninos-"+i);
					$(this).attr("disabled", false);
				}
				if ((k == 2) || (k == 3) || (k == 4)) {
					$(this).attr("name", "edni"+i+"-"+(parseInt(k, 10)-1));
					$(this).attr("id", "edni"+i+"-"+(parseInt(k, 10)-1));
					
					$(this).attr("disabled", false);
					
					$(this).css("visibility", "hidden");
				}
				if (k == 5) {
					$(this).attr("id", "cunas-"+i);
					$(this).attr("name", "cunas-"+i);
					$(this).attr("disabled", false);
				}
			});
			
			
			//y ahora lo mmis mo para los ids de los tds de las edades
			//Y ahora cambio los <selects>
			$("td", clonedRow).each( function (k) {
				if ((k == 3) || (k == 4) || (k == 5)) {
					$(this).attr("id", "td-edni"+i+"-"+(parseInt(k, 10)-2));
								
				}
				
			});
			
			
			//Por ultimo cambio el id de la columna de los munegotes y lo "vaciamos" de contenido
			$("td[id^='munegotes']", clonedRow).attr("id", "munegotes-"+i);
			$("td[id^='munegotes']", clonedRow).html("");
			
			//Añadimos la habitacion al listado
			$("#habitaciones").append(clonedRow);
		}
	
	//Si tengo que eliminar habitaciones		
	} else {
		for (i=parseInt(numero, 10)+1; i<=n_habitaciones; i++) $("#habitacion"+i).remove();	
	}
	
	//Y por ultimo, pongo el numero de habitaciones actualmente visibles
	n_habitaciones = numero;
}


//Poner los munegotes de niños y adultos
function muestra_munegotes_bbs(habitacion) {
	var res = '';
	id = habitacion.split('-');
	id = id[1];
	
	adultos = $("select[id^='adultos-"+id+"']").val();
	ninos = $("select[id^='ninos-"+id+"']").val();
	cunas = $("select[id^='cunas-"+id+"']").val();
	
	if (adultos>3){
		res +=  '<img src="images/icono-adulto.gif" /><b>x'+adultos+'</b>';
	}
	else{
		for (var i=1; i<=adultos; i++)
			{
				res += '<img src="images/icono-adulto.gif" />';
			}	
	}
	
	for (var i=1; i<=ninos; i++) res += '<img src="images/icono-nino.gif" />';	
	if (cunas>1) res +=  '<img src="images/cuna.gif" /><b>x'+cunas+'</b>';
	else if (cunas==1)res +=  '<img src="images/cuna.gif" />';
	
	//Y añadimos el resultado
	$("#munegotes-"+id).html(res);
}



function ver_valoracion_masopciones(opcion) {
	iddiv = 'valoracion-masopciones-'+opcion;
	if ($('#'+iddiv).html() == '') {
		//transid = document.getElementById('transidmopc').value;
		
		//var num_ninos= document.getElementById('ninos-'+num_hab).value;
		
		
		//necesitamos sacar el hotel de las opciones
		var array_opcion = opcion.split('-');
		var cod_hotel = array_opcion[0];
		transid = document.getElementById('transidmopc_'+cod_hotel).value;
		
		
		opciones_form = recupera_opciones();
		
		
		opciones = 'transid='+transid+'&opcion='+opcion+'&opciones_form='+opciones_form+'&masopciones=1';
		
		if (document.getElementById('es_un_parque') && document.getElementById('es_un_parque').value==1 ){
			opciones+='&es_un_parque=1';
		}
		
		/*if (document.getElementById('cunas-'+num_hab) && document.getElementById('cunas-'+num_hab).value){
			opciones+='&cunas_habitacion='+document.getElementById('cunas-'+num_hab).value;
			
		}*/
		//sacamos del opcion el codhotel
		//var array_opcion = opcion.split('-');
		//var cod_hotel = array_opcion[0];
		
		
		if (document.getElementById('margenBen_'+cod_hotel) && document.getElementById('margenBen_'+cod_hotel).value){
			opciones+='&margenBen='+document.getElementById('margenBen_'+cod_hotel).value;
			
		}
		
		
		$.ajax({
				type: "POST",
				dataType: "html",
				contentType: "application/x-www-form-urlencoded",
				url: "ajax/reservas_consultar_valoracion.php",
				data: opciones,
					beforeSend: function(objeto){
						$('#'+iddiv).show();
						$('#'+iddiv).html("<img src='images/cargando.gif'>");
					},
					success: function(datos){						
						$('#'+iddiv).html(datos);
					},
					error: function(obj, quepaso, obj2){
						//alert("Ha habido un error: "+quepaso);
					}
		});
	}
	else {
		$('#'+iddiv).hide();
		$('#'+iddiv).html("");
	}
}

//Ver la valoracion de las habitaciones pedidas
function ver_valoracion(opcion) {
	iddiv = 'valoracion-'+opcion;
	if ($('#'+iddiv).html() == '') {
		//Recuperamos todas las variables del form para enviarselas al AJAX para saber el numero de adultos y niños pedidos
		var opciones_form = recupera_opciones();	
		var transid = $("#transid").val();
		opciones = 'transid='+transid+'&opcion='+opcion+'&opciones_form='+opciones_form;
		
		if (document.getElementById('es_un_parque') && document.getElementById('es_un_parque').value==1 ){
			opciones+='&es_un_parque=1';
		}
		
		
		//sacamos del opcion el codhotel
		var array_opcion = opcion.split('-');
		var cod_hotel = array_opcion[0];
		if (document.getElementById('margenBen_'+cod_hotel) && document.getElementById('margenBen_'+cod_hotel).value){
			opciones+='&margenBen='+document.getElementById('margenBen_'+cod_hotel).value;
			
		}
		
		
		$.ajax({
				type: "POST",
				dataType: "html",
				contentType: "application/x-www-form-urlencoded",
				url: "ajax/reservas_consultar_valoracion.php",
				data: opciones,
					success: function(datos){
						$('#'+iddiv).show();
						$('#'+iddiv).html(datos);
					},
					error: function(obj, quepaso, obj2){
						//alert("Ha habido un error: "+quepaso);
					}
		});
	}
	else {
		$('#'+iddiv).hide();
		$('#'+iddiv).html("");
	}
}

function ver_valoracion2(opcion,num_hab) {
	iddiv = 'valoracion2-'+opcion;
	if ($('#'+iddiv).html() == '') {
		if (document.getElementById('transid')) transid = document.getElementById('transid').value;

		//envio directamente el numero de niños d el ahabitacion para ahorrar calculos (TEMA CAMA SUPLETORIA)
		var num_ninos= document.getElementById('ninos-'+num_hab).value;
		
		opciones = 'transid='+transid+'&opcion='+opcion+'&num_hab='+num_hab+'&num_ninos='+num_ninos;
		
		if (document.getElementById('es_un_parque') && document.getElementById('es_un_parque').value==1 ){
			opciones+='&es_un_parque=1';
		}
		
		if (document.getElementById('cunas-'+num_hab) && document.getElementById('cunas-'+num_hab).value){
			opciones+='&cunas_habitacion='+document.getElementById('cunas-'+num_hab).value;
			
		}
		
		
		//sacamos del opcion el codhotel
		var array_opcion = opcion.split('-');
		var cod_hotel = array_opcion[0];
		if (document.getElementById('margenBen_'+cod_hotel) && document.getElementById('margenBen_'+cod_hotel).value){
			opciones+='&margenBen='+document.getElementById('margenBen_'+cod_hotel).value;
			
		}
		
		$.ajax({
				type: "POST",
				dataType: "html",
				contentType: "application/x-www-form-urlencoded",
				url: "ajax/reservas_consultar_valoracion2.php",
				data: opciones,
					success: function(datos){
						if (datos == 'KO-SESSION' || datos == 'KO-PERM') {
							Alert_Error (datos);
						} else {
							$('#'+iddiv).show();
							$('#'+iddiv).html(datos);
						}
					},
					error: function(obj, quepaso, obj2){
						//alert("Ha habido un error: "+quepaso);
					}
		});
	}
	else {
		$('#'+iddiv).hide();
		$('#'+iddiv).html("");
	}
}

function ver_valoracion2_masopciones(opcion,num_hab) {
	iddiv = 'valoracion2-masopciones-'+opcion;
	if ($('#'+iddiv).html() == '') {
		//transid = document.getElementById('transidmopc').value;
		
		//necesitamos sacar el hotel de las opciones
		var array_opcion = opcion.split('-');
		var cod_hotel = array_opcion[0];
		transid = document.getElementById('transidmopc_'+cod_hotel).value;
		
		var num_ninos= document.getElementById('ninos-'+num_hab).value;
		
		opciones = 'transid='+transid+'&opcion='+opcion+'&num_hab='+num_hab+'&num_ninos='+num_ninos+'&masopciones=1';
		
		if (document.getElementById('es_un_parque') && document.getElementById('es_un_parque').value==1 ){
			opciones+='&es_un_parque=1';
		}
		
		if (document.getElementById('cunas-'+num_hab) && document.getElementById('cunas-'+num_hab).value){
			opciones+='&cunas_habitacion='+document.getElementById('cunas-'+num_hab).value;
			
		}
		
		//sacamos del opcion el codhotel
		
		
		if (document.getElementById('margenBen_'+cod_hotel) && document.getElementById('margenBen_'+cod_hotel).value){
			opciones+='&margenBen='+document.getElementById('margenBen_'+cod_hotel).value;
			
		}
		
		
		$.ajax({
				type: "POST",
				dataType: "html",
				contentType: "application/x-www-form-urlencoded",
				url: "ajax/reservas_consultar_valoracion2.php",
				data: opciones,
					beforeSend: function(objeto){
						$('#'+iddiv).show();
						$('#'+iddiv).html("<img src='images/cargando.gif'>");
					},
					success: function(datos){						
						$('#'+iddiv).html(datos);
					},
					error: function(obj, quepaso, obj2){
						//alert("Ha habido un error: "+quepaso);
					}
		});
	}
	else {
		$('#'+iddiv).hide();
		$('#'+iddiv).html("");
	}
}

function ver_valoracion_localizador(opcion,num_hab) {
	if ($("#valoracion2-"+opcion).html() == '') {
		var transid = $("#transid").val();
		var num_ninos = $("#ninos-"+num_hab).val();		
		opciones = 'transid='+transid+'&opcion='+opcion+'&num_hab='+num_hab+'&num_ninos='+num_ninos;
		
		if (document.getElementById('es_un_parque') && $("#es_un_parque").val() == 1 ){
			opciones+='&es_un_parque=1';
		}

		if (document.getElementById('cunas-'+num_hab) && document.getElementById('cunas-'+num_hab).value){
			opciones+='&cunas_habitacion='+document.getElementById('cunas-'+num_hab).value;			
		}
		
		//sacamos del opcion el codhotel
		var array_opcion = opcion.split('-');
		var cod_hotel = array_opcion[0];
		if (document.getElementById('margenBen_'+cod_hotel) && document.getElementById('margenBen_'+cod_hotel).value){
			opciones+='&margenBen='+document.getElementById('margenBen_'+cod_hotel).value;
			
		}
		
		$.ajax({
			type: "POST",
			dataType: "html",
			contentType: "application/x-www-form-urlencoded",
			url: "ajax/reservas_consultar_valoracion2.php",
			data: opciones,
				beforeSend: function(objeto){
					$("#valoracion2-"+opcion).html("<img src='images/cargando.gif'>");
				},
				success: function(datos){
					if (datos == 'KO-SESSION' || datos == 'KO-PERM') {
						Alert_Error (datos);
					} else {
						$("#valoracion2-"+opcion).html(datos)
					}
				},
				error: function(obj, quepaso, obj2){
					dlg.hide();
					//alert("Ha habido un error: "+quepaso);
				}
		});
	}
	else ("#valoracion2-"+opcion).html("");
}




//Ficha de los hoteles
function ver_ficha_hotel_v2(codigo, ficha_defecto) {
	//Incorporo el script para las pestañas
	
	var script = document.createElement("script");
    script.src = "js/jquery.tabs.pack.js";
    script.type = "text/javascript"
    document.getElementsByTagName("head")[0].appendChild(script);
	
	//Guardamos el scroll que se ha hecho
	var sX = window.pageXOffset || document.documentElement && document.documentElement.scrollLeft || document.body.scrollLeft || 0;
    var sY = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop || 0;
	
	
	//Y muestro la ficha
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/ver_ficha_hotel.php",
		data: 'codigo='+codigo+'&ficha_defecto='+ficha_defecto+"&mayorista="+$("#tipo_mayorista").val(),
			success: function(datos){
				
				dlgFichaHotel.show();
				
				document.getElementById("ficha_hotel_v2").innerHTML = datos;
				//$("#ficha_hotel_v2").html(datos);	
				$('#menutabs').tabs(2);
				window.scrollTo(sX, sY);
			}
	});
} 
	
function cerrar_ficha_hotel_v2(){
	dlgFichaHotel.hide(); 
	//GUnload();
	if (document.getElementById('vengo_de_google_maps')){
		if (document.getElementById('vengo_de_google_maps').value==1){
			//y reabro el mapa de google con el ultimo hotel posicionado
			//muestro mapa otra vez
			carga_mapa_hoteles();

			//y lo situo en el ultimo
			mueve_centro_mapa("ultimo","ultimo","ultimo");
		}
	}
}

//Mostrar el calendario de disponibilidad
function solicita_calendario_disp(hot,hab,reg,cont_div) {
	var fecha400='';
	
	if (!cont_div) cont_div="0";
	
	var auxDiv = "div_flotante_calendisp_"+hot+"_"+cont_div;
	//var auxDivPista = "div_flotante_calendisppista_"+hot+"_"+cont_div;
	var auxDivPista = "div_flotante_calendisppista_masopc_"+hot+"_"+cont_div;
	var ptr = document.getElementById(auxDiv);
	var ptrPista = document.getElementById(auxDivPista);
	
	var fechaAhora=new Date();
	tiempoAhora = fechaAhora.getTime();	
		
	var f= document.forms["busqueda_disponibilidad"];
	
	//realmente calculamos 7 dias antes de la fecha inicial, a no ser que sea menor que la actual
	
		
	if (f.fecha_entrada){
		 var fIniForm= f.fecha_entrada.value;
		 aux = fIniForm.split("-");
		 
		 
		  var diaIniNum = parseInt(aux[2],10);
			var mesIniNum = parseInt(aux[1],10);
			var anoIniNum = parseInt(aux[0],10);
			fechaIniNums = new Date(anoIniNum, mesIniNum-1, diaIniNum, 12, 00, 00);
			
			tiempoIni = parseInt(fechaIniNums.getTime());
			
			//ahora le restamos 7 dias!!
			var dias7=7*24*60*60*1000;//milisegundos
			var tiempo7dias=parseInt(tiempoIni-dias7);
			
			
			
			//alert ("7 dias "+tiempo7dias+ " ahora "+tiempoAhora);

			
			if (tiempo7dias<tiempoAhora){
			//if (1==1){
					//NO PODEMOS RESTAR 7 DIAS, nos quedamos con el actual!
					//alert("Ahora");
						var day=fechaAhora.getDate();
						var month=fechaAhora.getMonth()+1;
						var year=fechaAhora.getYear();
						
						aux[2]=day+"";
						aux[1]=month+"";
						aux[0]=year+"";
						
						
						
			}
			else{
					//NOS QUEDAMOS CON LOS SIETE DIAS ANTES
					//alert("7 dias");
					//fechaFin = new Date(anoIni, mesIni-1, diaIni, 12, 00, 00);
					var fecha7dias=new Date();
					fecha7dias.setTime(parseInt(tiempo7dias));
					var day=fecha7dias.getDate();
					var month=fecha7dias.getMonth()+1;
					var year=fecha7dias.getYear();
					
					/*
					auxAno = fechaFin.getYear();
						if (auxAno < 1000)
							auxAno = auxAno + 1900;
						
						f.fecha_salida.value= auxAno+"-"+rellenar_ceros(fechaFin.getMonth()+1)+"-"+rellenar_ceros(fechaFin.getDate());
					
					*/
					//alert ("dia "+day+" mes "+month+ "anyo "+year);
						aux[2]=day+"";
						aux[1]=month+"";
						aux[0]=year+"";
						
						//alert ("dia "+aux[2]+" mes "+aux[1]+ "anyo "+aux[0]);
						
					
			}
			
			//pasamos LO QUE HAYA EN AUX a fecha 400
			
			diaIni = aux[2];
			if (diaIni.length==1) diaIni="0"+diaIni;
			mesIni = aux[1];
			if (mesIni.length==1) mesIni="0"+mesIni;
			anoIni = aux[0];
			
			//y del anyo nos quedamos las dos ultimas
			anoIni=anoIni.substring(2);
			if (anoIni.length==1) anoIni="0"+anoIni;
			
			fecha400=diaIni+""+mesIni+""+anoIni;
	}
	

	
	opciones = 'hotel='+hot+'&habitacion='+hab+'&regimen='+reg+'&fecha='+fecha400+'&div_abierto='+auxDiv+'&cont_div='+cont_div;
	
	//Y muestro el calendario
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/calendario_disponibilidad.php",
		data: opciones,
			beforeSend: function(objeto){
				ptrPista.style.visibility = 'hidden';
				ptr.style.visibility = '';
				ptr.innerHTML = "<span style='color:#666699'><b>Cargando...</b></span>";
			},
			success: function(datos){
				ptr.innerHTML = datos;
				ptr.style.visibility = '';
				ptrPista.style.visibility = 'hidden';				
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}

function cambia_a_estmin(cont_div_pista){
	if (document.getElementById("caldisp_noestmin_"+cont_div_pista).style.display=="none"){
		document.getElementById("caldisp_noestmin_"+cont_div_pista).style.display = "";
		document.getElementById("caldisp_estmin_"+cont_div_pista).style.display = "none";
	}
	else{
		document.getElementById("caldisp_noestmin_"+cont_div_pista).style.display = "none";
		document.getElementById("caldisp_estmin_"+cont_div_pista).style.display = "";
	}	
}

function cierra_div(div_id){
	document.getElementById(div_id).style.visibility = "hidden";
	return false;
}

//Mostrar el formulario de envio individual para los hoteles
function mostrar_form_envio(idhotel, disponible) {
	$("#form_envio_avanzado_"+idhotel).toggle();
	
	//Recupero el codigo del formulario
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/formulario_envio_avanzado.php",
		data: 'idhotel='+idhotel+'&disponible='+disponible,
			beforeSend: function(objeto){
				$("#form_envio_avanzado_"+idhotel).html("<img src='images/cargando.gif'>");
			},
			success: function(datos){
				$("#form_envio_avanzado_"+idhotel).html(datos);			
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}

//Paginar los resultados de la busqueda
function consultar_disponibilidad_paginada(inicio) {	
	var id_div_tab=inicio-5;
	var num_iters=$("#num_hoteles").val();
	opciones = "&inicio_pagin_ajax="+inicio;
	$("#siguiente_tabla_res_"+id_div_tab).css("display", "block");
	
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "includes/disponibilidad_paginacion.php",
		data: opciones,
			success: function(datos){
				if (datos == 'KO-SESSION' || datos == 'KO-PERM') {
					Alert_Error (datos);
				} else {
					$("#siguiente_tabla_res_"+id_div_tab).show();
					$("#siguiente_tabla_res_"+id_div_tab).html(datos);
					if (inicio+5<=num_iters){
						//lamada recursiva
						consultar_disponibilidad_paginada(inicio+5);
					}
				}
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}


//Funcion para permitir solo la entrada de numeros en un campo
function EvaluateText(obj, e){
	opc = false;
	tecla = (document.all) ? e.keyCode : e.which;

	//Vemos las teclas que se han pulsado
	if (tecla >=48 && tecla <=57) opc = true;
	if (tecla == 8) opc = true;
	if (tecla == 0) opc = true;
	
	return opc;
}

//Funcion para permitir solo la entrada de numeros en un campo
function Comprobar_Dias(obj, e){
	if (EvaluateText(obj, e)) {
		if (obj.value > 30 || obj.value < 1) {
			alert('El número de días debe estar comprendido entre 1 y 30');
			return false;
		} else return true;
	} else return false;
}

//Funcion para saber si un año es bisiesto o no
function anoBisiesto(year) { 
	return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
}

//Mostrar la edad de los niños
function muestra_edad(cualo, numero) {
	
	aux = cualo.split("-");
	campo = aux[0];
	habitacion = aux[1];
	
	//Para cada fila superior de titulo seleccionada, la muestro
	for (i=1; i<=numero; i++){ 
		document.getElementById("edni"+habitacion+"-"+i).style.visibility = "visible";
		//y el display de los td's también!!!
		//OJO: si muesto un td de edad, muestro el resto de los td's tambi-en (no los selects)
		//para que no se rompa la tabla
		
		for (z=1; z<=parseInt(n_habitaciones, 10); z++) {
			document.getElementById("td-edni"+z+"-"+i).style.display = "";
		}
		
		
	}
	
	//Las que no se muestran, las pongo a 0 y las escondo. Los titulos los escondo si no estan visibles por otro registro
	for (j=parseInt(numero, 10)+1; j<=3; j++) {
		document.getElementById("edni"+habitacion+"-"+j).selectedIndex = "0";
		document.getElementById("edni"+habitacion+"-"+j).style.visibility = "hidden";		
		
		//y el display de los td's también!!! NO HACE FALTA!!!!
		//for (z=1; z<=parseInt(n_habitaciones, 10); z++) {
			//document.getElementById("td-edni"+z+"-"+j).style.display = "none";
		//}
	}
	
	//Calculo las filas superiores a mostrar
	edades_vis = 0;
	for (i=1; i<=n_habitaciones; i++) {
		for (j=1; j<=3; j++) {
			if (document.getElementById("edni"+i+"-"+j).style.visibility == "visible") {
				if (j>edades_vis) edades_vis = j;	
			}
		}
	}

	//Y muestro las filas superiors que se deban mostrar
	for (n=1; n<=edades_vis; n++){ 
		document.getElementById("edadnin"+n).style.visibility = "visible";
		//y los displays tambie:
		document.getElementById("edadnin"+n).style.display = "";
		
	}
	for (m=edades_vis+1; m<=3; m++){ 
		document.getElementById("edadnin"+m).style.visibility = "hidden";
		//y los displays tambie: NO HACE FALTA!!!!
		//document.getElementById("edadnin"+m).style.display = "none";
	}
}



function ver_playa_media(prov, loc, playa, archivo, extension) {
	url = 'playas_ver_media.php?prov='+prov+'&loc='+loc+'&playa='+playa+'&archivo='+archivo+'&extension='+extension;
	window.open(url,'','width=300,height=100,scrollbars=no,menubar=no,resizable=yes,toolbar=no,location=no,status=no');
}

function ver_playa_primera_linea(prov, loc, playa) {
	if (playa != '')
		ver_playa_media(prov, loc, playa, 'playa.flv', 'flv');
	else
		alert("En estos momentos no tenemos esta informacion disponible.\nDisculpe las molestias");
}

function ver_video(url) {
	window.open('hotel_ver_video.php?url='+url,'','width=700,height=400,scrollbars,menubar=no,resizable');
}

function ver_foto(url) {
	window.open(url,'','width=800,height=600,scrollbars,menubar=no,resizable');
}

function ver_contratoweb(mayorista) {
	window.open('contenidos/contratoweb_'+mayorista+'.pdf','','width=910,height=700,scrollbars,menubar=no,resizable');
}

function ver_video2(codigo) {
	window.open('','','width=800,height=600,scrollbars=no,menubar=no');
}

function ver_todo_incluido(codigo) {				
	window.open('hotel_todo_incluido.php?codigo='+codigo,'','width=740,height=400,menubar,scrollbars,resizable');
}

function ver_media_pension(codigo,texto_info) {				
	window.open('hotel_media_pension.php?texto_info='+texto_info+'&codigo='+codigo,'','width=740,height=200,menubar,scrollbars,resizable');
} 

function ver_ofertas(codigo) {
	window.open('hotel_ofertas.php?codigo='+codigo,'','width=740,height=300,menubar=no,scrollbars,resizable');
} 

function ver_spa(codigo) {
	window.open('hotel_spa.php?codigo='+codigo,'','width=700,height=400,menubar=no,scrollbars,resizable');
}

//Funcion general para crear ventanitas modales
function crear_dialog_general(div,offset_w,offset_h){
	dlgGeneral = initDialog('fondo_alpha', div);
	dlgGeneral.setStyles('dialogos_fondo', div);
	dlgGeneral.setWidthSize(offset_w);
	dlgGeneral.setHeightOffset(offset_h);
}

//Funcion para esconder y mostrar DIV's
function toggleDIV (id) {
	$("#"+id).toggle(); 
	return false;
}

//Si hay algun error en algun script, le muestro un alert traducido
function Alert_Error (error) {
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/traducir_errores_js.php",
		data: 'errores='+error,
			success: function(datos){
				lista_errores = datos.split('@#@');
				alert(lista_errores[0]);
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}


/***
	Funciones para mostrar los hoteles seleccionados en el mapa de Google
***/
//Con estas funciones cargo dinamicamente el script de google maps
var mapsLoad= 0;    // variable a 0, script no cargado
var zoom= 11;    // nivel de zoom del mapa
var divMapa = '';
var divHoteles = '';

function showMaps(key, divM, divLH){
	if (mapsLoad==0) {
		divMapa = divM;
		divHoteles = divLH;
		initLoader(key);
	} else muestra_mapa_hoteles(divMapa, divHoteles);
}


function loadMaps() {
    mapsLoad=1;
    google.load("maps", "2", {"callback" : showMaps});
}

function initLoader(key) {
	mapsLoad=1;
	var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key="+key+"&callback=loadMaps&hl=es";
    script.type = "text/javascript"
    document.getElementsByTagName("head")[0].appendChild(script);
	
	var script = document.createElement("script");
    script.src = "js/codigo_mapas.js";
    script.type = "text/javascript"
    document.getElementsByTagName("head")[0].appendChild(script);
}
	


//Cambiar el idioma de la pagina
function cambiar_idioma(idioma) {
	opciones = 'idioma='+idioma;
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/cambiar_idiomas.php",
		data: opciones,
			success: function(){
				window.location.reload();
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}

function ocultar_disponibilidad_hotel(hotel){
		$("#masopc_"+hotel).css("display", "none");
}

//Funcion "mas opciones" de cada hotel
function consultar_disponibilidad_hotel(hotel) {
	opciones = recupera_opciones();
	opciones += '&codestab='+hotel;
	opciones += '&onrequest=3';
	opciones += '&mayorista='+$("#tipo_mayorista").val();
	
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/reservas_consultar_hotel.php",
		data: opciones,
			beforeSend: function(objeto){
				$("#masopc_"+hotel).css("display", "");
				$("#masopc_"+hotel).css("text-align", "center");
				$("#masopc_"+hotel).html("<img src='images/cargando.gif'>");
                //alert(opciones);
			},
			success: function(datos){
				if (datos == 'KO-SESSION' || datos == 'KO-PERM') {
					Alert_Error (datos);
				} else {
					$("#masopc_"+hotel).html("");
					$("#masopc_"+hotel).html(datos);
				}
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}

//Codificar las cadenas de texto con URL Encode (para listado por mail, entre otras cosas)
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

//Buscar hoteles bajo peticion en "Mas opciones"
function busca_bajo_peticion(){
	//en las minoristas siempre son los verdes (jamas bajo pet)
	//if ($("#solo_disponibles").length == 0) $("#solo_disponibles").attr("checked", false);
	consultar_disponibilidad_bbs(false);
}

function busca_bajo_peticion_parques(){
	//document.getElementById('solo_disponibles').checked=false;
	//en las minoristas siempre son los verdes (jamas bajo pet)
	consultar_disponibilidad_parques(false);
}

//Buscar hoteles en la localidad actual
function busca_hoteles_cercanos(value_loc,value_prov){
	//Activamos los campos
	$("#codhotel").attr("disabled", false);
	$("#hotel").attr("disabled", false);
	$("#localidad").attr("disabled", false);
	$("#provincia").attr("disabled", false);
	var opciones = '';
	
	//Cambiamos el select de las provincias
	opciones = "zona=*";
	$.ajax({
		type: "POST",
		async: false,
		url: "ajax/select_zona_provincias.php",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: opciones,
		success: function(j) {
			var opciones = '';
			for (var i = 0; i < j.length; i++) {
				opciones += '<option value="' + j[i].provincia + '">' + j[i].provincia_txt + '</option>';
			}
			$("#provincia").html(opciones);
		}
	});
	
	//Cambiamos el select de las localidades
	opciones = "provincia="+value_prov;
	$.ajax({
		type: "POST",
		async: false,
		url: "ajax/select_localidades_v2.php",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: opciones,
		success: function(j) {
			var opciones = '';
			for (var i = 0; i < j.length; i++) {
				opciones += '<option value="' + j[i].localidad + '">' + j[i].localidad_txt + '</option>';
			}
			$("#localidad").html(opciones);
		}
	});
	
	$("#codhotel").val("");	
	$("#hotel").val("");
	$("#provincia option[value='"+value_prov+"']").attr("selected", "selected");
	$("#localidad option[value='"+value_loc+"']").attr("selected", "selected");	
	
	//Y volvemos a desactivar
	$("#codhotel").attr("disabled", true);
	$("#hotel").attr("disabled", true);
	$("#localidad").attr("disabled", true);
	$("#provincia").attr("disabled", true);
	
	//Y buscamos otra vez
	consultar_disponibilidad_bbs(true);
}





//Iniciar una reserva 
function reserva_iniciar(opcion) {
	//Activamos los campos de adultos, niños y cunas para que se envien	
	var datos_ocupacion='';
	for(var i=1; i<=4; i++) {
		ad = "adultos-"+i;
		ni = "ninos-"+i;
		cu = "cunas-"+i;
		if ($("#"+ad).length){ 
			$("#"+ad).attr("disabled", false); 
			$("#"+ad).attr("name", ad);
		}
		if ($("#"+ni).length){ 
			$("#"+ni).attr("disabled", false); 
			$("#"+ni).attr("name", ni);
			
		}
		if ($("#"+cu).length){ 
			$("#"+cu).attr("disabled", false); 
			$("#"+cu).attr("name", cu);
			
		}

		
	}
	
	
	
	
	var comisi=$("#porcent_comisi_"+opcion).val();
	$("#comision_aplicada").val(comisi);
	
	$("#tipo_accion").val("reservar");
	$("#opcion").val(opcion);
	
	//eval("var adultos2=document.busqueda_disponibilidad.adultos-2.value();");
	//alert(adultos2);
	
	//alert("transid:"+$("#transid").val());
	
	$("#busqueda_disponibilidad").submit();
}

//Iniciar una reserva bajo peticion
function bajopeticion_iniciar(opcion){	
	//Activamos los campos de adultos, niños y cunas para que se envien
	for(var i=1; i<=4; i++) {
		ad = "adultos-"+i;
		ni = "ninos-"+i;
		cu = "cunas-"+i;
		if ($("#"+ad).length) $("#"+ad).attr("disabled", false);
		if ($("#"+ni).length) $("#"+ni).attr("disabled", false);
		if ($("#"+cu).length) $("#"+cu).attr("disabled", false);
	}
	
	var comisi=$("#porcent_comisi_"+opcion).val();
	$("#comision_aplicada").val(comisi);

	$("#tipo_accion").val("bajopeticion");
	$("#opcion").val(opcion);
	
	$("#busqueda_disponibilidad").submit();
}

//Iniciar una reserva en "Mas opciones"
function reserva_iniciar_masopc(opcion) {
	//Activamos los campos de adultos, niños y cunas para que se envien
	for(var i=1; i<=4; i++) {
		ad = "adultos-"+i;
		ni = "ninos-"+i;
		cu = "cunas-"+i;
		if ($("#"+ad).length) $("#"+ad).attr("disabled", false);
		if ($("#"+ni).length) $("#"+ni).attr("disabled", false);
		if ($("#"+cu).length) $("#"+cu).attr("disabled", false);
	}
	
	//sacamos el hotel
	var array_opcion = opcion.split('-');
	var cod_hotel = array_opcion[0];
	
	document.getElementById("tipo_accion").value="reservar";
	document.getElementById("opcion").value=opcion;
	var transid_masopc=document.getElementById("transidmopc_"+cod_hotel).value;
	
	document.getElementById("transid").value=transid_masopc;
	
	var comisi=document.getElementById("porcent_comisi_"+opcion).value;
	document.getElementById("comision_aplicada").value=comisi;

	document.getElementById("busqueda_disponibilidad").submit();
}

//Iniciar una reserva bajo peticion en "Mas opciones"
function bajopeticion_iniciar_masopc(opcion){
	//Activamos los campos de adultos, niños y cunas para que se envien
	for(var i=1; i<=4; i++) {
		ad = "adultos-"+i;
		ni = "ninos-"+i;
		cu = "cunas-"+i;
		if ($("#"+ad).length) $("#"+ad).attr("disabled", false);
		if ($("#"+ni).length) $("#"+ni).attr("disabled", false);
		if ($("#"+cu).length) $("#"+cu).attr("disabled", false);
	}
	
	//sacamos el hotel
	var array_opcion = opcion.split('-');
	var cod_hotel = array_opcion[0];
	
	document.getElementById("tipo_accion").value="bajopeticion";
	document.getElementById("opcion").value=opcion;
	var transid_masopc=document.getElementById("transidmopc_"+cod_hotel).value;
	
	document.getElementById("transid").value=transid_masopc;
	
	var comisi=document.getElementById("porcent_comisi_"+opcion).value;
	document.getElementById("comision_aplicada").value=comisi;

	document.getElementById("busqueda_disponibilidad").submit();
}


//Obtiene el desplazamiento vertical del scroll
function ScrollV() {
  var scrollv=0;
  if (typeof window.pageYOffset != 'undefined')
  {
    scrollv = window.pageYOffset;
  }
  else   {
	if (document.documentElement && document.documentElement.scrollTop) scrollv = document.documentElement.scrollTop;
	else if (document.body && document.body.scrollTop) scrollv = document.body.scrollTop;
  }
  return scrollv;
}

//Avisar y realizar la marcha atras (estamos en reservas, y voy de nuevo al listado)
function marcha_atras_comprob(aviso){
	if (confirm(aviso)){	
		document.form_marchaatras.submit();
	}
}

//Si desde la pagina principal recibimos un "marcha_atras", realizamos de nuevo la busqueda
function marcha_atras_func(n_habs_marchatras,request_marchaatras){
	n_habitaciones=n_habs_marchatras;
	consultar_disponibilidad_bbs(request_marchaatras);
}


//Obtiene el numero de dias entre 2 fechas
function dias_Entre (date1, date2) {
	var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = date2_ms - date1_ms

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)
}


//Bloquear o desbloquear el formulario tras una busqueda
function DisableEnableForm(xForm,xHow){
  objElems = xForm.elements;
  for(i=0;i<objElems.length;i++){
	if (objElems[i].type == 'text' || objElems[i].type == 'select-one' || objElems[i].type == 'checkbox') objElems[i].disabled = xHow;
  }
}

//Volver a activar el formulario una vez hecha la busqueda para realizar otra busqueda diferente
function ActivaBusqueda(activado, aviso) {
	if (activado == true) {
		if (confirm(aviso)) { 
			DisableEnableForm(document.busqueda_disponibilidad,false);
			$("#boton_cal_ini").css("visibility", "visible");
			$("#boton_cal_fin").css("visibility", "visible");
			$("#boton_inc_hab").css("visibility", "visible");
			$("#boton_dec_hab").css("visibility", "visible");
			$("#boton_inc_noches").css("visibility", "visible");
			$("#boton_dec_noches").css("visibility", "visible");
			$("#selector_fechas").css("visibility", "visible");
			$("#enviarbusqueda").css("display", "");
			$("#boton_empezar").css("display", "");
			$("#enviarbusqueda_mod").css("display", "none");
			$("#resultados").html("");
			$("#resultados").css("display", "none");
			if ($("#bu_av").attr("display") != 'undefined') $("#bu_av").show();
		}		
	} else {
		DisableEnableForm(document.busqueda_disponibilidad,true);
		$("#boton_cal_ini").css("visibility", "hidden");
		$("#boton_cal_fin").css("visibility", "hidden");
		$("#boton_inc_hab").css("visibility", "hidden");
		$("#boton_dec_hab").css("visibility", "hidden");
		$("#boton_inc_noches").css("visibility", "hidden");
		$("#boton_dec_noches").css("visibility", "hidden");
		$("#selector_fechas").css("visibility", "hidden");
		$("#enviarbusqueda").css("display", "none");
		$("#boton_empezar").css("display", "none");
		$("#enviarbusqueda_mod").css("display", "");
		if ($("#bu_av").attr("display") != 'undefined') $("#bu_av").hide();
	}
}

//Limpiar el formulario para empezar de nuevo
function limpiar_formulario(aviso) {    
	if (confirm(aviso)){
		$("#codhotel").val("");
		$("#fecha_entrada").val($("#fecha_de_hoy").val());
		$("#fecha_salida").val($("#fecha_de_manana").val());
		$("#textareaoculto").html("");
		$("#mapeo_provincia").hide();
		$("#titulo_mapeo_provincia").hide();
		document.busqueda_disponibilidad.reset();
        $('#filtro').css("display", "block");
	}
	
}

//Marcar y desmarcar radios del mapa de localidades. Y buscamos disponibilidad
function marca_radio_loc_mapa(nombre_loc){
	document.getElementById("locmap_"+nombre_loc).checked=true;
	document.getElementById("locmap_"+nombre_loc).style.background="url('images/bgradio.gif')";
	document.getElementById("loclist_"+nombre_loc).style.textDecoration ="underline";
	document.getElementById("loclist_"+nombre_loc).style.color ="#FF0000";
	
	 
}
function desmarca_radio_loc_mapa(nombre_loc){
	document.getElementById("locmap_"+nombre_loc).checked=false;
	document.getElementById("locmap_"+nombre_loc).style.background="none";
	document.getElementById("loclist_"+nombre_loc).style.textDecoration ="none";
	document.getElementById("loclist_"+nombre_loc).style.color ="#000000";
}

function disponibilidad_desde_mapa(value_localidad,nombre_loc){
	//Miramos si lo hemos pedido bajo peticion o no (si existe el campo)
	/*if ($("#solo_disponibles").length > 0) {
		if ($("#solo_disponibles").attr("checked") == true) onrequest = '0';
		if ($("#solo_disponibles").attr("checked") == false) onrequest = '2';
	} else onrequest = '0';*/
	
	//en las minoristas siempre son los verdes (jamas bajo pet)
	onrequest = '0';
	
	
	$("#localidad option[value='"+value_localidad+"']").attr("selected", "selected");
	$("#locmap_"+nombre_loc).attr("checked", true);
	$("#nombre_hotel").val("");
	
	//Y buscamos!!!!!
	consultar_disponibilidad_bbs(onrequest);	
}

//Hacer la busqueda rapida de hoteles. Si presiono la tecla ENTER redirecciono
function Busqueda_Rapida_hotel(obj, e){
	opc = false;
	tecla = (document.all) ? e.keyCode : e.which;

	if (tecla == 13) {
		location.href = 'hotel_ficha.php?codigo='+obj;	
	}
}

//Cerrar un DIV determinado
function Cerrar_Div (div) {
	$("#"+div).hide();
}

//Colorea las estrellas de los comentarios
function colorea_estab(puntos){
	puntos=parseInt(puntos);
	//coloreamos las imagenes anteriore
	for (var i=1; i <= puntos; i++){
		document.getElementById('img_valorcion_'+i).src='images/icono-sol-open-color.gif';
	}
	//y el resto en blanco y negro
	for (var j=i;j<= 5; j++){
		document.getElementById('img_valorcion_'+j).src='images/icono-sol-open-b-n.gif';
	}		
}

function resetea_puntuacion(){
	//ON MOUSE OUT
	//cuando quitamos el ratón dejamos todo como estaba hasta el último click
	var puntuacion=document.getElementById('puntuacion_estab').value;
	
	var inicio_punt=parseInt(puntuacion);
	
	for (var i=1; i <= inicio_punt; i++){
		document.getElementById('img_valorcion_'+i).src='images/icono-sol-open-color.gif';
	}		
	
	for (var j=i;j<= 5; j++){
			//alert ('img_valorcion_'+j);
		document.getElementById('img_valorcion_'+j).src='images/icono-sol-open-b-n.gif';
	}
}
function valora_estab(puntos){
	//ON CLICK
	document.getElementById('puntuacion_estab').value=puntos;		
}

//Pop-up de aviso de comentarios
function popup_uso_comentarios(){
	window.open('popup_avisos_comentarios.php','','width=750,height=230,menubar,scrollbars,resizable');
}

//Enviar un comentario de un establecimiento
function envia_comentario_estab(codigo){
	var comentario_envio=document.getElementById('comentario_envio').value;
	
	if (document.getElementById('email_agente').value=="" ){
		alert("Por favor, indique su email.");
		document.getElementById('email_agente').focus();
	}
	else if (document.getElementById('nombre_agente').value=="" ){
		alert("Por favor, indique su nombre.");
		document.getElementById('nombre_agente').focus();
	}
	else if (comentario_envio==""){
		alert("Por favor, escriba un comentario.");
		document.getElementById('comentario_envio').focus();
	}
	else if (document.getElementById('puntuacion_estab').value=="" || document.getElementById('puntuacion_estab').value==0){
		alert("Por favor, puntue el establecimiento.\n Para ello pase el ratón por encima de nuestros soles y haga click.");			
	}
	else if (document.getElementById('acepto_usos_comentario').checked!=true ){
		alert("Por favor, lea y acepte las condiciones de uso.");
		document.getElementById('acepto_usos_comentario').focus();
	}
	else{			
		document.getElementById('bot_env_com').disabled="disabled";
			
		var puntuacion=$('#puntuacion_estab').val();
		comentario_envio=urlEncode(comentario_envio);
			
		var nombre_establecimiento=$('#nombre_establecimiento').val();
		nombre_establecimiento=urlEncode(nombre_establecimiento);
			
		//Y lanzamos el ajax para grabar el comentario
		$.ajax({
			type: "POST",
			dataType: "html",
			contentType: "application/x-www-form-urlencoded",
			url: "ajax/guarda_comentario.php",
			data: 'codigo='+codigo+'&comentario='+comentario_envio+'&puntuacion='+puntuacion+"&nombre_agente="+document.getElementById('nombre_agente').value+'&nombre_establecimiento='+nombre_establecimiento+"&email_agente="+document.getElementById('email_agente').value,
				success: function(datos){
					$("#resultado_envio_comentario").show();
					$("#resultado_envio_comentario").html(datos);					
				},
				error: function(obj, quepaso, obj2){
					//alert("Ha habido un error: "+quepaso);
				}
		});
	}	
}

function ver_form_comentario_hotel(codigo) {
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/ver_form_comentario_hotel.php",
		data: 'codigo='+codigo,
			success: function(datos){
				$('#div_form_com_hot').html(datos);					
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
} 
	
function Poner_Valoracion()	{
	tabla = document.getElementById('precios');
	filas = tabla.getElementsByTagName("tr");
	num_filas = filas.length;
	
	for (i=0;i<num_filas;++i) {
		celda1 = document.createElement("td");
		celda2 = document.createElement("td");
		
		//Dependiendo del numero de fila que sea, pongo una cosa o pongo otra
		if (i == 0) {
			celda1.innerHTML = "Precio";
			celda2.innerHTML = "Bruto";
		}
		if (i == 1) {
			celda1.innerHTML = "<hr>";
			celda2.innerHTML = "<hr>";
		}
		filas[i].appendChild (celda1);
		filas[i].appendChild (celda2);
	}
} 


function presupuestos_avanzados(hotel, disponible, tipo_listado){
	opciones = recupera_opciones();
	opciones += '&onrequest=3';
	opciones += '&codestab='+hotel;
	opciones += '&poner_disponibles=1';
	opciones += '&mayorista='+$("#tipo_mayorista").val();
	
	//Cogemos el HTML de la tabla ya generada
	var html_actual = $("#resultado_"+hotel).html();
	$("#listado_rec").html(html_actual);
	$("#listado_rec input:checkbox, #listado_rec img, #listado_rec td[id*='masopc_'], #listado_rec input:button, #listado_rec .listado_check, #listado_rec a[@class*='url_video'], #listado_rec a[@class*='url_foto'], #listado_rec input:hidden, #listado_rec #checkear_todos, #listado_rec .listado_servicios, #listado_rec .opciones_hotel, #listado_rec a[@class*='mas_tipos_hab']").each( function (){
		$(this).remove();
	});
	$("#listado_rec tr").each( function (){
		$(this).css("font", "normal 9px Tahoma");
	});
	html_actual = urlEncode($("#listado_rec").html());
	
	//Calculamos el "Mas opciones"
	$("#listado_rec").html("");
	$.ajax({
		type: "POST",
		dataType: "html",
		async: false,
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/reservas_consultar_hotel.php",
		data: opciones,
			success: function(datos){
				if (datos == 'KO-SESSION' || datos == 'KO-PERM') Alert_Error (datos);
				else $("#listado_rec").html(datos); 
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
	$("#listado_rec input:checkbox, #listado_rec a[@class*='calendario_disp'], #listado_rec a[@class*='url_video'], #listado_rec a[@class*='url_foto'], #listado_rec img[@src*= 'jpg'], #listado_rec img[@src*= 'gif'], #listado_rec input:button, #listado_rec .listado_check, #listado_rec .listado_foto, #listado_rec input:hidden, #listado_rec #checkear_todos, #listado_rec .listado_servicios, #listado_rec .opciones_hotel, #listado_rec div[id*='div_flotante_']").each( function (){
		$(this).remove();
	});
	$("#listado_rec tr").each( function (){
		$(this).css("height", "1px");
		$(this).css("font", "normal 9px Tahoma");
	});
	var html_masopc = urlEncode($("#listado_rec").html());
	$("#listado_rec").html("");
	
	//Si quiero mandar el mail, cojo los emails de destino y el posible comentario
	if (tipo_listado == 'mail') {
		mails = $("#correos_electronicos_"+hotel).val();
		comentario = $("#comentario_envio_"+hotel).val();
	} else {
		mails = '';
		comentario = '';
	}

	//Mando estas opciones por POST a la pagina que se encarga de mostrar el resultado
	$.post("ajax/imprimir_avanzado.php", {
		"actual": html_actual,
		"mas_opc": html_masopc,
		"idhotel": hotel,
		"llegada": $("#fecha_entrada").val(),
		"salida": $("#fecha_salida").val(),
		"tipo": tipo_listado,
		"mails": mails,
		"comentario": comentario,
		"disponible": disponible
	}, function(data){
		if (tipo_listado == 'print') {
			var printWin = window.open("","printSpecial");
			printWin.document.open();
			printWin.document.write(data);
			printWin.document.close();
			printWin.print();	
		} else {
			$("#res_envio_"+hotel).css("border", "1px solid #fff");
			$("#res_envio_"+hotel).css("font", "normal 11px Tahoma");
			$("#res_envio_"+hotel).show();
			$("#res_envio_"+hotel).html("<img src='images/cargando.gif' width='20'>");
			$("#res_envio_"+hotel).html(data);	
		}
//		var iframe=document.createElement('IFRAME'); 
//		var doc=null; 
//		$(iframe).attr('style','position:absolute;width:0px;height:0px;left:-500px;top:-500px;'); 
//		document.body.appendChild(iframe); 
//		doc=iframe.contentWindow.document; 
//		doc.write(data); 
//		doc.close(); 
//		iframe.contentWindow.focus(); 
//		iframe.contentWindow.print(); 
//		wait(1); 
//		document.body.removeChild(iframe); 
    });
}

function ver_bono(codigo,dni)
	{
		
		window.open('reservas_ver_bono.php?codigo='+codigo+"&dni="+dni,'','width=700,height=600,menubar,scrollbars,resizable');
	}

function formoferta(img_grande,tit_oferta){
	var opciones='imagen='+"'"+img_grande+"'"+'&titulo='+"'"+tit_oferta+"'";
	
	dlg_img_oferta_click.hide(); 
	
	$.ajax({
		type: "POST",
		dataType: "html",
		async: false,
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/formulario_ofertas.php",
		data: opciones,
			success: function(datos){
				
				document.getElementById("formulario_ofertas").innerHTML = datos;
				dlg_form_oferta.show();
				
			},
			error: function(obj, quepaso, obj2){
				//alert("Ha habido un error: "+quepaso);
			}
	});
}


function enviar_peticion_info_ofertas(){
	var res = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
	if (document.getElementById("nombre_ofertas").value!=""){
		if (document.getElementById("email_ofertas").value!="" && res.test(document.getElementById("email_ofertas").value)){ 
			if (document.getElementById("he_leido").checked){
			var iddiv='peticion_info_ofertas';
			
			var opciones = 'nombre_rellamada='+document.getElementById("nombre_ofertas").value;
				opciones+='&telefono_rellamada='+document.getElementById("telefono_ofertas").value;
				opciones+='&email_destino='+document.getElementById("email_destino_ofertas").value;
				opciones+='&email_peticion='+document.getElementById("email_ofertas").value;
				opciones+='&obs='+document.getElementById("obs_ofertas").value;
				opciones+='&titulo_oferta='+document.getElementById("titulo_ofertas").value;
				opciones+='&foto_ofertas='+document.getElementById("foto_ofertas").value;
				
				$.ajax({
							type: "POST",
							dataType: "html",
							contentType: "application/x-www-form-urlencoded",
							url: "ajax/envio_info_ofertas.php",
							data: opciones,
								beforeSend: function(objeto){
									//$('#'+iddiv).show();
									//$('#'+iddiv).html("<img src='images/cargando.gif'>");
								},
								success: function(datos){
									
							alert("Sus datos se han recibido correctamente.Le responderemos a la mayor brevedad.\n¡Muchas gracias!");
									
									$('#'+iddiv).css("display","block");
									$('#'+iddiv).html(datos);
								},
								error: function(obj, quepaso, obj2){
									//alert("Ha habido un error: "+quepaso);
								}
					});
			}else{
				alert("Para usar este servicio debe leer y aceptar las condiciones de uso");
			}
		}else{
			alert("Por favor indique algún email para poder informarle.\nMuchas Gracias");
		}
	}else{
		alert("Por favor indiquenos su nombre para dirigirnos a usted.\nMuchas Gracias");
	}
}

function agranda_oferta_click(img_grande,tit_oferta){
	
	dlg_img_oferta_click.show();
	//document.getElementById("div_imagen_oferta_click").innerHTML = '<table border="0" cellpadding="0" cellspacing="0" width="600px"><tr><td align="left"><b>'+tit_oferta+'</b></td><td align="center"><a href="javascript:void(0);" onclick="formoferta('+"'"+img_grande+"'"+','+"'"+tit_oferta+"'"+');" ><img src="../../images/btnsolinfo.png" alt="Agencia Viajes Benamar: Solicitar Informacion de informacion" border="0"/></a></td><td align="right"><b><a href="javascript:quita_oferta_click();">CERRAR[X]</a></b></td></tr></table><img src="'+img_grande+'" width="600px">';
    document.getElementById("div_imagen_oferta_click").innerHTML = '<table border="0" cellpadding="0" cellspacing="0" width="600px"><tr><td align="left"><b>'+tit_oferta+'</b></td><td align="center"><a href="javascript:void(0);" onclick="formoferta('+"'"+img_grande+"'"+','+"'"+tit_oferta+"'"+');" ><img src="../../images/btnsolinfo.png" alt="Agencia Viajes Benamar: Solicitar Informacion de informacion" border="0"/></a></td><td align="right"><b><a href="javascript:quita_oferta_click();"><img src="../../images/cerrar.png" ></a></b></td></tr></table><img src="'+img_grande+'" width="600px">';
	//recordamos q img es para no ocultarla en el onmouseout
	//document.getElementById("img_cliqueada").value=img_grande;
}

function agranda_oferta_listado(img_grande,tit_oferta){
	
	dlg_img_oferta_click.show();
	document.getElementById("div_imagen_oferta_click").innerHTML = '<table border="0" cellpadding="0" cellspacing="0" width="600px"><tr><td align="left"><b>'+tit_oferta+'</b></td><td><a href="javascript:void(0);" onclick="formoferta('+"'"+img_grande+"'"+','+"'"+tit_oferta+"'"+');" ><img src="../../images/btnsolinfo.png" alt="Agencia Viajes Benamar: Solicitar Informacion de informacion" border="0"/></a></td><td align="right"><b><a href="javascript:quita_oferta_click();"><img src="../../images/cerrar.png" ></a></b></td></tr></table><img src="'+img_grande+'" width="600px">';}

function agranda_oferta(img_grande,tit_oferta){
	
	dlg_img_oferta.show();
	document.getElementById("div_imagen_oferta").innerHTML = '<div align="center"><b>'+tit_oferta+'</b></div><img src="'+img_grande+'" width="250px">';
	
}

function quita_oferta(img){
	
		dlg_img_oferta.hide(); 
	
}

function quita_oferta_click(img){
	dlg_img_oferta_click.hide(); 
}

function ver_oferta(codigo, nombre_fichero){
    window.open('contenidos/ofertas/'+codigo+'/'+nombre_fichero,'','width=700,height=600,menubar,scrollbars,resizable');
} 


/*function ver_oferta(nombre_fichero,titulo) {

	opciones = 'nombre_imagen='+nombre_fichero;
	$.ajax({
		type: "POST",
		dataType: "html",
		contentType: "application/x-www-form-urlencoded",
		url: "ajax/crear_png_ofertas_andalucia.php",
		data: opciones,
			beforeSend: function(objeto){
				
			},
			success: function(datos){
				agranda_oferta_listado(datos,titulo);			
			},
			error: function(obj, quepaso, obj2){
				alert("Ha habido un error: comuniquese con el administrador ");
			}
	});
}*/

/*function comprobar_fechas()
{

    alert("comprobing...");

	var f = document.getElementById('busqueda_disponibilidad');
	fini_seleccionada = f.fecha_entrada.value;
	ffin_seleccionada = f.fecha_salida.value;
	
	var dateIniSeleccionada = new Date();
	aux = fini_seleccionada.split("-");
	dateIniSeleccionada.setFullYear(aux[0], aux[1]-1, aux[2]);
	
	var dateFinSeleccionada = new Date();
	aux = ffin_seleccionada.split("-");
	dateFinSeleccionada.setFullYear(aux[0], aux[1]-1, aux[2]);
	
	fhoy_value = f.fecha_de_hoy.value;
	var dateFechaHoy = new Date();
	aux = fhoy_value.split("-");
	dateFechaHoy.setFullYear(aux[0], aux[1]-1, aux[2]);
	
	var fNochesControl= f.num_noches.value;
	var NumNochesControl = parseInt(fNochesControl);
	if (NumNochesControl>31){
		alert("Lo sentimos: Las reservas de más de 1 mes, NO están permitidas por la WEB.\nNuestro Booking estará encantado de atenderle en el "+f.telefono_booking.value);
			
			return true;
	}
	
	
	if (g_inioferta != 0)
	{
		
		
		var dateIniOferta = new Date();
		aux = g_inioferta.split("-");
		dateIniOferta.setFullYear(aux[0], aux[1]-1, aux[2]);
		var dateFinOferta = new Date();
		aux = g_finoferta.split("-");
		dateFinOferta.setFullYear(aux[0], aux[1]-1, aux[2]);
		
		alert(dateIniSeleccionada+ " < " + dateIniOferta);
		
		if (dateIniSeleccionada < dateIniOferta)
		{
			alert('La fecha de entrada ha de estar en el periodo de vigencia de la oferta.\n\nFecha Inicio Oferta: '+g_inioferta+'\nFecha Fin Oferta: '+g_finoferta);
			return true;
		}
		
		//realmente la salida es de un dia más!!!!!
		var dateFinOferta_mas_uno=sumaDias(dateFinOferta,1);
		
		if (dateFinSeleccionada > dateFinOferta_mas_uno)
		{
			alert('La fecha de salida ha de estar en el periodo de vigencia de la oferta.\n\nFecha Inicio Oferta: '+g_inioferta+'\nFecha Fin Oferta: '+g_finoferta);
			return true;
		}
	}
	
	
	if (f.soy_de_prepago.value==1){
		//alert(f.fecha_de_hoy.value);
		//alert(f.fecha_de_manana.value);
		var fmanana_value = f.fecha_de_manana.value;
		var dateFechaManana = new Date();
		aux = fmanana_value.split("-");
		//atencion la fecha de mana esta en formato spanish guay
		//dateFechaManana.setFullYear(aux[0], aux[1]-1, aux[2]);
		dateFechaManana.setFullYear(aux[2], aux[1]-1, aux[0]);
	
		if (dateIniSeleccionada<dateFechaManana){
			//alert("Las reservas sólo pueden ser realizadas a partir del "+f.fecha_de_pasao_manana.value+"\nNuestro Booking estará encantado de atenderle en el "+f.telefono_booking.value);
			//alert("Las reservas NO pueden ser realizadas a día pasado\nNuestro Booking estará encantado de atenderle en el "+f.telefono_booking.value);
			
			alert("Las reservas sólo pueden ser realizadas a partir del "+f.fecha_de_manana.value+"\nNuestro Booking estará encantado de atenderle en el "+f.telefono_booking.value);
			
			return true;
		}
	}
	else{
	
		if (dateIniSeleccionada<dateFechaHoy){
			//alert("Las reservas sólo pueden ser realizadas a partir del "+f.fecha_de_manana.value+"\nNuestro Booking estará encantado de atenderle en el "+f.telefono_booking.value);
			alert("Las reservas NO pueden ser realizadas a día pasado\nNuestro Booking estará encantado de atenderle en el "+f.telefono_booking.value);
			return true;
		}
	
	}
	
	
	return false;
}*/

function ver_info_anulacion(codigo)
	{
		
		window.open('politicas_cancelacion.php?localizador='+codigo,'','width=550,height=250,menubar,scrollbars,resizable');
	}
