var requestUrl = "/calendar.php";
var d=new Date();
var currentMonth = d.getMonth()+1;
var currentYear = d.getFullYear();

//To go foward a month we call "handleCalendarRequest('next')" and "handleCalendarRequest('prev')" to go back a month
function handleCalendarRequest(direction)
{
    ax = ajaxRequest();
    if(direction == 'next') {
        currentMonth++;
        if(currentMonth > 12){currentMonth=1;currentYear++;}
    }
    else if(direction == 'prev') {
        currentMonth--;
        if(currentMonth < 1){currentMonth=12;currentYear--;}
    }
    
    ax.onreadystatechange = fillCalendar;
    var query = "?cm=" + currentMonth + "&cy=" + currentYear;
    ax.open("GET", requestUrl + query);
    ax.send(null);
}

function fillCalendar()
{
	var celem = "CalendarContent";
    if(ax.readyState==4)
    {
        var calendarDate = new Date();
        calendarDate.setFullYear(currentYear);
        calendarDate.setMonth(currentMonth-1);
        //calendarDate = calendarDate.toLocaleDateString();
        //var calendarArray = calendarDate.split(",");
        //var calendarMonth = calendarArray[1].substring(1,calendarArray[1].length);
        //calendarMonth = calendarMonth.substring(0, calendarMonth.indexOf(" "));
        
		try{
			document.getElementById(celem).innerHTML = ax.responseText;
		} catch(e){}
		
        //Now we have the month and year the calendar is in, so we can put it in between the "<<" and the ">>" links
        //alert("Month: " + calendarMonth + "\nYear: " + currentYear);
        
        //alert(ax.responseText);
		//We will set the summary tooltips after everything gets finished, and the HTML is set
        //setSummarys();
    }
}

function setSummarys()
{
    lastX = 0;
    lastY = 0;
    var dates = $("div[rel='summaryTooltip']");
    dates.mouseenter(function(e){
        lastX = e.clientX + $(document.body).scrollLeft();
        lastY = e.clientY + $(document.body).scrollTop();
        summaryShowToolTip(lastX, lastY, $(e.currentTarget).next());
    });
    dates.next().mouseenter(function(e){
        summaryShowToolTip(lastX, lastY, $(e.currentTarget));
    });
    dates.next().mouseleave(function(e){
        summaryHideToolTip($(e.currentTarget));
    });
    dates.mouseleave(function(e){
        summaryHideToolTip($(e.currentTarget).next());
    });
    $("div[rel='summaryTooltip']").next().addClass("tooltip");
}

function summaryShowToolTip(left, top, ele)
{
    $(ele).css({'top':top + 'px', 'left':left + 'px', 'display':'block'});
}

function summaryHideToolTip(ele)
{
    $(ele).css('display','none');
}

function ajaxRequest(){
	var ajax = null;
	if(typeof(XMLHttpRequest) == "function" || typeof(XMLHttpRequest) == "object"){
		ajax = new XMLHttpRequest();
	} else if(typeof(ActiveXObject) == "function"){
		try{ajax = new ActiveXObject("Msxml2.XMLHTTP");}
		catch (e) {
			try{ajax = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}
		}
	}
	return ajax;
}

handleCalendarRequest();