$(document).ready(function(){
		$('#curdate').width($('#curdate').parent().width()-35);
		populateeventCalendar(cureventdate);
	}
);

function daysInMonth(iMonth, iYear)
{
	return 32 - new Date(iYear, iMonth, 32).getDate();
	/*
	var date1=new Date(iYear, iMonth, 1);
	var date2=new Date(iYear, iMonth+1, 1);
	return Math.floor((date2.getTime()-date1.getTime())/(1000*24*3600));
	*/
}

function nextMonthEvents(){
	cureventdate.setMonth(cureventdate.getMonth()+1);
	populateeventCalendar(cureventdate);
}

function previousMonthEvents(){
	cureventdate.setMonth(cureventdate.getMonth()-1);
	populateeventCalendar(cureventdate);
}

var posts;

function populateeventCalendar(dateval){
	$('#eventloading').show();
	$('#eventloading').height($('#eventloading').parent().height());
	$.getJSON(baseDir+'events.php?ajax=true&month='+(dateval.getMonth()+1)+'&year='+dateval.getFullYear(), 
		function(data){
			var streventcalendar, i, j, k;
			var firstday=dateval;
			$('#eventcontents').html('');
			posts = new Object();
			firstday.setDate(1);
			streventcalendar='<table cellspacing="0" width="100%"><tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>';
			if(firstday.getDay()>0){
				streventcalendar=streventcalendar+'</tr><tr>';
			}
			for(i=0; i<firstday.getDay(); i++){
				streventcalendar=streventcalendar+'<td>&nbsp;</td>';		
			}
			j=i;
			for(i=1; i<=daysInMonth(dateval.getMonth(), dateval.getFullYear()); i++){
				if(((j+i-1)%7)==0){
					streventcalendar=streventcalendar+'</tr><tr>';
				}
				streventcalendar=streventcalendar+'<td id="date'+i+'">'+i+'</td>';
			}
			i=(j+i-1)%7;
			if(i>0){
				for(; i<7; i++){
					streventcalendar=streventcalendar+'<td>&nbsp;</td>';		
				}
			}
			streventcalendar=streventcalendar+'</tr>';
			streventcalendar=streventcalendar+'</table>';
			$('#eventcalendar').html(streventcalendar);
			$('#curdate').html(month[dateval.getMonth()]+' '+dateval.getFullYear());
			$('#eventloading').hide();			
			$.each(data.events, function(i,item){
				for(k=item.on*1; k<=item.last*1; k++){
					if(!posts[k]){
						$('#eventcontents').append('<div class="eventtooltip" id="content'+k+'"></div>');
						$('#date'+k).addClass("posted");
						$('#date'+k).html('<a href="'+baseDir+'events.php?day='+k+'&year='+dateval.getFullYear()+'&month='+(dateval.getMonth()+1)+'">'+$('#date'+k).text()+'</a>');
						var c='#content'+k;
						$('#date'+k).mouseout(function(){
							$(c).hide();
						});
						$('#date'+k).mouseover(function(){
							$(c).show();
							$(c).css('left', ($(this).position().left+$(this).width()+2)+"px");
							$(c).css('top', ($(this).position().top+$(this).height()+15)+"px");
						});
						posts[k]=true;
					}
					$('#content'+k).append('<div>'+item.title+'<br>'+item.start+' - '+item.end+'</div>');
				}
	          });
	});
}
