// JavaScript Document
/*

	LISTA DE EQUIVALENCIAS DE ACENTOS
	\u00e1 -> á 
	\u00e9 -> é 
	\u00ed -> í 
	\u00f3 -> ó 
	\u00fa -> ú 
	\u00c1 -> Á 
	\u00c9 -> É 
	\u00cd -> Í 
	\u00d3 -> Ó 
	\u00da -> Ú 
	\u00f1 -> ñ 
	\u00d1 -> Ñ 
*/

function dameListaAlojamientosFiltro(sel) {
	var idLocalidad = sel.options[sel.selectedIndex].value;
	if (idLocalidad == "") {
		document.getElementById('lista_alojamiento').options.length = 0;
		document.getElementById('lista_alojamiento').options[document.getElementById('lista_alojamiento').options.length] = new Option('Selecciona localidad...','');
		document.getElementById('lista_huespedes').options.length = 0;
		document.getElementById('lista_huespedes').options[document.getElementById('lista_huespedes').options.length] = new Option('Selecciona alojamiento...','');		
	} else {
		document.getElementById('lista_alojamiento').options.length = 0;
		document.getElementById('lista_alojamiento').options[document.getElementById('lista_alojamiento').options.length] = new Option('Calculando...','');
		document.getElementById('lista_huespedes').options.length = 0;
		document.getElementById('lista_huespedes').options[document.getElementById('lista_huespedes').options.length] = new Option('Selecciona alojamiento...','');			
	}
	if(idLocalidad.length>0) {
		ajax.requestFile = 'includes/dame_alojamientos_filtro.php?idLocalidad='+idLocalidad;	
		ajax.onCompletion = creaAlojamientosFiltro;	
		ajax.runAJAX();	
	}	
}

function creaAlojamientosFiltro() {
	var obj = document.getElementById('lista_alojamiento');
	eval(ajax.response);	
}


function dameListaHuespedesFiltro(sel) {
	var idAlojamiento = sel.options[sel.selectedIndex].value;
	if (idAlojamiento == "") {
		document.getElementById('lista_huespedes').options.length = 0;
		document.getElementById('lista_huespedes').options[document.getElementById('lista_huespedes').options.length] = new Option('Selecciona alojamiento...','');		
	} else {
		document.getElementById('lista_huespedes').options.length = 0;
		document.getElementById('lista_huespedes').options[document.getElementById('lista_huespedes').options.length] = new Option('Calculando...','');
	}
	if(idAlojamiento.length>0) {
		ajax.requestFile = 'includes/dame_huespedes_filtro.php?idAlojamiento='+idAlojamiento;	
		ajax.onCompletion = creaHuespedesFiltro;	
		ajax.runAJAX();	
	}	
}

function creaHuespedesFiltro() {
	var obj = document.getElementById('lista_huespedes');
	eval(ajax.response);	
}

function checkEmail(str)
{
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(str)){
		return true;
	}
	return false;
}

  
function diasEntreFechas (desde, hasta) {   
  
   //Obtiene dia, mes y año   
   var fecha1 = new fecha( desde )      
   var fecha2 = new fecha( hasta )   
      
   //Obtiene objetos Date   
   var miFecha1 = new Date( fecha1.anio, fecha1.mes, fecha1.dia )   
   var miFecha2 = new Date( fecha2.anio, fecha2.mes, fecha2.dia )   
  
   //Resta fechas y redondea   
   var diferencia = miFecha2.getTime() - miFecha1.getTime()   
   var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24))   
      
   return dias;   
}   
  
function fecha( cadena ) {   
  
   //Separador para la introduccion de las fechas   
   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      
   }   
} 

function validaFrmDisponibilidad() {
	if (document.frmDisponibilidad.desde.value == "" || document.frmDisponibilidad.hasta.value == "" || document.frmDisponibilidad.lista_localidad.value == "" 
		|| document.frmDisponibilidad.lista_alojamiento.value == "" || document.frmDisponibilidad.lista_huespedes.value == "") {
		alert("Por favor, rellena correctamente todos los campos para comprobar la disponibilidad. Son necesarios.");
		return false;
	} else {
		var fec=new Date; 
		var dia=fec.getDate(); 
		if (dia<10) dia='0'+dia; 
		var mes=fec.getMonth()+1; 
		if (mes<10) mes='0'+mes; 
		var anio=fec.getFullYear(); 
		fechaHoy=dia+'/'+mes+'/'+anio;
		var diasAlojamiento = diasEntreFechas(document.frmDisponibilidad.desde.value, document.frmDisponibilidad.hasta.value);
		var diasHoy = diasEntreFechas(fechaHoy, document.frmDisponibilidad.desde.value);
		if (diasAlojamiento >= 1 && diasHoy >= 0) {
			enviaFormularioAjax("frmDisponibilidad", "capaDisponibilidad", "formulario.disponibilidad.php")	
		} else {
			alert("La fecha de entrada no puede ser anterior a hoy o posterior a la fecha de salida. Por favor, introduce las fechas de entrada y salida correctamente.");
			return false;
		}

	}

}
function validaFrmDisponibilidadAlojamiento() {
	if (document.frmDisponibilidad.desde.value == "" || document.frmDisponibilidad.hasta.value == "" || document.frmDisponibilidad.lista_localidad.value == "" 
		|| document.frmDisponibilidad.lista_alojamiento.value == "" || document.frmDisponibilidad.lista_huespedes.value == "") {
		alert("Por favor, rellena correctamente todos los campos para comprobar la disponibilidad. Son necesarios.");
		return false;
	} else {
		var fec=new Date; 
		var dia=fec.getDate(); 
		if (dia<10) dia='0'+dia; 
		var mes=fec.getMonth()+1; 
		if (mes<10) mes='0'+mes; 
		var anio=fec.getFullYear(); 
		fechaHoy=dia+'/'+mes+'/'+anio;
		var diasAlojamiento = diasEntreFechas(document.frmDisponibilidad.desde.value, document.frmDisponibilidad.hasta.value);
		var diasHoy = diasEntreFechas(fechaHoy, document.frmDisponibilidad.desde.value);
		if (diasAlojamiento >= 1 && diasHoy >= 0) {
			enviaFormularioAjax("frmDisponibilidad", "capaDisponibilidad", "formulario.disponibilidad-alojamiento.php")	
		} else {
			alert("La fecha de entrada no puede ser anterior a hoy o posterior a la fecha de salida. Por favor, introduce las fechas de entrada y salida correctamente.");
			return false;
		}

	}

}
function validaVal() {

	if (document.frmValidar.v_pass.value == "" || !checkEmail(document.frmValidar.v_mail.value)) {
		alert('Por favor, introduce un email y una contrase\u00f1a v\u00e1lidas para identificarte.');
		return false;
	} else { 
		return true;
	}
}

function validaReg() {
	if (document.frmRegistro.nombre.value == "" || document.frmRegistro.apellidos.value == "") {
		alert('Por favor, introduce tu nombre y apellidos.');
		return false;
	} else {
		if (document.frmRegistro.direccion.value == "" || document.frmRegistro.poblacion.value == "" || document.frmRegistro.cp.value == "" ||
			document.frmRegistro.provincia.value == "" || document.frmRegistro.id_pais.value == "" || 
			document.frmRegistro.movil.value == "") {
			alert('Por favor, introduce todos tus datos de contacto (direcci\u00f3n, poblaci\u00f3n, cp, pa\u00eds, tel\u00e9fono, m\u00f3vil)');
			return false;
		} else { 
			if (document.frmRegistro.email.value != document.frmRegistro.email2.value) {
				alert('Las direcci\u00f3n de correo electr\u00f3nico que has introducido no coincide con su confirmaci\u00f3n.');
				return false;
			} else {
				if (!checkEmail(document.frmRegistro.email.value)) {
					alert('Por favor, introduce una direcci\u00f3n de correo electr\u00f3nico v\u00e1lida.');
					return false;
				} else {
					if (document.frmRegistro.password.value != document.frmRegistro.password2.value) { 
						alert('La contrase\u00f1a que has introducido no coincide con su confirmaci\u00f3n');
						return false;
					} else {
						if (document.frmRegistro.password.value.length < 6 || document.frmRegistro.password.value.length > 10) {
							alert('La contrase\u00f1a debe tener un m\u00ednimo de 6 caracteres y un m\u00e1ximo de 10.');	
							return false;
						} else {
							if (document.frmRegistro.txtimagen.value == "") {
								alert('Por favor, introduce en texto de la imagen.');
								return false;
							} else {
								return true;	
							}
						}
					}
				}
			}
		}
	}
}

function confirmarDatos(accion) {
	if (document.frmDatos.nombre.value == "" || document.frmDatos.apellidos.value == "") {
		alert('Por favor, introduce tu nombre y apellidos.');
	} else {
		if (document.frmDatos.direccion.value == "" || document.frmDatos.poblacion.value == "" || document.frmDatos.cp.value == "" ||
			document.frmDatos.provincia.value == "" || document.frmDatos.id_pais.value == "" || 
			document.frmDatos.movil.value == "") {
			alert('Por favor, introduce todos tus datos de contacto (direcci\u00f3n, poblaci\u00f3n, cp, pa\u00eds, tel\u00e9fono, m\u00f3vil)');
		} else { 
			if (document.frmDatos.email.value != document.frmDatos.email2.value) {
				alert('Las direcci\u00f3n de correo electr\u00f3nico que has introducido no coincide con su confirmaci\u00f3n.');
			} else {
				if (!checkEmail(document.frmDatos.email.value)) {
					alert('Por favor, introduce una direcci\u00f3n de correo electr\u00f3nico v\u00e1lida.');
				} else {
					//if (document.frmDatos.txtimagen.value == "") {
						//alert('Por favor, introduce en texto de la imagen.');
					//} else {
						if (document.frmDatos.factu.checked == true) {
							if (document.frmDatos.direccion_fac.value == "" || document.frmDatos.poblacion_fac.value == "" || document.frmDatos.cp_fac.value == "" || 
								document.frmDatos.provincia_fac.value == "" || document.frmDatos.id_pais_fac.value == "") {
									alert("Debes completar los datos de la facturaci\u00f3n.");
							} else {
								
								if (accion == 2) {
																		
										if (document.frmDatos.condiciones.checked == false) {
											alert("Debes aceptar las condiciones para confirmar tu reserva.");
										} else {
											document.frmDatos.accion.value = accion;
											document.frmDatos.submit();										
										}
								} else {
									document.frmDatos.accion.value = accion;
									document.frmDatos.submit();
								}										
							}
						} else {
							if (accion == 2) {									
								
									if (document.frmDatos.condiciones.checked == false) {
										alert("Debes aceptar las condiciones para confirmar tu reserva.");
									} else {
										document.frmDatos.accion.value = accion;
										document.frmDatos.submit();										
									}
							} else {
								document.frmDatos.accion.value = accion;
								document.frmDatos.submit();
							}
						}							
					//}
				}
			}
		}
	}	
}

function validaPass() {
	if (!checkEmail(document.frmNuevaPass.email.value)) {
		alert('Debes introducir una direcci\u00f3n de correo electr\u00f3nico v\u00e1lida.');
		return false;
	} else { 
		if (document.frmNuevaPass.passwd.value != document.frmNuevaPass.passwd2.value) { 
			alert('La contrase\u00f1a que has introducido no coincide con su confirmaci\u00f3n');
			return false;
		} else {
			if (document.frmNuevaPass.passwd.value.length < 6 || document.frmNuevaPass.passwd.value.length > 10) {
				alert('La contrase\u00f1a debe tener un m\u00ednimo de 6 caracteres y un m\u00e1ximo de 10.');	
				return false;
			} else {
				return true;	
			}
		}
	}
}

function activacionFactu() {
	if (document.getElementById("factu").checked == true) {
		document.getElementById("rsocial_fac").disabled = false;
		document.getElementById("nifcif_fac").disabled = false;
		document.getElementById("direccion_fac").disabled = false;
		document.getElementById("poblacion_fac").disabled = false;
		document.getElementById("cp_fac").disabled = false;
		document.getElementById("provincia_fac").disabled = false;
		document.getElementById("id_pais_fac").disabled = false;
		
	} else {
		document.getElementById("rsocial_fac").disabled = true;
		document.getElementById("nifcif_fac").disabled = true;
		document.getElementById("direccion_fac").disabled = true;
		document.getElementById("poblacion_fac").disabled = true;
		document.getElementById("cp_fac").disabled = true;
		document.getElementById("provincia_fac").disabled = true;
		document.getElementById("id_pais_fac").disabled = true;		
	}
}

function lanzaReservas(url, lista_localidad, lista_alojamiento, lista_huespedes, desde, hasta, tipo_reserva){
	document.getElementById("lista_localidad").value = lista_localidad;
	document.getElementById("lista_alojamiento").value = lista_alojamiento;
	document.getElementById("lista_huespedes").value = lista_huespedes;
	document.getElementById("desde").value = desde;
	document.getElementById("hasta").value = hasta;
	document.getElementById("tipo_reserva").value = tipo_reserva;
	document.getElementById("compruebaDisponibilidad").value = "1";
	document.getElementById("frmDisponibilidad").action = url;
	document.getElementById("frmDisponibilidad").target = "_blank";
	document.getElementById("frmDisponibilidad").submit();
}
function info(cuales){
	if (cuales == "leame") {
		window.open('importante_leame.php','importante_leame','toolbar=no,location=no,status=yes,menubar=no, scrollbars=yes,resizable=yes,width=600,height=600,top=50,left=50');	
	}
	if (cuales == "condiciones") {
		window.open('condiciones.html','condiciones','toolbar=no,location=no,status=yes,menubar=no, scrollbars=yes,resizable=yes,width=900,height=600,top=50,left=50');	
	}
	if (cuales == "legal") {
		window.open('legal.html','legal','toolbar=no,location=no,status=yes,menubar=no, scrollbars=yes,resizable=yes,width=900,height=600,top=50,left=50');	
	}		
}
function compartirSocialMedia(url,titulo,red,a){
	var http="";
	var principal="http://desarrollo.valdelarco.com";
	titulo=titulo.replace("<b>","");
	titulo=titulo.replace("</b>","");
	switch(red){
		case"facebook":
			http="http://www.facebook.com/share.php?src=bm&u="+encodeURIComponent(principal+url)+"&t="+encodeURIComponent(titulo)+"&v=3";
			break;
		case"myspace":
			http="http://www.myspace.com/Modules/PostTo/Pages/?u="+encodeURIComponent(principal+url)+"&t="+encodeURIComponent(titulo)+'&l=3&c=%20via+<a+href%3D"http://desarrollo.valdelarco.com/">Casas+rurales+en+Aracena+y+en+el+bajo+Guadiana+Apartamentos+y+Aticos+en+Sevilla</a>';
			break;
		case"twitter":
			http="http://twitter.com/home?status="+encodeURIComponent(principal+url)+encodeURIComponent(titulo+" ");
			break
	}
	//if(typeof(a)=="undefined"){
		//a="/buscar/anyadido_a"
	//}
	//track(a+"_"+red);
	window.open(http,"","")
}
function borrarEncendidas(tipo) {
	for (i=1;i<=10;i++) {
		document.getElementById(tipo+'_'+i).src='images/stella.jpg';
	}
}

function asignaValor(tipo,valor) {
	borrarEncendidas(tipo);
	for (i=1;i<=valor;i++) {
		document.getElementById(tipo+'_'+i).src='images/stella2.jpg';
	}
	document.getElementById(tipo).value=valor;
//	alert(tipo+': '+document.getElementById(tipo).value);
}

function validarOpiniones() {
	campos=document.getElementsByTagName('input');
	for (i=0;i<campos.length;i++) {
		if ((campos[i].type=='hidden' || campos[i].type=='text') && campos[i].value=='') {
//	alert(campos[i].name+'('+campos[i].type+'): '+campos[i].value);
			alert('Necesitamos que cumplimentes todos los campos. Gracias.');
			campos[i].focus();
			return false;
		}
	}
	campos=document.getElementsByTagName('textarea');
	for (i=0;i<campos.length;i++) {
		if (campos[i].value=='') {
//	alert(campos[i].name+': '+campos[i].value);
			alert('Necesitamos que cumplimentes todos los campos. Gracias.');
			campos[i].focus();
			return false;
		}
		if (campos[i].value.length<30) {
//	alert(campos[i].name+': '+campos[i].value);
			alert('Por favor, necesitamos que tu opinión sea más completa. Gracias.');
			campos[i].focus();
			return false;
		}
	}
	return true;
}
function cambiaOpiniones() {
	opiniones = document.getElementById('sel_alojamiento').value;
	if (opiniones != "") {
		window.location.href=opiniones;	
	}
}
