//global values
var selectedRow = "";  // global to hold the cell that is clicked on
var theDate; // global Date object
var theMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var daysOfTheWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var daysPerMonth   = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysPerMonthLeap = new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var dayArrayToUse; // holder for the proper array to use, either leap year or normal
var thePassBackField = ""; // the field to pass the info back to.

// previous() sets the global date object to the previous month, taking into account
// that if the current month is "0" (or January), that it goes to December of the 
// previous year.  It then calls the makeCalendar() function.
// Author: Dan Piccolo
function previous() {
	if (theDate.getMonth() == 0) {
		theDate.setMonth(11, 1);
		var theYear = theDate.getFullYear() - 1;
		theDate.setFullYear(parseInt(theYear, 10));
		makeCalendar();
	}
	else {
		var theMonth = theDate.getMonth() - 1;
		theDate.setMonth(parseInt(theMonth, 10), 1);
		makeCalendar();
	}
}

// next() sets the global date object to the next month, taking into account
// that if the current month is "11" (or December), that it goes to January of the 
// next year.  It then calls the makeCalendar() function.
// Author: Dan Piccolo
function next() {
	if (theDate.getMonth() == 11) {
		theDate.setMonth(0, 1);
		var theYear = theDate.getFullYear() + 1;
		theDate.setFullYear(parseInt(theYear, 10));
		makeCalendar();
	}
	else {
		var theMonth = theDate.getMonth() + 1;
		theDate.setMonth(parseInt(theMonth, 10), 1);
		makeCalendar();
	}
}

function up(e) {
	var targetElement;
	if(!e) e = window.event; 
	if(e.target) targetElement = e.target;
	else targetElement = e.srcElement;

	document.getElementById("currentYear").value = parseInt(document.getElementById("currentYear").value, 10) + 1;
	document.getElementById("currentYear").focus();
	targetElement.focus();
}

function down(e) {
	var targetElement;
	if(!e) e = window.event; 
	if(e.target) targetElement = e.target;
	else targetElement = e.srcElement;

	document.getElementById("currentYear").value = parseInt(document.getElementById("currentYear").value, 10) - 1;
	document.getElementById("currentYear").focus();
	targetElement.focus();
}

// initialize() is only called on the page's onload event.  It initializes the global Date 
// object, calls the buildTable() function, and then calls makeCalendar().
// Author: Dan Piccolo
function initialize() {
	theDate = new Date();
	var theQuery = window.location.search;
	thePassBackField = theQuery.substring(theQuery.indexOf("=")+1);
	buildTable();
	makeCalendar();
}

// makeCalendar() populates the calendar table.  It creates a Date object for today, so it can 
// appropriately highlight the current day (assuming that the global Date object matches today's date).
// It calls resetCalendar(), and then populates all the days in the calendar approprately using crazy
// modulus math.  IT also handles leap years.
// Author: Dan Piccolo
function makeCalendar() {
	var today = new Date();
	resetCalendar();
	
	var month = theDate.getMonth();
	var theYear = theDate.getFullYear();
	
	if(isLeap(theYear)) {
		dayArrayToUse = daysPerMonthLeap;
	}
	else {
		dayArrayToUse = daysPerMonth;
	}

	document.getElementById("month").options[month].selected = true;
	document.getElementById("currentYear").value = theYear;
	for(var x=1; x <= dayArrayToUse[month]; x++) {
		theDate.setDate(x);
		var dayIndex = theDate.getDay();
		var theDay = daysOfTheWeek[dayIndex];
		var theWeek = Math.floor(x / 7)+1;
		if (((dayIndex)%7 < x%7)) {
			theWeek++;
		}
		if ((dayIndex+1)%7 == x%7) {
			theWeek--;
		}
		else theWeek = theWeek;
		var theID = theDay.substring(0,2) +""+ theWeek; 
		var theCell = document.getElementById(theID);
		if(today.getDate() == x && today.getMonth() == month && today.getFullYear() == theYear) {
			theCell.style.fontWeight = "bold";
			theCell.style.backgroundColor = "#FFFF00";
			selectedRow = theCell;
		}
		theCell.innerHTML = x;
		theCell.className = "valid";
	}
	if(document.getElementById("datagatherer")) {
		month++;
		if(month < 10) month = "0"+month;
		theDay = "01";
		document.getElementById("datagatherer").src = "getBlogsByDate.php?date="+theYear+"-"+month+"-"+theDay;
	}
}

// resetCalendar() clears the calendar table, and the currently selectedRow.  It uses a nested loop to
// clear all the weeks, but leaves the previous and next buttons, and the days of the week.
// Author: Dan Piccolo
function resetCalendar() {
	if (selectedRow != "") {
		selectedRow.style.fontWeight = "";
		selectedRow.style.backgroundColor = "";
	}
	selectedRow = "";
	for (var x=1; x <= 6; x++) {
		for(var y=0; y < 7; y++) {
			var theID = daysOfTheWeek[y].substring(0,2)+ x
			var theCell = document.getElementById(theID);
			theCell.innerHTML = "&nbsp;";
			theCell.className = "";
		}
	}
}

// isLeap() just takes the modulus of the value passed to it.  If dividing by 4 leaves 0 remainder, it's 
// a leap year, and returns a true or false.
// Author: Dan Piccolo
function isLeap(theYear) {
	if(theYear%4 == 0) return true;
	else return false;
}
	

// rowHighlight() is used to highlight the current selected row or cell.  It's a simple toggle function.
// Author: Dan Piccolo
function rowHighlight(whichRow) {
	if(whichRow.innerHTML != "&nbsp;") {
		if (selectedRow != "") {
		selectedRow.style.fontWeight = "";
		selectedRow.style.backgroundColor = "";
		}
		whichRow.style.fontWeight = "bold";
		whichRow.style.backgroundColor = "#FFFF00";
		selectedRow = whichRow;
	}
}

// buildTable() dynamically creates a table to hold the calendar.  It uses DOM functions to create the
// elements and set appropriate attributes, eventHandlers, etc.  The bulk of the work is done in nested loops.
// Author: Dan Piccolo
function buildTable() {
	// theDiv holds the calendar.
	var theDiv = document.getElementById("calHolder");
	
	// create the table.
	var newTable = document.createElement("table");
	newTable.className = "cal";
	newTable.id = "calendarTable";
	
	// start the header and buttons.
	var newTHead = document.createElement("thead"); 
	newTHead.className = "header";
	var newHeaderTR = document.createElement("tr");
	var newHeadTDs = new Array(3);
	for (var x=0; x < newHeadTDs.length; x++){
		newHeadTDs[x] = document.createElement("td");
		if(x==0) {
			var newPrev = document.createElement("input");
			newPrev.setAttribute("type", "button");
			newPrev.setAttribute("value", "<");
			newPrev.style.fontFace = "Helvetica";
			newPrev.style.fontSize = "9px";
			newPrev.style.lineHeight = "11px";
			newPrev.style.width = "25px";
			if (newPrev.attachEvent) {
				newPrev.attachEvent("onclick", previous);
			}
			else {
				newPrev.setAttribute("onclick", "previous()");
			}
			newHeadTDs[x].appendChild(newPrev);
		}
		if(x==1) {
			newHeadTDs[x].colSpan = "5";
			var newSelect = document.createElement("select");
			newSelect.setAttribute("id", "month");
			newSelect.style.fontFace = "Helvetica";
			newSelect.style.fontSize = "9px";
			newSelect.style.lineHeight = "11px";
			if (newSelect.attachEvent) {
				newSelect.attachEvent("onchange", updateCal);
			}
			else {
				newSelect.setAttribute("onchange", "updateCal()");
			}
			var newOptions = new Array(12);
			for (var y=0;y<newOptions.length;y++) {
				newOptions[y] = document.createElement("option");
				newOptions[y].setAttribute("value", y);
				newOptions[y].innerHTML = theMonths[y];
				newSelect.appendChild(newOptions[y]);
			}
			var newYearText = document.createElement("input");
			newYearText.setAttribute("type", "text");
			newYearText.setAttribute("id", "currentYear");
			newYearText.setAttribute("size", "2");
			newYearText.style.fontFace = "Helvetica";
			newYearText.style.fontSize = "9px";
			newYearText.style.lineHeight = "11px";
			if (newYearText.attachEvent) {
				newYearText.attachEvent("onblur", updateCal);
			}
			else {
				newYearText.setAttribute("onblur", "updateCal()");
			}
			var newUp = document.createElement("input");
			newUp.setAttribute("type", "button");
			newUp.setAttribute("value", "+");
			newUp.style.fontFace = "Helvetica";
			newUp.style.fontSize = "9px";
			newUp.style.lineHeight = "11px";
			newUp.style.width = "25px";
			if (newUp.attachEvent) {
				newUp.attachEvent("onclick", up);
			}
			else {
				newUp.setAttribute("onclick", "up(event)");
			}
			
			var newDown = document.createElement("input");
			newDown.setAttribute("type", "button");
			newDown.setAttribute("value", "-");
			newDown.style.fontFace = "Helvetica";
			newDown.style.fontSize = "9px";
			newDown.style.lineHeight = "11px";
			newDown.style.width = "25px";
			if (newDown.attachEvent) {
				newDown.attachEvent("onclick", down);
			}
			else {
				newDown.setAttribute("onclick", "down(event)");
			}
			
			newHeadTDs[x].appendChild(newSelect);
			newHeadTDs[x].appendChild(newYearText);
			newHeadTDs[x].appendChild(newDown);
			newHeadTDs[x].appendChild(newUp);
			
		}
		if(x==2) {
			var newNext = document.createElement("input");
			newNext.setAttribute("type", "button");
			newNext.setAttribute("value", ">");
			newNext.style.fontFace = "Helvetica";
			newNext.style.fontSize = "9px";
			newNext.style.lineHeight = "11px";
			newNext.style.width = "25px";
			if (newNext.attachEvent) {
				newNext.attachEvent("onclick", next);
			}
			else {
				newNext.setAttribute("onclick", "next()");
			}
			newHeadTDs[x].appendChild(newNext);
		}
		newHeadTDs[x].style.textAlign = "center";
		newHeaderTR.appendChild(newHeadTDs[x]);
	}
	newTHead.appendChild(newHeaderTR);
	newTable.appendChild(newTHead);
	// header and buttons done.

	// start the days of the week
	var newDaysTBody = document.createElement("tbody");
	newDaysTBody.className = "days";
	var newDaysTR = document.createElement("tr");
	var newDaysTD = new Array(7);
	for (x=0; x<newDaysTD.length; x++) {
		newDaysTD[x] = document.createElement("td");
		var theID = daysOfTheWeek[x].substring(0,2) + "0";
		newDaysTD[x].setAttribute("id", theID);
		newDaysTD[x].innerHTML = daysOfTheWeek[x];
		newDaysTR.appendChild(newDaysTD[x]);
	}
	newDaysTBody.appendChild(newDaysTR);
	newTable.appendChild(newDaysTBody);
	// days of the week done
	
	// start the main body of the table.
	var newMainTBody = document.createElement("tbody");
	var newMainTRs = new Array(6);
	for (x=0;x<newMainTRs.length;x++) {
		newMainTRs[x] = document.createElement("tr");
		var newMainTDs = new Array(7);
		for (var y=0;y<newMainTDs.length;y++)  {
			newMainTDs[y] = document.createElement("td");
			var theID = daysOfTheWeek[y].substring(0,2) + (x+1);
			newMainTDs[y].setAttribute("id", theID);
			if (newMainTDs[y].attachEvent) {
				newMainTDs[y].attachEvent("onclick", ieHandler2);
				newMainTDs[y].attachEvent("ondblclick", ieHandler2);
			}
			else {
				newMainTDs[y].setAttribute("onclick", "rowHighlight(this)");
				newMainTDs[y].setAttribute("ondblclick", "selectDate()");
			}
			newMainTRs[x].appendChild(newMainTDs[y]);
		}		
		newMainTBody.appendChild(newMainTRs[x]);
	}
	newTable.appendChild(newMainTBody);
	// main body is done
	
	theDiv.appendChild(newTable);
	// whole table done and added to the page.;
}

// ieHandler2() is required to add event handlers to dynamically created elements in the page.
// It finds out the type of even, and then the element that was clicked on.  After that, it triggers
// the appropriate function to be called for that element on that event.
// Author: Dan Piccolo		
function ieHandler2() {
	var eventType = window.event.type;
	var targetElement;

	if (eventType == "click") {
		targetElement = window.event.srcElement;
		rowHighlight(targetElement);
	}
	if (eventType == "dblclick") {
		targetElement = window.event.srcElement;
		selectDate();
	}
}

function updateCal() {
	theDate.setMonth(document.getElementById("month").options[document.getElementById("month").selectedIndex].value, 1);
	theDate.setFullYear(document.getElementById("currentYear").value);
	makeCalendar();
}


// selectDate() just grabs the selected date in the calendar.  At the moment, it just triggers an alert,
// but will be used to pass back a function.
// Author: Dan Piccolo
function selectDate() {
	
	if (selectedRow != "" && selectedRow.innerHTML != "&nbsp;" ) {
		var MonthHolder = theDate.getMonth()+1;
		var DateHolder = selectedRow.innerHTML;
		if (MonthHolder < 10) {
			MonthHolder = "0"+MonthHolder;
		}
		if (DateHolder < 10) {
			DateHolder = "0"+DateHolder;
		}
		
		if (self.opener && self.opener.document.getElementById(thePassBackField)) {
			var theField = self.opener.document.getElementById(thePassBackField);
			theField.value = theDate.getFullYear()+ "-" + MonthHolder + "-" + DateHolder;
			self.close();
		}
		else {
			alert(theDate.getFullYear()+ "-" + MonthHolder + "-" + DateHolder);
		}
	}
	else {
		alert("Please select a date first");
	}
}

function boldCalendar(theDates) {
	var theTable = document.getElementById("calendarTable");
	var theWeeksBody = theTable.childNodes[2];
	var theWeeks = theWeeksBody.childNodes;
	var theNumbers = theDates.split(",");
	for(var x=0; x<theWeeks.length; x++) {
		var theCells = theWeeks[x].childNodes;
		for(var y=0;y<theCells.length;y++) {
			var theDay = theCells[y].innerHTML;
			theDay = parseInt(theDay, 10);
			var isfound = false;
			for(var z=0;z<theNumbers.length;z++) {
				theNumber = parseInt(theNumbers[z], 10);
				if(theDay == theNumber) { 
					isfound = true;
					break;
				}
			}
			if(isfound) {
				theCells[y].style.fontWeight = "bold";
				theCells[y].style.backgroundColor = "#DADADA";
				
			}
			else {
				theCells[y].style.fontWeight = "";
				theCells[y].style.backgroundColor = "";
			}
		}
	}
	

}

function toggleCalendar() {
	var calendarObject = document.getElementById("calendarContent");
	var navigationObject = document.getElementById("navigationContent");
	if(calendarObject.style.display == "none" || calendarObject.style.display == "") calendarObject.style.display = "block";
	else calendarObject.style.display = "none";
	if(navigationObject.style.display != "none" || navigationObject.style.display != "") navigationObject.style.display = "none";
}

