	
	var http_request = false;
	var preuTotal = 0; //el que es mostrara a lusuari
	var preuDeTot = 0; //string amb tots els preus, separats amb un guio(-)
	var minDateAnt = "";//minima fecha de salida
	
/*----------------------------CALENDARIO JQUERY---------------------------------------*/	
	
	//parametros por defecto para las fechas, numero de meses a mostrar y ocultar el boton de prev			
	$.datepicker.setDefaults($.extend({numberOfMonths: 2, hideIfNoPrevNext: true, showOn: 'both', buttonImage: 'jquery/development-bundle/images/bot_calendario_off.gif', buttonImageOnly: true}, $.datepicker.regional['']));
				
	$(function(){
		//fecha de entrada, idioma del calendario				
		$("#fechaEntrada").datepicker($.extend({minDate: 0}, $.datepicker.regional['<?=$idiomaCalendari ?>']));
		
		$('#fechaEntrada').datepicker({ dateFormat: 'yy-mm-dd' });
								
		//fecha de salida
		$("#fechaSalida").datepicker('disable');
		//invisibilidad de los radions buttons y campo de fecha salida
		$('input[name=disHab]:radio').attr("disabled", true);
		$('input[id=otros]:radio').attr("disabled", false);
		
		$("#fechaSalida").attr("disabled", true);

		//limpiar formulario
		document.getElementById("envio_pag").reset();
				
		//cuando ja se ha escogido la fecha de entrada
		$("#fechaEntrada").change(function() {		
			$('input[name=disHab]:radio').attr("checked", false);
						
			$("#fechaSalida").datepicker($.extend({minDate: 0}, $.datepicker.regional['<?=$idiomaCalendari ?>']));
			
			any = Number($.datepicker.formatDate('yy', new Date($('#fechaEntrada').datepicker('getDate'))));
			mes = Number($.datepicker.formatDate('mm', new Date($('#fechaEntrada').datepicker('getDate'))));
			dia = Number($.datepicker.formatDate('dd', new Date($('#fechaEntrada').datepicker('getDate'))));
			
			$("#fechaSalida").datepicker('enable');

			//borramos datos y desabilitamos input radio 
			document.getElementById("fechaSalida").value = "";
			borrar_precio();
			mens_no_dispo_off();
			$('input[name=disHab]:radio').attr("disabled", true);
			$('input[id=otros]:radio').attr("disabled", false);
			
			$("#fechaSalida").datepicker('option', 'minDate', new Date(any, mes - 1, dia + 1));					
		});

		//al cambiar fecha de salida, hara las peticiones al servidor
		$("#fechaSalida").change(function() {
			var numhabit = $('select[name=numHab]').attr('value');
			makeRequest("calcula_ofert.php", $('#fechaEntrada').attr('value'), $('#fechaSalida').attr('value'), numhabit);	
			$('input[name=disHab]:radio').attr("disabled", false);
			$('input[name=disHab]:radio').attr("checked", false);
			borrar_precio();
			mens_no_dispo_off();
			bot_envia_off();
		});
		$('select[name=numHab]').change(function() {
			var numhabit = $('select[name=numHab]').attr('value');
			//alert("entra");
			if($('#fechaEntrada').attr('value') != "" && $('#fechaSalida').attr('value') != ""){
				//alert("ok!");
				makeRequest("calcula_ofert.php", $('#fechaEntrada').attr('value'), $('#fechaSalida').attr('value'), numhabit);	
				$('input[name=disHab]:radio').attr("checked", false);
				borrar_precio();
				mens_no_dispo_off();
			}
		});
		
	});
	
/*----------------------------FIN CALENDARIO JQUERY---------------------------------------*/
	
	//funciones ajax para hacer una peticion al servidor asincrona
	function makeRequest(url, dataEnt, dataSal, numhabi) {
		
	    http_request = false;
	
	    if (window.XMLHttpRequest) { // Mozilla, Safari,...
	        http_request = new XMLHttpRequest();
	        if (http_request.overrideMimeType) {
	            http_request.overrideMimeType('text/xml');
	        }
	    } else if (window.ActiveXObject) { // IE
	        try {
	            http_request = new ActiveXObject("Msxml2.XMLHTTP");
	        } catch (e) {
	            try {
	                http_request = new ActiveXObject("Microsoft.XMLHTTP");
	            } catch (e) {}
	        }
	    }
	
	    if (!http_request) {
	        alert('Lo sentimos: Hubo problemas con el servidor.');
	        return false;
	    }
	   
	    url = url+"?dataEnt="+dataEnt+"&dataSal="+dataSal+"&idioma=<?=$idioma?>&numHab="+numhabi;
	    
	    http_request.onreadystatechange = alertContents;
	    http_request.open('GET', url, true);
	    http_request.send(null);
	
	}
	
	function alertContents() {	
	    if (http_request.readyState == 4) {
	        if (http_request.status == 200) {
	        	preuDeTot = http_request.responseText;//peticio del preu
	        } else {
	            alert('Lo sentimos: Hubo problemas con la petición.');
	            //desabilitamos input radio 
	            $('input[name=disHab]:radio').attr("disabled", true);
				$('input[id=otros]:radio').attr("disabled", false);
	        }
	    }
	
	}

	//da el precio segun regimen/habitacion, devuelve false si no hay disponibilidad
	function donaPreu(num_id){
		var arrPreu = new Array();
		if(preuDeTot == ""){//no hi ha disponibilitat
			mens_no_dispo_on();
			bot_envia_on();
			return false;
		}else{
			//alert(preuDeTot);
			arrPreu = preuDeTot.split("-");
			preuTotal = arrPreu[num_id-1];
			return true;
		}
		
	}

	//si hay disponibilidad muestra el precio del regimes/habitacion escogido
	function posaPreu(num_id, idCampPreu,idinput){
		var nomId = "ocult_"+num_id;
		var b = donaPreu(num_id);
		if(b){
			if(document.getElementById('vist') != null){ //si hay algun precio visible
				document.getElementById('vist').style.visibility='hidden';
				document.getElementById('vist').style.display='none';
				var v = document.getElementById('vist').className;
				document.getElementById(v).innerHTML = "";
				document.getElementById('vist').id='ocult_'+document.getElementById('vist').className;
			}
	
			document.getElementById(nomId).style.visibility='visible';
			document.getElementById(nomId).style.display='inline';
			var c = document.getElementById(nomId).className;							
			document.getElementById(c).innerHTML = ": ";
			document.getElementById(idCampPreu).innerHTML = preuTotal+" €";
			document.getElementById(nomId).id='vist';
			if (preuTotal== "No disponible") {
				document.getElementById(idinput).disabled=true;
			}
			//precio a enviar	
			document.getElementById('imp').value = preuTotal;
			
			//visibilidad de los botones de enviar
			bot_envia_off();
		}
	}
	
	//visibilidad de los botones de enviar, visible: Enviar solicitud
	function bot_envia_on(){		
		document.getElementById('envia_paga').style.display='none';
		document.getElementById('envia_paga').style.visibility='hidden';
		document.getElementById('envia').style.visibility='visible';
		document.getElementById('envia').style.display='block';
	}

	//visibilidad de los botones de enviar, visible: Ir a pagar
	function bot_envia_off(){
		document.getElementById('envia').style.display='none';
		document.getElementById('envia').style.visibility='hidden';
		document.getElementById('envia_paga').style.visibility='visible';
		document.getElementById('envia_paga').style.display='block';
	}

	//mens no hay disponibilidad
	function mens_no_dispo_on(){
		document.getElementById('mens_no_dispo').style.display = 'inline';
		document.getElementById('mens').style.display = 'none';
	}

	//mens hay disponibilidad
	function mens_no_dispo_off(){
		document.getElementById('mens_no_dispo').style.display = 'none';
		document.getElementById('mens').style.display = 'inline';
	}

	//borra el precio si hay alguno visible
	function res(){
		borrar_precio();
		//visibilidad de los botones de enviar
		bot_envia_on();
		mens_no_dispo_off();
	}

	//envia para pagar al tpv
	function enviar_pagar(tipus){//enviar al tpv
		if(tipus == 1){//viene de reserva_ofertas.php
			if(comprovar_errores(1)){
				document.getElementById('envio_pag').action= "tpv/pago_send_ofertas.php";
				document.getElementById('envio_pag').submit();
			}
		}else{	//viene de reserva_dias_sueltos.php
			if(comprovar_errores(2)){
				document.getElementById('envio_pag').action= "tpv/pago_send_dias_sueltos.php";
				document.getElementById('envio_pag').submit();
			}
		}		
	}

	//envia solicitud como mail
	function enviar_mail(){//enviar un mail
		if(comprovar_errores()){
			if('<?=$idioma ?>' == '_en'){ //cambiamos el formato de la fecha, ya que estara en formato ingles
				dataEntradaCaste = formatoCaste(document.getElementById('fechaEntrada').value);
				dataSalidaCaste = formatoCaste(document.getElementById('fechaSalida').value);
				document.getElementById('fechaEntrada').value = dataEntradaCaste;
				document.getElementById('fechaSalida').value = dataSalidaCaste;
			}
			document.getElementById('envio_pag').action= "reserva_send_dias_sueltos.php";
			document.getElementById('envio_pag').submit();
		}		
	}

	//dar formato a castellano a una fecha
	function formatoCaste(fecha){
		var arrFecha = fecha.split("/");
		var dia = arrFecha[1];
		var mes = arrFecha[0];
		var any = arrFecha[2];
		var fechaFormat = dia+"/"+mes+"/"+any;
		return fechaFormat;
	}

	//borra el precio
	function borrar_precio(){
		if(document.getElementById('vist') != null){ //si hay algun precio visible
			document.getElementById('vist').style.visibility='hidden';
			document.getElementById('vist').style.display='none';
			var v = document.getElementById('vist').className
			document.getElementById(v).innerHTML = "";
			document.getElementById('vist').id='ocult_'+document.getElementById('vist').className;
		}
	}
	
	// Funcion para verificar los datos antes de enviar
	function comprovar_errores(num){
		var email = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*$/);
		var movil_fijo = new RegExp(/^[6,9]{1}-? ?[0-9]{8}$/);
		//|| !document.envio.telefono.value.match(movil_fijo)
		var bol = true;
		//comprueba nombre y apallidos
		if(document.envio.nombre_apellidos.value == ""){
			 document.getElementById('nC').className = "color_chillon";
			 bol = false;
		}else	document.getElementById('nC').className = "blanco";

		//comprueba email
		if(document.envio.email.value=="" || !document.envio.email.value.match(email)){
			document.getElementById('em').className = "color_chillon";
			bol = false;
		}else	document.getElementById('em').className = "blanco";
		
		
		//comprueba telefono
		if(document.envio.telefono.value==""){
			document.getElementById('tel').className = "color_chillon";
			bol = false;
		}else	document.getElementById('tel').className = "blanco";
		
		//comprueba errores segun el formulario
		if(num == 1){
			if(!erroresOfertas()) bol = false;
		}else{
			if(!erroresDiasSueltos()) bol = false;
		}
		
		//escribe mensaje de error en el caso de haber
		if(bol) mens_error_off();
		else mens_error_on();
		
		return bol;			
	}
	
	function erroresOfertas(){
		var bol = true;
		//comprueba que se haya escogido un dia para la reserva
		if($("select[name=id_dispo] option:selected").val() == "no"){
			document.getElementById('fec').className = "color_chillon";
			bol = false;
		}else document.getElementById('fec').className = "blanco";
		return bol;
	}
	
	function erroresDiasSueltos(){
		var bol = true;
		//comprueba dia de entrada menos cuando esta otras peticiones activado
		if(document.envio.fechaEntrada.value == "" && $('input[name=disHabOtros]:radio').attr("checked") == false){
			document.getElementById('dE').className = "color_chillon";
			bol = false;
		}else document.getElementById('dE').className = "blanco";

		//comprueba dia de salida
		if(document.envio.fechaSalida.value == "" && $('input[name=disHabOtros]:radio').attr("checked") == false){
			document.getElementById('dS').className = "color_chillon";
			bol = false;
		}else document.getElementById('dS').className = "blanco";

		//comprueba regimen y habitacion
		if($("input:checked").length == 0){//si no ha escogido otros y tampoco radio
			document.getElementById('rH').className = "color_chillon";
			bol = false;
			
		}else document.getElementById('rH').className = "blanco";
		return bol;
	}

	//mens para el error -> hay algun campo sin rellenar
	function mens_error_on(){
		if(document.getElementById('mens_error_env') != null)	document.getElementById('mens_error_env').style.display = 'none';
		document.getElementById('mens_error').style.display = 'block';
	}

	//quitar el mens de error
	function mens_error_off(){
		document.getElementById('mens_error').style.display = 'none';
	}

