var updateRequest;
//get first day of current month
var currentMonth = new Date();
currentMonth.setDate(1);
var earliestMonth = new Date(2009,0,1);
var latestMonth = new Date(2010,0,1);

function monthToString(month) {
	switch(month) {
	case 1:
		return "January";
	case 2:
		return "February";
	case 3:
		return "March";
	case 4:
		return "April";
	case 5:
		return "May";
	case 6:
		return "June";
	case 7:
		return "July";
	case 8:
		return "August";
	case 9:
		return "September";
	case 10:
		return "October";
	case 11:
		return "November";
	case 12:
		return "December";
	};
}

function getDay(entry) {
	var whenElem = entry.getElementsByTagName("gd:when")[0];
	if(!whenElem) {
		whenElem = entry.getElementsByTagName("when")[0];
	}
	timestring = whenElem.attributes.getNamedItem("startTime").value;
	numbers = timestring.match(/\d+/g);
	return parseInt(numbers[2],10);
}

function getISOString(da) {
	dy = da.getFullYear() 		// Get full year (as opposed to last two digits only)
	dm = da.getMonth() + 1 		// Get month and correct it (getMonth() returns 0 to 11)
	dd = da.getDate() 			// Get date within month
	if ( dy < 1970 ) dy = dy + 100; 	// We still have to fix the millennium bug
	ys = new String(dy) 		// Convert year, month and date to strings
	ms = new String(dm) 	 
	ds = new String(dd) 	 
	if ( ms.length == 1 ) ms = "0" + ms; 	// Add leading zeros to month and date if required
	if ( ds.length == 1 ) ds = "0" + ds; 	 
	ys = ys + "-" + ms + "-" + ds
	return ys	
}

function setNextPrevLinks() {
	var prevMonth = new Date(currentMonth.getFullYear(),currentMonth.getMonth()-1,1);
	var nextMonth = new Date(currentMonth.getFullYear(),currentMonth.getMonth()+1,1);
	if (prevMonth >= earliestMonth) {
		replaceText(document.getElementById("prevMonthField"),monthToString(prevMonth.getMonth()+1) + " " + prevMonth.getFullYear());
	} else {
		clearText(document.getElementById("prevMonthField"));
	}
	replaceText(document.getElementById("currentMonthField"),monthToString(currentMonth.getMonth()+1) + " " + currentMonth.getFullYear());
	if (nextMonth <= latestMonth) {
		replaceText(document.getElementById("nextMonthField"),monthToString(nextMonth.getMonth()+1) + " " + nextMonth.getFullYear());
	} else {
		clearText(document.getElementById("nextMonthField"));
	}
}

function updateCalendar() {
	updateRequest = createRequest();
	var lastDayOfMonth = new Date(currentMonth.getFullYear(),currentMonth.getMonth()+1);
	lastDayOfMonth.setDate(0);
	var url = "fetchGCal.php" +
			  "?start-min=" + getISOString(currentMonth) +
			  "&start-max=" + getISOString(lastDayOfMonth) + 
			  "&dummy=" + new Date().getTime();
	updateRequest.onreadystatechange = calendarUpdated;
	updateRequest.open('GET',url,true);
	updateRequest.send(null);
	setNextPrevLinks();
}

function calendarUpdated() {
	if (updateRequest.readyState == 4) {
		if (updateRequest.status == 200) {
			if(updateRequest.responseXML) {
				//get booked days into boolean array
				var entries = updateRequest.responseXML.getElementsByTagName("entry");
				var lastDayOfMonth = new Date(currentMonth.getFullYear(),currentMonth.getMonth()+1);
				lastDayOfMonth.setDate(0);
				var daysInMonth = lastDayOfMonth.getDate();
				var daysBooked = new Array(daysInMonth+1);
				for(i = 0; i < daysBooked.length; i++) {
					daysBooked[i] = false;
				}
				for(i = 0; i < entries.length ; i++) {
					daysBooked[getDay(entries[i])] = true;
				}
				
				var row_index = 0;
				var calendar_index = 1 - currentMonth.getDay();
				
				//clear out calendar
				var table = document.getElementById("calendarTable");
				while(table.rows.length > 1) {
					table.deleteRow(1);
				}

				while (calendar_index <= daysInMonth) {
					var i = row_index;
					var c = calendar_index;
					var row = table.insertRow(table.rows.length);
					
					row.className="number";
					do {
						var cell = row.insertCell(row.cells.length);
						cell.className = "calbox";
						if(c > 0 && c <= daysInMonth) {
							cell.innerHTML = " " + c + " ";
						} 
						i++;
						c++;
					} while (i % 7 != 0);
					
					i = row_index;
					c = calendar_index;
					row = table.insertRow(table.rows.length);
					row.className="day";
					do {
						var cell = row.insertCell(row.cells.length);
						if(c > 0 && c <= daysInMonth && daysBooked[c]) {
							cell.className="busy";					
						} else {
							cell.className="calbox";
						}
						i++;
						c++;
					} while (i % 7 != 0);
					calendar_index=c;
				}
			
			} else {
				alert("Failed to xml from server!");
			}
		} else {
			alert("Page load failed! Error code = " +updateRequest.status);
		}
	}
}

function nextMonth() {
	currentMonth.setMonth(currentMonth.getMonth() + 1);
	updateCalendar();
}

function prevMonth() {
	currentMonth.setMonth(currentMonth.getMonth() - 1);
	updateCalendar();
}
