/* Copyright Commcam Limited 2008. All rights reserved. (See licence/licence.txt) */
 
var arrCalendars = new Array(2);

function updateCalendar()
{
  var strUsername;
  
  strUsername = document.getElementById("user").value;
	startLoading();
	setTimeout("_updateCalendar('" + strUsername + "')", 10);
}

function _updateCalendar(strUsername)
{
	var objAjax, objEdit;
	
	objAjax = new CAjax();
	objAjax.create();
	
	objEdit = document.getElementById("calendar");
	
	if (objAjax.open("main.php?mode=UPDATE&requiredUser=" + strUsername, true))
	{
		objEdit.innerHTML = objAjax.getResponse();	
	}
	
	endLoading();
}



Calendar = function() {	
	this.objTable = null;
	this.objCalenderDiv = null;
	this.objButton = null;
	this.objTextBox = null;
	this.objDate = null;
	this.objWeekHolder = null;
	this.objTitleCell = null;
	this.currentDate = new Date();
	this.nCalendar = 0;
	this.bPopup = false;
}

//Sets up the Calendar using the date passed to it.
Calendar.prototype.setup = function(nCalendar, objDate, bPopup, strDivName) {
	// Create the table that will contain the calendar.
	this.nCalendar = nCalendar;
	this.bPopup = bPopup;
	
	this.objTable = this.createElement("table");
	this.objDate = objDate;
	this.currentDate.setDate(this.objDate.getDate());
	this.currentDate.setMonth(this.objDate.getMonth());
	this.currentDate.setFullYear(this.objDate.getFullYear());
	
	this.createCalendar(this.objTable);

	if (bPopup)
	{
		// Create a DIV and attach the table to it.
		this.objCalenderDiv = this.createElement("div", document.body);
	}
	else
	{
		// Create a DIV and attach the table to it.
		this.objCalenderDiv = document.getElementById(strDivName);

		if (this.objCalenderDiv == undefined)
		{
			alert("Could not find a div named '" + strDivName + "', cannot display calendar");
		}
	}
	this.objCalenderDiv.className = "Calendar";

	this.objCalenderDiv.appendChild(this.objTable);
	
	return true;
}

//Sets up the Calendar using the date passed to it.
Calendar.prototype.changeDate = function(objDate) {
	var nTempMonth, nTempYear;
	
	this.objDate = objDate;
	this.currentDate.setDate(this.objDate.getDate());
	this.currentDate.setMonth(this.objDate.getMonth());
	this.currentDate.setFullYear(this.objDate.getFullYear());
	
	nTempMonth = this.objDate.getMonth();
	nTempYear = this.objDate.getFullYear();
	
	// Set the month and year
	this.objDate.setMonth(nTempMonth);
	this.objDate.setYear(nTempYear);

	// Display the month and then update the title.
	this.displayMonth();
	this.populateTitleCell();
	
	return true;
}


//This function starts the creation process of the calendar.
Calendar.prototype.createCalendar = function(objTable) {
	var objTBody;
		
	objTable.cellspacing = "0";
	objTable.cellpadding = "0";
	objTable.className = "CalendarTable";

	objTBody = this.createElement("tbody", objTable);

	this.createHeader(objTBody);
	this.displayMonth();
	
	if (this.bPopup)
	{
		// Add the event onmousedown, so when the user clicks on the page it can hide the calendar.
		eval("document.attachEvent('onmousedown', function() { Calendar.checkCalendar(" + this.nCalendar + "); });");
	
	}
}

//  Creates the header of the table, containing the buttons and day list.
Calendar.prototype.createHeader = function(objTable) {
	var objHeader, objTitleHeader, objEmptyCell, objTitleCell, objDayBar, objWeekHolder, objPrevYear, objPrevMonth, objNextYear, objNextMonth;

	// Button row.
	objHeader = this.createElement("tr", objTable);
	objHeader.className = "CalendarTitle";

	// Previous Year Button
	objPrevYear = this.createElement("td", objHeader);
	objPrevYear.innerHTML = "&lt;&lt;";
	objPrevYear.className = "CalendarButton";
	eval("objPrevYear.attachEvent('onclick', function() { Calendar.prevYear(" + this.nCalendar + "); });");
	objPrevYear.attachEvent("onmouseover", Calendar.mouseOverButton);
	objPrevYear.attachEvent("onmouseout", Calendar.mouseOutButton);
	
	// Previous Month Button
	objPrevMonth = this.createElement("td", objHeader);
	objPrevMonth.innerHTML = "&lt;";
	objPrevMonth.className = "CalendarButton";
	eval("objPrevMonth.attachEvent('onclick', function() { Calendar.prevMonth(" + this.nCalendar + "); });");
	objPrevMonth.attachEvent("onmouseover", Calendar.mouseOverButton);
	objPrevMonth.attachEvent("onmouseout", Calendar.mouseOutButton);
	
	// Empty cell, between the buttons.
	objEmptyCell = this.createElement("td", objHeader);
	objEmptyCell.colSpan = "3";
	
	// Next Month Button
	objNextMonth = this.createElement("td", objHeader);
	objNextMonth.innerHTML = "&gt;";
	objNextMonth.className = "CalendarButton";
	eval("objNextMonth.attachEvent('onclick', function() { Calendar.nextMonth(" + this.nCalendar + "); });");
	objNextMonth.attachEvent("onmouseover", Calendar.mouseOverButton);
	objNextMonth.attachEvent("onmouseout", Calendar.mouseOutButton);
	
	// Next Year Button
	objNextYear = this.createElement("td", objHeader);
	objNextYear.innerHTML = "&gt;&gt;";
	objNextYear.className = "CalendarButton";
	eval("objNextYear.attachEvent('onclick', function() { Calendar.nextYear(" + this.nCalendar + "); });");
	objNextYear.attachEvent("onmouseover", Calendar.mouseOverButton);
	objNextYear.attachEvent("onmouseout", Calendar.mouseOutButton);
	
	objTitleHeader = this.createElement("tr", objTable);
	objTitleHeader.className = "CalendarTitle";
	
	// Class global Title Cell to allow this title to be changed when the month/year is changed.
	this.objTitleCell = this.createElement("td", objTitleHeader);
	this.objTitleCell.colSpan = "7";
	
	this.populateTitleCell();
	
	// Day Bar
	objDayBar = this.createElement("tr", objTable);
	objDayBar.className = "CalendarDayBar";
	
	// Week starts on Sunday
	this.createElement("td", objDayBar, "S");
	this.createElement("td", objDayBar, "M");
	this.createElement("td", objDayBar, "T");
	this.createElement("td", objDayBar, "W");
	this.createElement("td", objDayBar, "T");
	this.createElement("td", objDayBar, "F");
	this.createElement("td", objDayBar, "S");

	// Create the element that will be used to hold the weeks.
	this.objWeekHolder = this.createElement("bodyweeks", objTable);
}

//Populates the Title of the calendar.
Calendar.prototype.populateTitleCell = function() {
	// Month Year
	this.objTitleCell.innerHTML = Calendar.getMonthName(this.objDate.getMonth()) + " " + this.objDate.getUTCFullYear();
}

//Populates the bodyweeks holder with the current month.
Calendar.prototype.displayMonth = function() {
	var nCurrentDay, nFirstDayOfTheMonth, nLastDayOfMonth;

	nCurrentDay = 1;
	nFirstDayOfTheMonth = Calendar.getFirstDayOfMonth(this.objDate);
	nLastDayOfMonth = Calendar.getLastDateOfMonth(this.objDate);

	// Remove all the nodes from the previous month.
	while(this.objWeekHolder.childNodes.length > 0) {
		this.objWeekHolder.removeChild(this.objWeekHolder.childNodes.item(0));
	}

	// Keep adding weeks to the Calendar until the last week hits the end of the month
	while (nCurrentDay <= nLastDayOfMonth) {
		nCurrentDay = this.displayWeek(nCurrentDay, nFirstDayOfTheMonth, nLastDayOfMonth);
	}
}

//Display the week starting at <nCurrentDay>.
Calendar.prototype.displayWeek = function(nCurrentDay, nFirstDayOfTheMonth, nLastDayOfMonth)
{
	var nDayOfWeek, objWeekRow, objDayCell, nDaysInWeek, nTempCurrentDay, displayDate, todaysDate;
	objWeekRow = this.createElement("tr", this.objWeekHolder);
	
	todaysDate = Calendar.getFullDate(this.currentDate.getDate()) + "/" + Calendar.getFullMonth(this.currentDate.getUTCMonth()) + "/" + this.currentDate.getUTCFullYear()
	
	// Loop for seven days.
	for (nDayOfWeek = 1; nDayOfWeek <= 7; nDayOfWeek++) {
		// If current day is 1, then start incrementing days until current day is first day of the week.
		if ((nCurrentDay == 1 && nDayOfWeek < nFirstDayOfTheMonth) || nCurrentDay > nLastDayOfMonth) {
			objDayCell = this.createElement("td", objWeekRow, "-");
			objDayCell.className = "CalendarNoDay";
		}
		else {
			// Display the day.
			objDayCell = this.createElement("td", objWeekRow, "" + nCurrentDay);
			displayDate = Calendar.getFullDate(nCurrentDay) + "/" + Calendar.getFullMonth(this.objDate.getUTCMonth()) + "/" + this.objDate.getUTCFullYear();
			
			if(todaysDate == displayDate) {
				objDayCell.className = "CalendarToday";
				objDayCell.attachEvent("onmouseout", Calendar.mouseOutToday);
			}
			else {
				objDayCell.className = "CalendarDay";
				objDayCell.attachEvent("onmouseout", Calendar.mouseOutDay);
				
			}
			objDayCell.date = nCurrentDay;
			
			// Add the events, so when the user clicks on a date, the function 'dateSelected'
			// is fired.
			eval("objDayCell.attachEvent('onclick', function() { Calendar.dateSelected(" + this.nCalendar + "); });");
			objDayCell.attachEvent("onmouseover", Calendar.mouseOverDay);
			

			nCurrentDay++;
		}
	}
	return nCurrentDay;
}

/*
 *  Shows the calendar next to the passed button <objButton>, and populates the
 *  input box <objTextBox> with the date selected.
 */
Calendar.prototype.showPopup = function(objButton, objTextBox) {
	var parentRect = document.body.getClientRects();
	this.objButton = objButton;
	this.objTextBox = objTextBox;
	this.objCalenderDiv.style.left = objButton.getClientRects()[0].left + document.body.scrollLeft;
	this.objCalenderDiv.style.top = objButton.getClientRects()[0].bottom + document.body.scrollTop;
	this.objCalenderDiv.style.display = "block";
}

Calendar.prototype.display = function(objTextBox) {
	var parentRect = document.body.getClientRects();
	this.objTextBox = objTextBox;
	//this.objCalenderDiv.style.position = "relative";
}


//Hides the calendar.
Calendar.prototype.hide = function() {

	if (this.bPopup)
	{
		this.objCalenderDiv.style.display = "none";
	}
}

//Populates the text box <objTextBox> with the selected date.
Calendar.prototype.selectDate = function(nDate) {
	this.objDate.setDate(nDate);
	this.currentDate.setDate(nDate);

	this.objTextBox.value = Calendar.getFullDate(nDate) + "/" + Calendar.getFullMonth(this.objDate.getUTCMonth()) + "/" + this.objDate.getUTCFullYear();
	if (this.bPopup)
	{
		this.hide();
	}
	else
	{
		this.changeDate(this.objDate);
	}
}

//Populates the text box <objTextBox> with the selected date.
Calendar.prototype.getSelectedDate = function(nDate) {
	return Calendar.getFullDate(nDate) + "/" + Calendar.getFullMonth(this.objDate.getUTCMonth()) + "/" + this.objDate.getUTCFullYear();
}

// Returns 2 digit string.
Calendar.getFullMonth = function(nMonth) {
	nMonth ++;
	if (nMonth < 10) {
		nMonth = "0" + nMonth;
	}
	return nMonth;
}

//Returns a 2 digit string.
Calendar.getFullDate = function(nDay) {
	if (nDay < 10) {
		nDay = "0" + nDay;
	}
	return nDay;
}

//Returns first day of week of passed date <objDate>
Calendar.getFirstDayOfMonth = function(objDate) {
	var nDate, nFirstDayOfMonth;
	if (objDate == null) {
		return 0;
	}
	nDate = objDate.getDate();
	objDate.setDate(1);
	nFirstDayOfMonth = objDate.getDay();
	objDate.setDate(nDate);
	
	nFirstDayOfMonth++;
	if (nFirstDayOfMonth > 7) {
		nFirstDayOfMonth = 1;
	}
	return nFirstDayOfMonth;
}

//Returns last day of current month.
Calendar.getLastDateOfMonth = function(objDate) {
	var nDate, nLastDateOfTheMonth, objTempDate;
	if (objDate == null) {
		return 0;
	}
	
	objTempDate = new Date();
	objTempDate.setMonth(objDate.getMonth() + 1);
	objTempDate.setDate(0);
	
	nLastDateOfTheMonth = objTempDate.getDate();
	
	// If month is February, change to 28 if leap year.
	if (objDate.getMonth() == 1 && !Calendar.CheckLeapYear(objDate.getYear())) {
		nLastDateOfTheMonth = 28;
	}
	return nLastDateOfTheMonth;
}

//Checks if current year is a leap year.
Calendar.CheckLeapYear = function(nYear) {
	return (((nYear % 4 == 0) && (nYear % 100 != 0)) || (nYear % 400 == 0)) ? true : false;
}

//Returns month's name
Calendar.getMonthName = function(nMonth) {
	var strReturnMonth;
	var arrMonthList = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	strReturnMonth = arrMonthList[nMonth];
	return strReturnMonth;
}

/*
 *  Takes a differential month <nMonth> and year <nYear> and changes the current calendar to
 *  reflec these changes.
 */
Calendar.prototype.setDate = function(nMonth, nYear) {
	var nTempMonth, nTempYear;
	
	// Increment month and year.
	nTempMonth = this.objDate.getMonth() + nMonth;
	nTempYear = this.objDate.getFullYear() + nYear;

	if (nTempMonth < 0)
	{
		nTempMonth = 11;
		nTempYear --;
	}
	else if (nTempMonth >= 12)
	{
		nTempMonth = 0;
		nTempYear ++;
	}
	
	// Set the month and year
	this.objDate.setMonth(nTempMonth);
	this.objDate.setYear(nTempYear);
	
	// Display the month and then update the title.
	this.displayMonth();
	this.populateTitleCell();
}

//Function called when the previous year button is pressed.
Calendar.prevYear = function(nCalendar) {
	arrCalendars[nCalendar].setDate(0, -1);
}

//Function called when the previous month button is pressed.
Calendar.prevMonth = function(nCalendar) {
	arrCalendars[nCalendar].setDate(-1, 0);
}

//Function called when the next month button is pressed.
Calendar.nextMonth = function(nCalendar) {
	arrCalendars[nCalendar].setDate(1, 0);
}

//Function called when the next year button is pressed.
Calendar.nextYear = function(nCalendar) {
	arrCalendars[nCalendar].setDate(0, 1);
}

//Function called when user mouses over a day
Calendar.mouseOverDay = function(objEvent) {
	var objElement = objEvent.srcElement;
	objElement.className = "CalendarDayOver";
}

//Function called when user's mouse leaves a day cell.
Calendar.mouseOutDay = function(objEvent) {
	var displayDate;
	var objElement = objEvent.srcElement;

	objElement.className = "CalendarDay";
}

//Function called when user's mouse leaves a day cell.
Calendar.mouseOutToday = function(objEvent) {
	var displayDate;
	var objElement = objEvent.srcElement;

	objElement.className = "CalendarToday";
}

//Function called when user mouses over a button
Calendar.mouseOverButton = function(objEvent) {
	var objElement = objEvent.srcElement;
	objElement.className = "CalendarButtonOver";
}

//Function called when user's mouse leaves a button.
Calendar.mouseOutButton = function(objEvent) {
	var objElement = objEvent.srcElement;
	objElement.className = "CalendarButton";
}

//Creates an 'XML' node <strName> and adds it to the parent node <objParent> if required.
Calendar.prototype.createElement = function(strName, objParent, strText) {
	var objElement = null;
	objElement = document.createElement(strName);

	// If a string was passed, set the text of the node to that.
	if (strText != null) {
		objElement.innerHTML = strText;
	}
	// If a parent was passed, add the newly created node to it.
	if (objParent != null) {
		objParent.appendChild(objElement);
	}
	return objElement;
}

//User has pressed mouse button (anywhere) - see if calendar needs hidding.
Calendar.checkCalendar = function(nCalendar) {
	var objElement = event.srcElement;
	
	// Check the object clicked and all the parents until we come across the calendar div.
	for (; objElement != null && objElement != arrCalendars[nCalendar].objCalenderDiv; objElement = objElement.parentNode);

	// If we did not come across the calendar div, then the user must have clicked a different
	// part of the screen.
	if (objElement == null)
	{
		arrCalendars[nCalendar].hide();
		document.detachEvent("onMouseDown", Calendar.checkCalendar);
	}
}

//The user clicked on a date, so select it and populate the text box.
Calendar.dateSelected = function(nCalendar) {
	var objElement;
	objElement = event.srcElement;
	arrCalendars[nCalendar].selectDate(objElement.date);
	arrCalendars[nCalendar].hide();
}

//Function called when the user clicks on a calendar button.
function createCalendar(objHiddenText, nCalendar, strDivName) {
	var nDay, nMonth, nYear;
	var objDate = new Date();
	
	nDay = objHiddenText.value.substring(0, 2);
	nMonth = objHiddenText.value.substring(3, 5);
	nYear = objHiddenText.value.substring(6, 10);
	
	if (!isNaN(nDay) && !isNaN(nMonth) && !isNaN(nYear))
	{
		objDate.setDate(nDay);
		objDate.setMonth(nMonth - 1);
		objDate.setFullYear(nYear);
	}
	
	if (arrCalendars[nCalendar] == null) {
		arrCalendars[nCalendar] = new Calendar();
		arrCalendars[nCalendar].setup(nCalendar, new Date(), false, strDivName);
	}
	
	arrCalendars[nCalendar].changeDate(objDate);

	arrCalendars[nCalendar].display(objHiddenText);
	
	return false;
}

//Function called when the user clicks on a calendar button.
function showCalendarPopup(objButton, objTextBox, nCalendar) {
	var nDay, nMonth, nYear;
	var objDate = new Date();
	
	if (objTextBox.value != "")
	{
		nDay = objTextBox.value.substring(0, 2);
		nMonth = objTextBox.value.substring(3, 5);
		nYear = objTextBox.value.substring(6, 10);
		
		if (!isNaN(nDay) && !isNaN(nMonth) && !isNaN(nYear))
		{
			objDate.setDate(nDay);
			objDate.setMonth(nMonth - 1);
			objDate.setFullYear(nYear);
		}
	}
	
	if (arrCalendars[nCalendar] == null) {
		arrCalendars[nCalendar] = new Calendar();
		arrCalendars[nCalendar].setup(nCalendar, new Date(), true, "");
	}

	arrCalendars[nCalendar].changeDate(objDate);
	arrCalendars[nCalendar].showPopup(objButton, objTextBox);
	
	return false;
}
