$(document).ready(function() {
	// Set the transparent pixel
/*
	jQuery.ifixpng('pics/blank.gif');
	jQuery('#cabecera, #ubic').ifixpng();
	$('#cabecera, #ubic').css("z-index","1");
	$('#cabecera a, #ubic *').css("z-index","100");
*/

	$.ajaxSetup({
		url: "ajax.php",
		type: "POST",
		dataType: "json"
	});
	
	
	var lang = $("#language").val();
	var hoy = new Date();
	hoy = new Date(hoy.getFullYear(),hoy.getMonth(),hoy.getDate());
	var manana = new Date();
	manana.setDate(hoy.getDate()+1);
	
	var ocupados;
	$.ajax({
		data: "module=reserva&action=getOcupados",
		success: function(data){
			if (data.ocupados){ //Si todo va bien, mostramos el mensaje y formulario recibidos
				ocupados = data.ocupados;
			}else{
				ocupados = null;
			}
		}
	});

	var temporadas;
	$.ajax({
		data: "module=reserva&action=getTemporadas",
		success: function(data){
			if (data.temporadas){ //Si todo va bien, mostramos el mensaje y formulario recibidos
				temporadas = data.temporadas;
			}else{
				temporadas = null;
			}
		}
	});
	

	$.datepicker.setDefaults({
		showOn: 'both',
		buttonImageOnly: true, 
		buttonImage: 'pics/calendario.png', 
		dateFormat: 'dd/mm/yy',
		showAnim: 'slideDown',
		regional: 'es',
		showStatus: true,
		minDate: hoy,
		maxDate: new Date(hoy.getFullYear()+1,hoy.getMonth(),hoy.getDate()),
		beforeShow: function(input){
						readLinked(input);
					}, 
		beforeShowDay: comprobarFecha,
		statusForDate: statusFecha,     
   		onSelect: function(date){
   						updateLinked(date,this);
   						updateRanges(date,this);
   					} 
	});
	
	function comprobarFecha(date){
		var ret = [true,""];

		$(ocupados).each(function(){
			//Si la fecha est� entre una llegada y una salida, entonces est� ocupado y no se puede seleccionar
			var f_llegada = new Date();
			f_llegada.setTime(this.f_llegada*1000);
			var f_salida = new Date();
			f_salida.setTime(this.f_salida*1000);
			
			if ((date >= f_llegada) && (date <= f_salida) && (date >= hoy)){
				ret = [false, "datepicker_ocupado"];
			}
		});
		return ret;
	}

	function statusFecha(date,inst){
		var ret = $.datepicker.dateStatus(date, inst) + " - libre";

		$(ocupados).each(function(){
			//Si la fecha est� entre una llegada y una salida, entonces est� ocupado y no se puede seleccionar
			var f_llegada = new Date();
			f_llegada.setTime(this.f_llegada*1000);
			var f_salida = new Date();
			f_salida.setTime(this.f_salida*1000);
			
			if ((date >= f_llegada) && (date <= f_salida) && (date >= hoy)){
				ret = $.datepicker.dateStatus(date, inst) + " - ocupado";
			}
		});
		return ret;
	}

	if ($("#f_llegada").is("input")){
		$("#f_llegada").datepicker($.datepicker.regional[lang]);
		$("#f_llegada").datepicker("change", {dateFormat: 'dd/mm/yy'});
	}
	
	if ($("#f_salida").is("input")){
		$("#f_salida").datepicker($.datepicker.regional[lang]);
		$("#f_salida").datepicker("change", {dateFormat: 'dd/mm/yy'});
	}
	
	//Al realizar un cambio en el mes o el a�o, se comprueba que las fechas disponibles sean correctas
	$('#f_salida_mes, #f_salida_ano, #f_llegada_mes, #f_llegada_ano').bind("change",function(){checkLinkedDays(this)}); 

	//Forzamos un change en las selects para que se actualicen y muestren solo las fechas v�lidas
	$('#f_llegada_mes').trigger("change");
	$('#f_salida_mes').trigger("change");
	
	function submitReserva(){
		var hoy = new Date();
		hoy = new Date(hoy.getFullYear(),hoy.getMonth(),hoy.getDate());

		var d_llegada = new Date($("#f_llegada_ano").val(),($("#f_llegada_mes").val()-1),$("#f_llegada_dia").val());
		var f_llegada = ""+$("#f_llegada_dia").val()+"/"+$("#f_llegada_mes").val()+"/"+$("#f_llegada_ano").val();
		var d_salida = new Date($("#f_salida_ano").val(),($("#f_salida_mes").val()-1),$("#f_salida_dia").val());
		var f_salida = ""+$("#f_salida_dia").val()+"/"+$("#f_salida_mes").val()+"/"+$("#f_salida_ano").val();


		//Si la fecha de llegada es anterior a la fecha de salida, realizamos la petici�n Ajax. 
		if ((hoy > d_llegada) || (d_llegada >= d_salida)){
			$("<div class='error' title='ERROR'>La fecha de llegada debe ser posterior a la fecha actual y la fecha de salida superior a la fecha de llegada</div>").dialog();
		}else{
			$.ajax({
				data: "module=reserva&action=checkDate&f_llegada="+f_llegada+"&f_salida="+f_salida,
				success: function(data){
					if (!data.error){ //Si todo va bien, mostramos el mensaje y formulario recibidos
						var formulario_reserva = $("<div class='formulario' title='FORMULARIO DE RESERVA'>"+data.mensaje+data.formulario_reserva+"</div>")
						.dialog({
							resizable: false,
							width: "550px",
							height: "650px"
						});
						$(".ui-resizable-handle").css("display","none");
						formulario_reserva.find("input[@name='reserva_nombre']").focus(); //Nos saltamos los inputs de las fechas
						formulario_reserva.find("input").each(function(i,n){
								$(n).attr("tabindex",(i+1));								
						});
					}else{
						$("<div class='error' title='ERROR'>"+data.error+"</div>").dialog();
					}
				}
			});
		}
		return false;
	}
	
	// Actualiza el valor del datepicker con los valores de las selects
	function readLinked(input) {
		var id = $(input).attr("id"); 
	    $(input).val( 
	        $('#'+id+'_dia').val() + '/' + 
	        $('#'+id+'_mes').val() + '/' +  
	        $('#'+id+'_ano').val() 
	    ); 
	    return {}; 
	} 
	 
	// Actualiza las selects con los valores introducidos en el datepicker
	function updateLinked(date,input) { 
		var id = $(input).attr("id"); 
	    $('#'+id+'_dia').val(date.substring(0, 2)); 
	    $('#'+id+'_mes').val(date.substring(3, 5)); 
	    $('#'+id+'_ano').val(date.substring(6, 10));
	    $('#'+id+'_mes').trigger("change");
	} 
	 
	//Actualiza los rangos de los datepickers, para evitar incongruencias en las fechas...
	function updateRanges(date,input){
		var id = $(input).attr("id");
		switch(id){
			case "f_salida":
				var max_date = $('#f_salida').datepicker('getDate');
				$("#f_llegada").datepicker("change",{maxDate:  max_date});
				break;
			case "f_llegada":
				var min_date = $('#f_llegada').datepicker('getDate');
				$("#f_salida").datepicker("change", {minDate: min_date});
				break;
		}
	}
	
	// Evita la selecci�n de fechas erroneas en las selects
	function checkLinkedDays(input) {
		var campo = $(input).attr("id").match("^(f_.+_).+$")[1];

		//Calculamos el �ltimo d�a del mes
	    var daysInMonth = 32 - new Date($('#'+campo+'ano').val(), 
	        $('#'+campo+'mes').val() - 1, 32).getDate();
	        
	    //Habilitar todos los d�as
	    $('#'+campo+'dia option').attr('disabled', '');
	    
	    //Deshabilitar todos los d�as que no pertenezcan al mes actual 
	    $('#'+campo+'dia option:gt(' + (daysInMonth - 1) +')').attr('disabled', 'disabled');
	    
	    //Si el d�a ya seleccionado es mayor que el �ltimo d�a del mes actual, se cambia por este 
	    if ($('#'+campo+'dia').val() > daysInMonth) { 
	        $('#'+campo+'dia').val(daysInMonth); 
	    }
	} 
				
		 

});

