/***********************************
		  MOTOR PRINCIPAL
************************************/

// Mostrar la capa fondo y la ventana
function mrh_mostrar(idhotel){
	// Se carga la pantalla principal del motor
	$("#mrh_carga").css("visibility", "visible");
    $("#mrh_procesa").load("motor.php?idhotel="+idhotel, function(){
		$("#mrh_carga").css("visibility", "hidden");
		document.getElementById('mrh_procesa').style.visibility='visible';
	});
}

// Ocultar la capa fondo y la ventana
function mrh_ocultar(){
	if(document.getElementById('motor2').style.visibility=='visible'){
		document.getElementById('motor2').style.visibility='hidden';
	}
	document.getElementById('mrh_procesa').style.visibility='hidden';
}

/***********************************
		  MÓDULO IZQUIERDA
************************************/

// Obtiene la diferencia de días entre dos fechas
function DiferenciaFechas (var1,var2,var3,var4,var5,var6) {  
	//Obtiene los datos del formulario  
	CadenaFecha2 = document.getElementById('mrh_start').value;
	CadenaFecha1 = document.getElementById('mrh_end').value;
	
	if(CadenaFecha2!='' && CadenaFecha1 !=''){
		//Obtiene dia, mes y año  
		var fecha1 = new fecha(CadenaFecha1); 
		var fecha2 = new fecha(CadenaFecha2); 
		  
		//Obtiene objetos Date  
		var miFecha1 = new Date(fecha1.anio, fecha1.mes-1, fecha1.dia);
		var miFecha2 = new Date(fecha2.anio, fecha2.mes-1, fecha2.dia);
		
		//Resta fechas y redondea  
		var diferencia = parseFloat(miFecha1.getTime() - miFecha2.getTime());
		var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));

		if(dias<=0){
			$("#diff_fechas").append("<br /><span style='color: red;'>"+var1+"</span>");
		}else{
			$("#diff_fechas").html("<input type='text' id='mrh_nights' size='1' onchange='mrh_aumenta(\""+var3+"\",\""+var4+"\",\""+var5+"\",\""+var6+"\"); mrh_precio_total();' value='"+dias+"' /> "+var2);
			if(dias>31){
				$("#diff_fechas").append("<br /><span style='color: red;'>"+var5+"</span>");
				document.getElementById("mrh_nights").value=31;
			}
		}
	}
	return false;
}  
   
// Separa un fecha en formato dd/mm/aaaa en día, mes y año por separado
function fecha(cadena) {  
	var separador = "/";
	//Separa por dia, mes y año  
	if(cadena.indexOf(separador)!=-1) {  
		 var posi1 = 0;
		 var posi2 = cadena.indexOf(separador, posi1+1);
		 var posi3 = cadena.indexOf(separador, posi2+1);
		 this.dia = cadena.substring(posi1,posi2);
		 this.mes = cadena.substring(posi2+1,posi3);
		 this.anio = cadena.substring(posi3+1,cadena.length);
	}else{  
		 this.dia = 0;
		 this.mes = 0; 
		 this.anio = 0;     
	}  
} 

// Suma un número de días a una fecha determinada
function mrh_aumenta(var1,var2,var3,var4) { 
	num=document.getElementById('mrh_nights').value;
	f=document.getElementById('mrh_start').value; 
	
	if(f!=''){
		if(num>0 && num<=31){
			f=f.split('/'); 
			f=f[1]+'/'+f[0]+'/'+f[2]; 
			
			hoy=new Date(f); 
			hoy.setTime(hoy.getTime()+num*24*60*60*1000); 
			
			mes=hoy.getMonth()+1; 
			if(mes<=9) mes='0'+mes; 
			dia=hoy.getDate();
			if(dia<=9) dia='0'+dia;
			
			res=dia+'/'+mes+'/'+hoy.getFullYear(); 
			document.getElementById('mrh_end').value=res;  
			$("#diff_fechas").html("<input type='text' id='mrh_nights' value='"+num+"' onchange='mrh_aumenta(\""+var1+"\",\""+var2+"\",\""+var3+"\",\""+var4+"\"); mrh_precio_total();' size='1'/> "+var1);
		}else{
			if(num<=0){
				$("#diff_fechas").append("<br /><span id='mrh_error' style='color: red;'>"+var2+"</span>");
			}
			if(num>31){
				$("#diff_fechas").append("<br /><span id='mrh_error' style='color: red;'>"+var3+"</span>");
				document.getElementById("mrh_nights").value=31;
			}
		}
	}else{
		document.getElementById("mrh_nights").value="";
		$("#diff_fechas").append("<br /><span id='mrh_error' style='color: red;'>"+var4+"</span>");
	}
} 

/***********************************
		  MÓDULO CENTRO
************************************/

// Carga las pestañas de habitaciones, paquetes y servicios
function mrh_tabs(){
	$('#mrh_contenido').tabs({ fxFade: true, fxSpeed: 'fast' });
}

// Realiza la búsqueda de habitaciones disponibles en el hotel
function mrh_busqueda(){
	window.parent.$("#mrh_cargando").css("visibility", "visible");
	window.parent.$("#mrh_cargando").fadeIn("normal");
	if(window.parent.frames[0].document.getElementById("mrh_start")){
		lafechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	}else{
		lafechai="empty";	
	}
	if(window.parent.frames[0].document.getElementById("mrh_nights")){
		losdias=window.parent.frames[0].document.getElementById("mrh_nights").value;	
	}else{
		losdias="empty";	
	}

	window.parent.$("#mrh_res_hab").load("busqueda.php?lfechai="+lafechai+"&ldias="+losdias, function(){
		window.parent.$("#mrh_cargando").fadeOut("slow");	
	});
}

// Lista seleccionable de habitaciones y paquetes
function mrh_cambiaclase(idhab,id,tope,tipo){
	if(tipo!='paq'){
		for(i=1;i<=tope;i++){
			document.getElementById(i).className='selectable';
			
			// Poner todos los input de cantidad en blanco
			elemento=document.getElementsByTagName("input");
			for(j=0;j<elemento.length;j++){
				ide=elemento[j].id
				if(ide.substring(0,1)=="c"){
					elemento[j].className='white';
				}
			}
		}
		document.getElementById(id).className='selectableon';
		document.getElementById("c"+idhab).className='wblue';
	}else{
		for(i=1;i<=tope;i++){
			document.getElementById('paq'+i).className='selectable';
		}
		document.getElementById(id).className='selectableon';
	}
}

// Incluye un archivo CSS desde JavaScript
function includeCSS(p_file) {
	var v_css  = document.createElement('link');
	v_css.rel = 'stylesheet'
	v_css.type = 'text/css';
	v_css.href = p_file;
	document.getElementsByTagName('head')[0].appendChild(v_css);
}

// Añade tantos combos de configuración como número de habitaciones se seleccionen
function mrh_addh(div,id,min_adultos,max_adultos,max_ninios,regimen,var1,var2,var3,var4,var5,var6,var7){
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	
	if(fechai!='' && dias!=''){	
		tope=document.getElementById("c"+id).value;
		$("#mrh_config"+div).html("");
	
		if(tope>0 && tope <=5){
			for(i=1;i<=tope;i++){
				// Se crean los select de adultos niños y regímenes
				if(max_ninios>0){
					if(id==9){
						$("#mrh_config"+div).append("<b>#"+i+":</b> "+var1+" <select id='a-"+id+"-"+i+"' onchange='mrh_comprueba("+i+"); mrh_conteo(); mrh_precio_total();'></select> "+var2+" <select id='n-"+id+"-"+i+"' onchange='mrh_conteo(); mrh_precio_total();'></select> <img src='/mrh/mrh_imagenes/info.png' onMouseOver='Tip(\""+var6+"\", TITLE, \"<img src=/mrh/mrh_imagenes/ayuda.png> "+var7+"\", WIDTH, 350)' onMouseOut='UnTip()' /> "+var3+" <select id='r-"+id+"-"+i+"' onchange='mrh_precio_total();'></select> <img src='/mrh/mrh_imagenes/info.png' onMouseOver='Tip(\""+var4+"\", TITLE, \"<img src=/mrh/mrh_imagenes/ayuda.png> "+var5+"\")' onMouseOut='UnTip()' /><br />");
					}else{
						$("#mrh_config"+div).append("<b>#"+i+":</b> "+var1+" <select id='a-"+id+"-"+i+"' onchange='mrh_conteo(); mrh_precio_total();'></select> "+var2+" <select id='n-"+id+"-"+i+"' onchange='mrh_conteo(); mrh_precio_total();'></select> <img src='/mrh/mrh_imagenes/info.png' onMouseOver='Tip(\""+var6+"\", TITLE, \"<img src=/mrh/mrh_imagenes/ayuda.png> "+var7+"\", WIDTH, 350)' onMouseOut='UnTip()' /> "+var3+" <select id='r-"+id+"-"+i+"' onchange='mrh_precio_total();'></select> <img src='/mrh/mrh_imagenes/info.png' onMouseOver='Tip(\""+var4+"\", TITLE, \"<img src=/mrh/mrh_imagenes/ayuda.png> "+var5+"\")' onMouseOut='UnTip()' /><br />");
					}
				}else{
					$("#mrh_config"+div).append("<b>#"+i+":</b> "+var1+" <select id='a-"+id+"-"+i+"' onchange='mrh_conteo(); mrh_precio_total();'></select> "+var3+" <select id='r-"+id+"-"+i+"' onchange='mrh_conteo(); mrh_precio_total();'></select> <img src='/mrh/mrh_imagenes/info.png' onMouseOver='Tip(\""+var4+"\", TITLE, \"<img src=/mrh/mrh_imagenes/ayuda.png> "+var5+"\")' onMouseOut='UnTip()' /><br />");
				}
			}
			
			// Se añaden los option con número de adultos
			for(j=1;j<=tope;j++){
				for(k=min_adultos;k<=max_adultos;k++){
					document.getElementById("a-"+id+"-"+j).options[k-min_adultos]=new Option(k,k);
				}
			}
			
			// Se añaden los option con número de niños
			if(max_ninios>0){
				for(j=1;j<=tope;j++){
					for(k=0;k<=max_ninios;k++){
						document.getElementById("n-"+id+"-"+j).options[k]=new Option(k,k);
					}
				}	
			}
			
			// Se añaden los regímenes según la codificación binaria
			regimen=regimen.split('-');
			for(j=1;j<=tope;j++){
				num=0;
				for(k=0;k<=4;k++){
					switch(k){
						case 0:
							if(parseInt(regimen[k])==1){
								document.getElementById("r-"+id+"-"+j).options[num]=new Option("SA","SA");
								num++;
							}
							break;
						
						case 1:
							if(parseInt(regimen[k])==1){
								document.getElementById("r-"+id+"-"+j).options[num]=new Option("AD","AD");	
								num++;
							}
							break;
							
						case 2:
							if(parseInt(regimen[k])==1){
								document.getElementById("r-"+id+"-"+j).options[num]=new Option("MP","MP");	
								num++;
							}
							break;
						
						case 3:
							if(parseInt(regimen[k])==1){
								document.getElementById("r-"+id+"-"+j).options[num]=new Option("PC","PC");
								num++;
							}
							break;
							
						case 4:
							if(parseInt(regimen[k])==1){
								document.getElementById("r-"+id+"-"+j).options[num]=new Option("TI","TI");	
								num++;
							}
							break;
					}
				}
			}
		}else{
			if(tope>5){
				$("#mrh_config"+div).append("<span style='color: red;'>El máximo de habitaciones que puede reservar es 5.</span>");
			}
		}
	}
}

//  Comprueba si el número de adultos en la junior suite es 3 y en caso afirmativo sólo permite seleccionar un niño
function mrh_comprueba(num){
	if(document.getElementById("a-9-"+num).value==3){
		document.getElementById("n-9-"+num).options[2]=null;	
	}else{
		if(document.getElementById("n-9-"+num).length==2){
			document.getElementById("n-9-"+num).options[2]=new Option("2","2");
		}
	}
}

// Cuenta el número de habitaciones, adultos y niños
function mrh_conteo(){
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	
	if(fechai!='' && dias!=''){	
		elemento=document.getElementsByTagName("input");
		var total_adultos=0;
		var total_ninios=0;
		var total_habitaciones=0;
		
		// HALLAR NÚMERO DE HABITACIONES
		// Recorro todos los input text del formulario
		for(i=0;i<elemento.length;i++){
			// Se cogen solo los elementos tipo text
			if(elemento[i].type=="text" && elemento[i].value!="" && elemento[i].value!=0){
				id=elemento[i].id;
				// Se comprueba que el id del input comienza con c de "cantidad"
				if(id.substring(0,1)=="c"){
					// Se suman al número de habitaciones total	
					total_habitaciones+=parseInt(elemento[i].value);
				}
			}
		} 
		
		// HALLAR NÚMERO DE ADULTOS Y NIÑOS
		opcion=document.getElementsByTagName("select");
		// Se recorren todos los select de las habitaciones
		for(j=0;j<opcion.length;j++){
			ido=opcion[j].id;
			
			switch(ido.substring(0,1)){
				case "a":
					total_adultos+=parseInt(opcion[j].value);
					break;
				
				case "n":
					total_ninios+=parseInt(opcion[j].value);
					break;
			}
		}
		window.parent.frames[0].document.getElementById("mrh_total_habitaciones").value=total_habitaciones;
		window.parent.frames[0].document.getElementById("mrh_total_adultos").value=total_adultos;
		window.parent.frames[0].document.getElementById("mrh_total_ninios").value=total_ninios;
	}
}

var total_price=0;
// Halla el precio total de la reserva elegida
function mrh_precio_total(){
	var llamada;
	window.parent.frames[0].document.getElementById('mrh_precio_total').value="";
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	
	// Tiene que haber una fecha de inicio y un número de días para calcular el precio
	if(fechai!='' && dias!=''){
		llamada="fechai="+fechai+"&dias="+dias;
		window.parent.frames[0].$("#mrh_total_reserva").load("unset.php", function(){
			elemento=window.parent.document.getElementsByTagName("input");
			for(i=0;i<elemento.length;i++){
				// Se recorren todos los tipos de habitaciones cuyo valor sea distinto de 0
				if(elemento[i].type=="text" && elemento[i].value!="" && elemento[i].value!=0 && elemento[i].value<=5){
					id=elemento[i].id;
					if(id.substring(0,1)=="c"){
						id=id.substring(1);
		
						// Se recorren todas las configuraciones de esta habitación
						tope=parseInt(elemento[i].value);
						for(j=1;j<=tope;j++){
							// Se obtiene el número de adultos de esta configuración
							if(window.parent.document.getElementById("a-"+id+"-"+j)){
								nadultos=window.parent.document.getElementById("a-"+id+"-"+j).value;
							}
							// Se obtiene el número de niños de esta configuración (si los hay)
							if(document.getElementById("n-"+id+"-"+j)){
								nninios=window.parent.document.getElementById("n-"+id+"-"+j).value;
							}else{
								nninios=0;	
							}
							// Se obtiene el regimen de esta configuración
							regimen=window.parent.document.getElementById("r-"+id+"-"+j).value;
							llamada=llamada+"&id"+i+j+"="+id+"&na"+i+j+"="+nadultos+"&nn"+i+j+"="+nninios+"&reg"+i+j+"="+regimen;
						}
					}
				}
			} 
			// Se carga el archivo PHP que procesa los datos y devuelve el precio
			window.parent.frames[0].$("#mrh_total_reserva").load("calcula_precio.php?"+llamada, function(){																						 
				mrh_precio_servicio();																						 
			});
		});
	}
}

// Halla el precio de los servicios
function mrh_precio_servicio(){
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	elemento=window.parent.document.getElementsByTagName("input");
	llamada="activa=true";
	// Se recorren todos los servicios cuya cantidad sea distinta de 0
	// Y cuyo id comience por "ser" de servicio
	for(i=0;i<elemento.length;i++){
		id=elemento[i].id;
		if(id.substring(0,3)=="ser"){
			if(elemento[i].value!=0 && elemento[i].value<=5){
				cantidad=elemento[i].value;
				// Se ejecuta el archivo que calculará el precio de los servicios
				llamada=llamada+"&id"+i+"="+id+"&cantidad"+i+"="+cantidad;
			}
		}
	}
	window.parent.frames[0].$("#mrh_total_reserva").load("calcula_servicio.php?"+llamada);
}

// Suma o resta 1 a la cantidad de la habitación seleccionada
function mrh_cantidad(tipo,div,var1,var2){
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	
	if(fechai!='' && dias!=''){	
		if(tipo=="+"){
			if(document.getElementById("c"+div).value<5){
				document.getElementById("c"+div).value=parseInt(document.getElementById("c"+div).value)+1;
			}
		}else{
			if(document.getElementById("c"+div).value>0){
				document.getElementById("c"+div).value=parseInt(document.getElementById("c"+div).value)-1;
			}
		}
	}else{
		jAlert(var1,var2);
	}
}

// Suma o resta 1 a la cantidad del servicio seleccionado
function mrh_cantidad_ser(tipo,div,var1,var2){
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	
	if(fechai!='' && dias!=''){	
		if(tipo=="+"){
			if(document.getElementById("ser"+div).value<5){
				document.getElementById("ser"+div).value=parseInt(document.getElementById("ser"+div).value)+1;
			}
		}else{
			if(document.getElementById("ser"+div).value>0){
				document.getElementById("ser"+div).value=parseInt(document.getElementById("ser"+div).value)-1;
			}
		}
	}else{
		jAlert(var1,var2);
	}
}

/***********************************
		  MÓDULO DERECHA
************************************/

// Detecta la resolución de la pantalla y si es demasiado pequeña
// Muestra una versión más pequeña de la parte derecha del motor
function mrh_resolucion(){
	if($(window).height()>500){
		$('#mrh_right').load('derecha.php');
	}else{
		$('#mrh_right').load('derecha-min.php');
	}
}

// Carga las fotos de las habitaciones dentro del div mrh_foto_hab
function mrh_fotos(url){
	$("#mrh_foto_hab").html("<img src='"+url+"' border='0' width='100%' />");
}

// Carga las fotos de los paquetes dentro del div mrh_foto_paq
function mrh_fotos_p(url){
	$("#mrh_foto_paq").html("<img src='"+url+"' border='0' width='100%' />");
}

// Muestra un div de "cargando" y muestra automáticamente la segunda parte del motor
function mrh_load(var1,var2){
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	totalhab=window.parent.frames[0].document.getElementById("mrh_total_habitaciones").value;
	
	// Tiene que haber una fecha de inicio y un número de días para calcular el precio
	if(fechai!='' && dias!='' && dias<31 && totalhab>0){
		document.getElementById("mrh_load").style.visibility='visible';
		totalres=window.parent.frames[0].document.getElementById('mrh_precio_total').value;
		$("#mrh_load").load("loading.php?total="+totalres+"&dias="+dias+"&nhab="+totalhab);
	}else{
		jAlert(var1,var2);	
	}
}

// Continua con la segunda y última parte de la reserva
function mrh_continuar_reserva(){
	fechai=window.parent.frames[0].document.getElementById("mrh_start").value;
	dias=window.parent.frames[0].document.getElementById("mrh_nights").value;
	
	// Tiene que haber una fecha de inicio y un número de días para calcular el precio
	if(fechai!='' && dias!=''){
		$("#motor2").load("motor2.php");
		document.getElementById("mrh_load").style.visibility='hidden';
		document.getElementById("motor2").style.visibility='visible';
	}
}

/*****************************
	SEGUNDA PARTE DEL MOTOR
******************************/

/* CENTRO */

// Desactiva el campo de provincias al seleccionar un país que no sea España.
// Se vuelve a activar al seleccionar España.
function mrh_paises(pais){
	if(pais!="Spain"){
		$('#mrh_provincias').attr("disabled", true); 
	}else{
		$("#mrh_provincias").removeAttr("disabled");
	}
}

// Reemplaza los espacios por el símbolo '+' para pasar datos por GET en una URL
function codifica(string){
	string=string.replace(/ /gi, "+");
	return string;
}

// Realiza la inserción de la reserva en la base de datos
function mrh_guardar_reserva(){
	// Datos cliente
	ftrato=document.getElementById("mrh_trato").value;
	fnombre=codifica(document.getElementById("mrh_nombre").value);
	fapellidos=codifica(document.getElementById("mrh_apellidos").value);
	ftelefono=codifica(document.getElementById("mrh_tlf").value);
	femail=document.getElementById("mrh_email").value;
	fpais=codifica(document.getElementById("mrh_pais").value);
	fprovincia=codifica(document.getElementById("mrh_provincias").value);
	fciudad=codifica(document.getElementById("mrh_ciudad").value);
	fdireccion=codifica(document.getElementById("mrh_direccion").value);
	fcp=codifica(document.getElementById("mrh_cp").value);
	if(document.getElementById("mrh_observaciones").value!=""){
		fobservaciones=codifica(document.getElementById("mrh_observaciones").value);
	}else{
		fobservaciones="";
	}
	if(document.getElementById("mrh_newsletter").checked==true){
		fautoriza=1;
	}else{
		fautoriza=0;
	}
	if(document.getElementById("mrh_contrato").checked==true){
		fcontrato=1;
	}else{
		fcontrato=0;
	}
	// Datos reserva
	fechaen=window.parent.frames[0].document.getElementById("mrh_start").value;
	fechasa=window.parent.frames[0].document.getElementById("mrh_end").value;
	nnoches=window.parent.frames[0].document.getElementById("mrh_nights").value;

	$("#mrh_formu").load("guardar_reserva.php?trato="+ftrato+"&nombre="+fnombre+"&apellidos="+fapellidos+"&telefono="+ftelefono+"&email="+femail+"&pais="+fpais+"&provincia="+fprovincia+"&ciudad="+fciudad+"&direccion="+fdireccion+"&cp="+fcp+"&observaciones="+fobservaciones+"&autoriza="+fautoriza+"&contrato="+fcontrato+"&fecha_i="+fechaen+"&fecha_f="+fechasa+"&noches="+nnoches);
}