var alt;
jQuery(document).ready(function($){
	// HTTP cache
	// var remoteCache = new Array();
	
	// Troca os meses
	function atualizaMes(t){
		var d = $(t).attr('rel').split('-');
		var mes = d[0];
		var ano = d[1];
		
		var pai = $(t).parent();
		var calendar = pai.next();
		var box = calendar.parent();
		var id = calendar.attr('id');
	
		// animação
		var anim = {"opacity":"hide"};
		$('.mes,.calendar',box).animate(anim,500,function(){
			box.addClass('loading');
		});	
		
		box.delay(1000).animate(anim,500,function(){
			/* Para cachear o resultado
			if( remoteCache[mes+ano] != undefined ) {
				box
				.html(remoteCache[mes+ano])
				.animate({"opacity":"show"});
				
			} else {
				*/$.post(
					rootUrl + '/calendario.php',
					{"ajax":true,"id":id,"mes":mes,"ano":ano,"p":p},
					function(data){
						box.removeClass('loading');
						$('.pai,.calendar',box).remove();
						box
						.html(data)
						.animate({"opacity":"show"});
						
						//remoteCache[mes+ano] = box.html();
				});/*
			}*/			
		});
	}
	
	$('.btNextMes').live('click',function(){
		atualizaMes(this);
	});
	
	$('.btPrevMes').live('click',function(){
		atualizaMes(this);		
	});	
	
	
	$('table.calendar a').live('click',function(){
		// Id do Calendário
		var calendar = $("#calendar_" + $(this).attr('class'));
		
		//Id da div que guarda o calendario
		var pai = calendar.parent();
		
		// eventos
		var calendarEvents = $('#' + $(this).attr('class'));
		
		//Unique ID for the link
		var timestamp = $(this).attr('rel');		
		
		
		if( alt ) alert(timestamp);		
				
		calendarEvents.animate({height:"hide",opacity:"hide"},function(){
			$.post(
				rootUrl + '/include/calendar_backend.php',
				{"ajax":true,"timestamp":timestamp,"p":p},
				function(data){
					calendarEvents
					.html(data)
					.animate({height:"show",opacity:"show"});
			});			
		});
	});
});
