function dateChanged(calendar) {
	// OK, a date was clicked, redirect to /yyyy/mm/dd/index.php
	var y = calendar.date.getFullYear();
	var m = calendar.date.getMonth();     // integer, 0..11
	var d = calendar.date.getDate();      // integer, 1..31
	// redirect...
	$('calDate').value =  y + "-" + m + "-" + d;
	
	updateHovers();
}

function nf(n) {
	if(n < 10)
		return '0'+n;
	return n;
}

function listaDeEventos(dia) {
			
	fecha = $('calDate').value.split('-');
	fecha[1]++;
			
	fecha = nf(fecha[0])+nf(fecha[1])+nf(dia);

	var evts = new Array();

	j = 0;
	for(k = 1; k < eventos.length; k++) {
		if(eventos[k][0] == fecha) {
			evts[j] = k;
			j++;
		}
	}
	
	return evts;

}

Calendar.setup(
	{
		flat: "calendar-container", // ID of the parent element
		firstDay: 0,
		weekNumbers: false,
		flatCallback: dateChanged,
		firstDay: 1
	}
);

updateHovers();

function updateHovers() {

	cells = $('calendar-container').select('.daysrow .day');
	for(i=0; i < cells.length; i++) {
		
		evs = listaDeEventos(cells[i].firstChild.nodeValue);
		
		if(evs.length > 0) {
			
			cells[i].className += ' highlightedDate';
		
			cells[i].onmouseover = function() {
			
				evs = listaDeEventos(this.firstChild.nodeValue);
						
				this.style.cursor = 'pointer';
				
				div = document.createElement('div');
				div.className = 'calHint';
				
				ul = document.createElement('ul');
				
				id = false;
				n = 0;
				
				for(k = 0; k < evs.length; k++) {
									
					li = document.createElement('li');
					text = document.createTextNode(eventos[evs[k]][2]);
					
					li.appendChild(text);
					ul.appendChild(li);				
					
					id = eventos[evs[k]][1];
					n++;
				}
				
				div.appendChild(ul);
				this.appendChild(div);
				
				this.onmouseout = function() {
					if(this.lastChild.tagName == 'DIV')
						this.removeChild(this.lastChild);
				}
				
				this.onclick = function() {
					
					if(this.lastChild.tagName == 'DIV')
						this.removeChild(this.lastChild);
		
					if(n > 1)
						location.href = '/noticias/lista/'+fecha
					else if(n == 1)
						location.href = '/noticias/view/'+id
					
				}			
				
			}
	
		}
		
	}
}
