$(document).ready(function() {	

	$("#datepicker").hide();
	$("#text").hide();
	data = null;
	lista_eventos = null;
	
	
	
	function createCalendar(year, month){
		if(year && month) data = new Date(year, month - 1, 1);
		else data = new Date();
			
		str_month = data.getMonth() + 1;
		if(str_month >= 1 && str_month<10){
			str_month = "0" + str_month;
		}
		str_year = data.getFullYear();
			
		lista_eventos;
		$.getJSON("/agenda/json", function(json){ 
			setTimeout(function(){
				lista_eventos = json;
			
				$("#calendario #datepicker").datepicker("destroy");
				$("#calendario #datepicker").datepicker({
					defaultDate: data,
					onChangeMonthYear: initToolTip,
					beforeShowDay: setEventos,
					onSelect: function(dateText){
							dt1 = dateText;
							dt2 = dt1.replace("/", "-");
							dt3 = dt2.replace("/", "-");
							window.location = "/agenda/index/data/" + dt3;
					}
				});
				
				initToolTip();
				
			}, 0);
			
			$("#carrenga").hide();
			$("#datepicker").show();
			$("#calendario #rodape").show();
			
		});
	}
	
	function initToolTip(){
		// com o timeout, esta função consegue enchergar o novo html que foi recém-atualizado na página.
		setTimeout(function(){
			$("#calendario #text").hide();
			$("#calendario #datepicker td.tool-tip").hover(function(){
				var pos = $(this).position();
				var dia = $(this).text();
				
				var desc = "<ul>" + $(this).attr("title") + "</ul>";
				$("#calendario #text").html(desc).show().css("top", pos.top + 30);
				
			}, function(){
				$("#calendario #text").hide();
			});
		}, 1);
	}
	
	function setEventos(date){
		eventos = lista_eventos;
		isAgendado = false;
		
		if(eventos){
			$.each(eventos, function(index, linha){
				if(linha[0] == $.datepicker.formatDate("yy-mm-dd", date)){
					isAgendado = true;
					title = linha[1];
				}
			});
		}
		
		if(isAgendado){
			return [true, "tool-tip", title];
		}
		else{
			return [false];
		}
	}
	
	createCalendar();

	
});
