
//global javascript vars
var calendars;							//array of calendar_ids to work with
var calendar_ids;						//a separate var to store an array of the calendar_ids
var calendar_ids_string;		//stores a string rep of calendar_ids
var calendar_layout;				//day,week,month,etc...
var user_relation;					//string saying what relation this user is to this calendar
														//(owner,moderator,friend,etc...)
var user_id;								//user_id of the user accessing this calendar
var ajax_url;								//url to the ajax file used in this calendar page
var default_timezone;				//timezone to use if user is not logged in or timezone is not set
var timezone_not_set;				//boolean to determin whether to show select timezone screen
var timezone;								//store timezone setting for current calendar (int:-12 to +13)
var is_error;								//boolean to determin if there is an error with this calendar
var show_admin;							//boolean. whether to allow admin actions or not (add/edit/delete events)
var ajax_timeout = 10000;		//default timeout value for ajax requests (10 sec)
var selected_date;					//currently selected date in date object
var selected_date_str;			//string representation of selected_date. Ex: '2007,1,15'
var loading_image_url;			//url of image to show when loading ajax requests
var updating_mini_cal = false;	//flag as true if in the middle of the script that updates the
																//selected cells
var node_id;								//stores the node_id of the node that is loading this calendar
var show_create;						//boolean that determins whether to load the create event screen at startup
var calendarMainHeight;			//int to store the height of the main container for IE6

var lang_glob; 						// The language in which the months should be stored



/*******************************************************************************
 *	This function is called when the calendar is initialized and is passed
 *	several parameters to define the init state of the calendar. Basicly
 *	assigning php class vars to javascript code.
 */
function initCalVars(cals,calIds,calLayout,userRelation,userId,ajaxURL,defaultTimezone,
										 timezoneNotSet,time_zone,isError,showAdmin,selectedDate,loadingImageUrl,
										 nodeId,showCreate,lang) {
	calendars = cals;
	calendar_ids = calIds;
	calendar_ids_string = calendar_ids.toString();
	calendar_layout = calLayout;
	user_relation = userRelation;
	user_id = userId;
	ajax_url = ajaxURL;
	default_timezone = defaultTimezone;
	timezone_not_set = timezoneNotSet;
	timezone = time_zone;
	is_error = isError;
	show_admin = showAdmin;
	loading_image_url = loadingImageUrl;
	node_id = nodeId;
	show_create = showCreate;
	lang_glob = lang;
	
	calendarMainHeight = 524;	//for IE6

	//set default date if none is provided
	if (selectedDate == '') {
		selected_date = new Date()
	}
	else {
		selected_date = new Date(selectedDate);
		var month = selected_date.getMonth();
		var year = selected_date.getFullYear();
		YAHOO.onesite.calendar.cal1.setMonth(month);
		YAHOO.onesite.calendar.cal1.setYear(year);
	}
	//set date string
	setSelectedDateString();

	//preload loading_image_url
	var preload_image = new Image();
	preload_image.src = loading_image_url;

	//load content
	//getCalendarContent();
	var date_str = (selected_date.getMonth()+1).toString() + '/'
								+ selected_date.getDate().toString() + '/'
								+ selected_date.getFullYear().toString();
	YAHOO.onesite.calendar.cal1.select(date_str);
}


/*******************************************************************************
 *	This function is called when a date is selected from the small yui
 *	calendar widget. This function only executes when updating_mini_cal=false.
 *	This is b/c this function is called by the default event for the mini yui
 *	calendar when a date is selected (this is good). But it is also called
 *	when we need to update the view for the selected dates for an entire month
 *	or week (this is when we dont want to do the things in this function).
 */
function selectDateEvent(type,args,obj) {
	if (!updating_mini_cal) {
		//hide mini cal
		//hideNav();
		
		//set date
		selected_date = this._toDate(args[0][0]);

		//set date string
		setSelectedDateString();

		//update selected calendar dates on the mini yui calendar
		setTimeout('updateMiniCalSelection();',500);

		//load new date content
		getCalendarContent();

		//alert(selected_date);
		//alert("Selected: " + this._toDate(selected_date));
	}
}


/*******************************************************************************
 *	This function takes the current selected_date and formats it as a string
 *	to be stored in selected_date_str. Usefull for ajax requests where we need
 *	to pass a date as a GET variable.
 */
function setSelectedDateString() {
	var month = selected_date.getMonth() + 1;
	var day = selected_date.getDate();
	var year = selected_date.getFullYear();
	selected_date_str = year + ',' + month + ',' + day;
}


/*******************************************************************************
 *	This function is called when a date is deselected from the small yui
 *	calendar widget.
 */
function deselectDateEvent(type,args,obj) {
	//var deselected = args[0];
	//alert("Deselected: " + this._toDate(args[0]));

	var deselected_date = this._toDate(args[0]);
	var month = deselected_date.getMonth() + 1;
	var day = deselected_date.getDate();
	var year = deselected_date.getFullYear();
	var date_str = month.toString() + '/' + day.toString() + '/' + year.toString();
	YAHOO.onesite.calendar.cal1.select(date_str);

	YAHOO.onesite.calendar.cal1.render();
}


/*******************************************************************************
 *	Is called when the user has not yet selected a timezone yet. Attempts
 *	to load the select timezone form for them.
 */
function selectUserTimezone() {
	var calContainer = document.getElementById('calendarMain');
	//calContainer.innerHTML = 'you need to select a timezone';

	showCalendarLoading();

	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=select_user_timezone&cal_ids=' + calendar_ids_string
										+ '&layout=' + calendar_layout
										+ '&user_id=' + user_id
										+ '&current_tz=' + timezone
										+ '&ms=' + new Date().getTime(),
				{
								success: handleSelectUserTimezone,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This function handles the returned ajax request from selectUserTimezone.
 *	Prints the select timezone form to the page.
 */
function handleSelectUserTimezone(req) {
	//printResponse(req);

	var calContainer = document.getElementById('calendarMain');
	calContainer.innerHTML = req.responseText;
}


/*******************************************************************************
 *	This function submits the users selected timezone to store in the db.
 */
function updateTimezoneSetting() {
	showCalendarLoading();

	var new_tz = parseInt(document.getElementById('timezone_list').value);

	//update timezone setting
	timezone = new_tz;

	//update users db record
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=update_user_timezone&cal_ids=' + calendar_ids_string
										+ '&layout=' + calendar_layout
										+ '&user_id=' + user_id
										+ '&new_tz=' + timezone
										+ '&ms=' + new Date().getTime(),
				{
								success: handleUpdateTimezoneSetting,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	Called once the ajax request from updateTimezoneSetting() has returned
 *	a result.
 */
function handleUpdateTimezoneSetting(req) {
	var calContainer = document.getElementById('calendarMain');
	calContainer.innerHTML = req.responseText + '<div style="text-align:center;">'
												+ '<img src="' + loading_image_url + '" '
												+ 'style="width:40px; position:relative; top:0px;" /></div>';

	//update timezone_not_set
	timezone_not_set = false;

	//wait, and then continue to main calendar page
	setTimeout("getCalendarContent();",2500);
}


/*******************************************************************************
 *	Returns the position (x and y values) of a given object printed on the
 *	screen.
 */
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


/*******************************************************************************
 *	Called when an Ajax request reported an error.
 */
function reportError(request) {
	//alert('Sorry! There was an error.');
	var calContainer = document.getElementById('calendarMain');
	calContainer.innerHTML = 'Sorry! There was an error.';
}


/*******************************************************************************
 *	This function makes an ajax request to retrieve a calendar for the given
 *	date and the given layout.
 */
function getCalendarContent() {

	//load select timezone screen if not selected
	if (timezone_not_set) {
		selectUserTimezone();
		return;
	}

	//show upload screen as first screen if requested
	if (show_create) {
		show_create = false;
		var month = selected_date.getMonth() + 1;
		var day = selected_date.getDate();
		var year = selected_date.getFullYear();
		createEvent(year,month,day);
		return;
	}

	showCalendarLoading();
	
	//determin which layout to show (admin or view)
	if (show_admin)
		var param_admin = 'admin';
	else
		var param_admin = 'view';
	
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=print_calendar_content&cal_ids=' + calendar_ids_string
										+ '&layout=' + calendar_layout + '&date=' + selected_date_str
										+ '&timezone=' + timezone
										+ '&view=' + param_admin
										+ '&ms=' + new Date().getTime(),
				{
								success: handlePrintCalendarContent,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This is the function that handles the ajax response for getCalendarContent()
 *	Prints the new content to the main calendar div.
 */
function handlePrintCalendarContent(req) {
	//printResponse(req);

	var calContainer = document.getElementById('calendarMain');
	//calContainer.innerHTML = req.responseText;
	
	//resize containers if necessary
	if (document.getElementById('allDayEventsContainer')) {
		var allDayElm = document.getElementById('allDayEventsContainer');
		var allDayHeight = allDayElm.offsetHeight;
		var containerHeight = calContainer.offsetHeight;
		
	}
	
	//update calendar title header
	var m_names = get_local_months(lang_glob);
	/*
	var m_names = new Array("January", "February", "March",
			"April", "May", "June", "July", "August", "September",
			"October", "November", "December"); */
	var m_names_short = get_local_short_months(lang_glob);
	/*
	var m_names_short = new Array("Jan","Feb","Mar","Apr","May",
			"Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	*/
	var m_days = get_local_days(lang_glob);
	
	/*
	var m_days = new Array("Sunday","Monday","Tuesday","Wednesday",
			"Thursday","Friday","Saturday");
	*/
	var month = selected_date.getMonth();
	var day = selected_date.getDate();
	var day2 = selected_date.getDay();
	var year = selected_date.getFullYear();
	
	calContainer.innerHTML = req.responseText;
	
	var header_str = m_names[month] + ', ' + year;
	if (calendar_layout == 'month') {
		header_str = m_names[month] + ', ' + year;
	}
	else if (calendar_layout == 'day') {
		header_str = m_days[day2] + ' ' + m_names_short[month] + ' ' + day + ', ' + year;
		
		var calContainerHeight = calContainer.offsetHeight;
		var calContainerWidth = calContainer.offsetWidth;
		if (calContainerHeight < 200) {	//some small number
			var newHeight = calendarMainHeight;
		}
		else {
			var newHeight = calContainerHeight;
		}
		newHeight = newHeight - 16;	//16 for header and border
		var newWidth = calContainerWidth - 2;
		
		//resize height if there are all-day events that take up height
		if (document.getElementById('allDayEventsContainer')) {
			var allDayElm = document.getElementById('allDayEventsContainer');
			var allDayHeight = allDayElm.offsetHeight;
			
			newHeight = newHeight - allDayHeight;
		}
		//alert('h:' + newHeight + ' w:' + newWidth + ' cH:' + calContainerHeight);
		//set size of dayViewContainer
		var dayViewContainer = document.getElementById('dayViewContainer');
		dayViewContainer.style.height = newHeight + 'px';
		dayViewContainer.style.width = newWidth + 'px';
		dayViewContainer.style.display = 'block';
	}
	document.getElementById('calendarTitleHeader').innerHTML = header_str;
}


/*******************************************************************************
 *	This function is triggered when a layout change is requested.
 */
function changeLayout(layout) {
	//alert('changing layout to: ' + layout);
	blurCalendar();

	old_layout = calendar_layout;
	calendar_layout = layout;

	setTimeout('updateMiniCalSelection();',500);

	//update view of tabs to reflect the newly selected tab
	udpateTabLinks(old_layout,layout);

	//call printCalendarContent to refresh calendar with requested layout
	getCalendarContent();
}


/*******************************************************************************
 *	Changes the view for which tab is selected by updating css classes for the
 *	old and new tab.
 */
function udpateTabLinks(old_layout,new_layout) {
	var old_tab = document.getElementById('layout_' + old_layout);
	var new_tab = document.getElementById('layout_' + new_layout);

	old_tab.className = 'calendarLayoutLink';
	new_tab.className = 'calendarLayoutLinkSelected';
}


/*******************************************************************************
 *	Updates the small YUI calendar by selecting the necessary dates for the
 *	given layout.
 *	Ex. If the 'week' layout is selected, then we update the calendar to select
 *			every day of the week for the current day selected.
 */
function updateMiniCalSelection() {
	//disable this for now
	return;
	
	updating_mini_cal = true;
	//YAHOO.onesite.calendar.cal1.select('01/20/2007');
	//YAHOO.onesite.calendar.cal1.render();

	//clear any currently selected
	//YAHOO.onesite.calendar.cal1.clear();
	YAHOO.onesite.calendar.cal1.cfg.setProperty("selected", []);
	YAHOO.onesite.calendar.cal1.clearEvent.fire();

	if (calendar_layout == 'month') {
		var month = selected_date.getMonth() + 1;
		var year = selected_date.getFullYear();
		var month_end = YAHOO.widget.DateMath.findMonthEnd(selected_date).getDate();

		//select each day of the month
		var debug_str = '';
		for (var i = 1; i <= month_end; i++) {
			var date_str = month.toString() + '/' + i.toString() + '/' + year.toString();

			var cell = YAHOO.onesite.calendar.cal1.cells[i];
			var cellDate = YAHOO.onesite.calendar.cal1.cellDates[i];
			var dCellDate = YAHOO.onesite.calendar.cal1._toDate(cellDate);
			debug_str = debug_str.concat(cellDate + " => " + dCellDate + "\n");

			//YAHOO.onesite.calendar.cal1.renderCellStyleSelected(dCellDate,cell);
			YAHOO.onesite.calendar.cal1.select(date_str);
			//YAHOO.onesite.calendar.cal1.selectCell(i);

			debug_str = debug_str.concat(date_str + "\n");
		}
//alert(debug_str);
		
		var month = selected_date.getMonth();
		var year = selected_date.getFullYear();
		YAHOO.onesite.calendar.cal1.setMonth(month);
		YAHOO.onesite.calendar.cal1.setYear(year);
		YAHOO.onesite.calendar.cal1.render();
		
		//update calendar
		YAHOO.onesite.calendar.cal1.render();
//alert(selected_date);
	}
	else if (calendar_layout == 'day') {
		var month = selected_date.getMonth() + 1;
		var year = selected_date.getFullYear();
		var day = selected_date.getDate();
		
		var date_str = month.toString() + '/' + day.toString() + '/' + year.toString();
		
		//var cell = YAHOO.onesite.calendar.cal1.cells[day];
		//var cellDate = YAHOO.onesite.calendar.cal1.cellDates[day];
		//var dCellDate = YAHOO.onesite.calendar.cal1._toDate(cellDate);
		//alert('selecting:' + date_str);
		YAHOO.onesite.calendar.cal1.select(date_str);
		
		//update calendar
		var month = selected_date.getMonth();
		var year = selected_date.getFullYear();
		YAHOO.onesite.calendar.cal1.setMonth(month);
		YAHOO.onesite.calendar.cal1.setYear(year);
		YAHOO.onesite.calendar.cal1.render();
	}

	updating_mini_cal = false;
}


/*******************************************************************************
 *	Prints response info for a given Ajax response for debugging.
 */
function printResponse(o) {
	var div = document.createElement('div');
	div.id = 'response_status';
	div.style.width = '700px';
	div.style.background = '#000000';
	div.style.color = 'red';
	div.style.position = 'absolute';
	div.style.top = '150px';
	if(o.responseText !== undefined){
					div.innerHTML = "Transaction id: " + o.tId + '<br />';
					div.innerHTML += "HTTP status: " + o.status + '<br />';
					div.innerHTML += "Status code message: " + o.statusText + '<br />';
					div.innerHTML += "<li>HTTP headers: <ul>" + o.getAllResponseHeaders + "</ul></li><br />";
					div.innerHTML += "PHP response: " + o.responseText + '<br />';
					div.innerHTML += "Argument object: " + o.argument + '<br />';
	}
	document.body.appendChild(div);
}


/*******************************************************************************
 *	Displays an overlaying div next to the event that was selected. This div
 *	contains info about the event along with edit/delete options.
 */
function editDayEvent(eventId,etop,eleft) {
	blurCalendar();
	
	editMonthSwitch = false;

	//alert('editing event_id:' + eventId);
	var infoElm = document.getElementById('monthEventEdit');

	//figure out where to position the div
	infoElm.style.left = (eleft + 20) + 'px';
	infoElm.style.top = (etop + 11) + 'px';
	
	//add loading image to innerHTML
	infoElm.innerHTML = '<a href="javascript:closeEditMonthEvent()" id="closeEventInfoBox">X</a>'
					+ '<div style="margin:30px auto; text-align:center;"><img src="'
					+ loading_image_url + '" id="calendarInfoLoading" alt="loading..." /></div>'

	//show div
	infoElm.style.display = 'block';
	
	//determin which layout to show (admin or view)
	if (show_admin)
		var param_admin = 'admin';
	else
		var param_admin = 'view';

	//retrieve event info
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=get_event_info_box&cal_ids=' + calendar_ids_string
										+ '&ce_id=' + eventId
										+ '&timezone=' + timezone
										+ '&view=' + param_admin
										+ '&ms=' + new Date().getTime(),
				{
								success: handleEditMonthEvent,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	Displays an overlaying div next to the event that was selected. This div
 *	contains info about the event along with edit/delete options.
 */
function editMonthEvent(eventId,cellNum) {
	blurCalendar();

	//alert('editing event_id:' + eventId);
	if (cellNum != -1) {
		var infoElm = document.getElementById('monthEventEdit');
		editMonthSwitch = false;
		var closeCall = 'closeEditMonthEvent';
	}
	else {
		var infoElm = document.getElementById('dayEventEdit');
		editMonthSwitch = true;
		var closeCall = 'closeEditDayEvent';
	}

	//get event element
	var eventElm = document.getElementById('event' + eventId + '_' + cellNum);

	//figure out where to position the div
	var coordinates = getCoordinates(eventElm);

	//get coordinates and position div
	infoElm.style.display = 'block';
	infoElm.style.visibility = 'hidden';

	infoElm.style.left = (coordinates.x+20) + 'px';
	infoElm.style.top = (coordinates.y+11) + 'px';

	var parent_region = YAHOO.util.Dom.getRegion('calendarMainContainer');
	var elm_region = YAHOO.util.Dom.getRegion(infoElm);

	if ( elm_region.right > parent_region.right ) {
		infoElm.style.left = (coordinates.x -  (elm_region.right - parent_region.right)) + 'px';
	}

	//add loading image to innerHTML
	infoElm.innerHTML = '<a href="javascript:' + closeCall + '()" id="closeEventInfoBox">X</a>'
					+ '<div style="margin:30px auto; text-align:center;"><img src="'
					+ loading_image_url + '" id="calendarInfoLoading" alt="loading..." /></div>'

	  //show div
	infoElm.style.visibility = 'visible';
	
	//determin which layout to show (admin or view)
	if (show_admin)
		var param_admin = 'admin';
	else
		var param_admin = 'view';

	//retrieve event info
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=get_event_info_box&cal_ids=' + calendar_ids_string
										+ '&ce_id=' + eventId
										+ '&timezone=' + timezone
										+ '&view=' + param_admin
										+ '&ms=' + new Date().getTime(),
				{
								success: handleEditMonthEvent,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}
var editMonthSwitch;

/*******************************************************************************
 *	This is the function that handles the ajax response for editMonthEvent()
 *	Prints the event info to the popup div 'monthEventEdit'.
 */
function handleEditMonthEvent(req) {
	//printResponse(req);
	if (!editMonthSwitch) {
		var infoElm = document.getElementById('monthEventEdit');
		var closeCall = 'closeEditMonthEvent';
	}
	else {
		var infoElm = document.getElementById('dayEventEdit');
		var closeCall = 'closeEditDayEvent';
	}
	infoElm.innerHTML = '<a href="javascript:' + closeCall + '()" id="closeEventInfoBox">X</a>'
					+ req.responseText;
}


/*******************************************************************************
 *	Hides the overlaying div that is displayed using the editMonthEvent()
 *	function.
 */
function closeEditMonthEvent() {
	var infoElm = document.getElementById('monthEventEdit');
	infoElm.style.display = 'none';
}


/******************************************************************************
 *	Hides the overlaying div that is displayed using the editMonth/dayEvent()
 *	function.
 */
function closeEditDayEvent() {
		var infoElm = document.getElementById('dayEventEdit');
		infoElm.style.display = 'none';
}



/*******************************************************************************
 *	Get the x and y coordinates of the given element.
 */
function getCoordinates(obj) {
	var point = { x: 0, y: 0 };

	do {
	  point.x += obj.offsetLeft ;
	  point.y += obj.offsetTop;
	  obj = obj.offsetParent;
	} while (obj.id != 'calendarMainContainer')

	return point;
}


/*******************************************************************************
 *	Call this function to blur the screen elements when a link is clicked.
 */
function blurCalendar() {
	document.getElementById('calendarContainer').blur();
}


/*******************************************************************************
 *	This function handles the event that loads the event edit screen.
 */
function editEvent(eventId) {
	showCalendarLoading();

	//retrieve the edit screen
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=edit_event_screen&cal_ids=' + calendar_ids_string
										+ '&ce_id=' + eventId
										+ '&timezone=' + timezone
										+ '&user_id=' + user_id
										+ '&user_relation=' + user_relation
										+ '&ms=' + new Date().getTime(),
				{
								success: handleEditEvent,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This is the function that handles the ajax response for editEvent()
 *	Prints the edit event form to the screen.
 */
function handleEditEvent(req) {
	//printResponse(req);
	var calContainer = document.getElementById('calendarMain');
	calContainer.innerHTML = req.responseText;
	
	var month_array = get_local_months(lang_glob);
	var day_short = get_local_short_days(lang_glob);
	
	YAHOO.onesite.calendar.cal2 = new YAHOO.widget.Calendar("cal2","calendarBegin", { title:"Choose start date:", close:true } );
	YAHOO.onesite.calendar.cal2.cfg.setProperty("MONTHS_LONG", month_array); 
	YAHOO.onesite.calendar.cal2.cfg.setProperty("WEEKDAYS_SHORT", day_short);  
	YAHOO.onesite.calendar.cal2.render();

	//listener to show the 1-up Calendar when the button is clicked
	YAHOO.util.Event.addListener("beginDateSelect", "focus", YAHOO.onesite.calendar.cal2.show, YAHOO.onesite.calendar.cal2, true);

	//listener for when a date is selected
	YAHOO.onesite.calendar.cal2.selectEvent.subscribe(selectBeginDateEvent, YAHOO.onesite.calendar.cal2, true);


	YAHOO.onesite.calendar.cal3 = new YAHOO.widget.Calendar("cal3","calendarEnd", { title:"Choose end date:", close:true } );
	YAHOO.onesite.calendar.cal3.cfg.setProperty("MONTHS_LONG", month_array); 
	YAHOO.onesite.calendar.cal3.cfg.setProperty("WEEKDAYS_SHORT", day_short); 
	YAHOO.onesite.calendar.cal3.render();

	//listener to show the 1-up Calendar when the button is clicked
	YAHOO.util.Event.addListener("endDateSelect", "focus", YAHOO.onesite.calendar.cal3.show, YAHOO.onesite.calendar.cal3, true);

	//listener for when a date is selected
	YAHOO.onesite.calendar.cal3.selectEvent.subscribe(selectEndDateEvent, YAHOO.onesite.calendar.cal3, true);

	//put cursor to the title input
	document.getElementById('event_form_title').focus();
}


/*******************************************************************************
 *	This function handles the event that loads the view edit screen.
 */
function viewEvent(eventId) {
	showCalendarLoading();

	//retrieve the edit screen
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=view_event_screen&cal_ids=' + calendar_ids_string
										+ '&ce_id=' + eventId
										+ '&timezone=' + timezone
										+ '&ms=' + new Date().getTime(),
				{
								success: handleViewEvent,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This is the function that handles the ajax response for viewEvent()
 *	Prints the view event info to the screen.
 */
function handleViewEvent(req) {
	//printResponse(req);
	var calContainer = document.getElementById('calendarMain');
	calContainer.innerHTML = req.responseText;
}


/*******************************************************************************
 *	Event handler function for when a date is selected from the begin time
 *	calendar popup.
 */
function selectBeginDateEvent(type,args,obj) {
	var date1 = this._toDate(args[0][0]);
	//alert(date1);

	//close popup
	YAHOO.onesite.calendar.cal2.hide();

	//put date string in text field
	var month = date1.getMonth() + 1;
	var day = date1.getDate();
	var year = date1.getFullYear();

	document.getElementById('beginDateSelect').value = month + '/' + day + '/' + year;
	
	var cur_end_date = new Date(document.getElementById('endDateSelect').value);
	if (cur_end_date < date1) {
		document.getElementById('endDateSelect').value = month + '/' + day + '/' + year;
	}
}


/*******************************************************************************
 *	Event handler function for when a date is selected from the begin time
 *	calendar popup.
 */
function selectEndDateEvent(type,args,obj) {
	var date1 = this._toDate(args[0][0]);
	//alert(date1);

	//close popup
	YAHOO.onesite.calendar.cal3.hide();

	//put date string in text field
	var month = date1.getMonth() + 1;
	var day = date1.getDate();
	var year = date1.getFullYear();

	document.getElementById('endDateSelect').value = month + '/' + day + '/' + year;
	
	var cur_begin_date = new Date(document.getElementById('beginDateSelect').value);
	if (cur_begin_date > date1) {
		document.getElementById('beginDateSelect').value = month + '/' + day + '/' + year;
	}
}


/*******************************************************************************
 *	Toggles the create/edit event forms from all_day times to hourly times.
 */
function switchAllDay() {
	blurCalendar();

	var chkbox = document.getElementById('calendar_all_day');

	if (chkbox.checked == true) {
		//remove time input boxes
		var txt1 = document.getElementById('beginHour');
		txt1.style.display = 'none';

		var txt2 = document.getElementById('beginMinute');
		txt2.style.display = 'none';

		var txt1 = document.getElementById('endHour');
		txt1.style.display = 'none';

		var txt2 = document.getElementById('endMinute');
		txt2.style.display = 'none';
	}
	else {
		//add time input boxes
		var txt1 = document.getElementById('beginHour');
		txt1.style.display = 'inline';

		var txt2 = document.getElementById('beginMinute');
		txt2.style.display = 'inline';

		var txt1 = document.getElementById('endHour');
		txt1.style.display = 'inline';

		var txt2 = document.getElementById('endMinute');
		txt2.style.display = 'inline';
	}
}


/*******************************************************************************
 *	This function handles deleting an event.
 */
function deleteEvent(eventId,title) {
	var conf = confirm("Are you sure you want to delete this event: \n\n\"" + title + "\"");

	if (conf) {
		showCalendarLoading();

		var connectionObject = YAHOO.util.Connect.asyncRequest(
					'GET',
					ajax_url + '?a=delete_event&cal_ids=' + calendar_ids_string
											+ '&ce_id=' + eventId
											+ '&timezone=' + timezone
											+ '&user_id=' + user_id
											+ '&user_relation=' + user_relation
											+ '&ms=' + new Date().getTime(),
					{
									success: handleDeleteEvent,
									failure: reportError,
									timout: ajax_timeout
					}
		);
	}
}


/*******************************************************************************
 *	This function is called once the deleteEvent function's ajax request
 *	has returned. We assume the event has been deleted and refresh the
 *	calendar screen.
 */
function handleDeleteEvent(req) {
	//printResponse(req);
	var calContainer = document.getElementById('calendarMain');
	//calContainer.innerHTML = req.responseText;

	//call printCalendarContent to refresh calendar with requested layout
	getCalendarContent();
}


/*******************************************************************************
 *	Advances the main calendar to the next day, week or month (depending on
 *	layout)
 */
function calendarNext() {
	blurCalendar();

	if (calendar_layout == 'month') {
		selected_date = new Date(selected_date.getFullYear(),selected_date.getMonth() + 1,selected_date.getDate(),0,0,0);
		setSelectedDateString();

		//retrieve new calendar
		getCalendarContent();

		//update mini calendar
		setTimeout('updateMiniCalSelection();',500);
		
		//YAHOO.onesite.calendar.cal1.nextMonth();
	}
	else if (calendar_layout == 'day') {
		selected_date = new Date(selected_date.getFullYear(),selected_date.getMonth(),selected_date.getDate() + 1,0,0,0);
		setSelectedDateString();
		
		//retrieve new calendar
		getCalendarContent();

		//update mini calendar
		setTimeout('updateMiniCalSelection();',500);
	}
}


/*******************************************************************************
 *	Moves the main calendar to the previous day, week or month (depending on
 *	layout)
 */
function calendarPrev() {
	blurCalendar();

	if (calendar_layout == 'month') {
		selected_date = new Date(selected_date.getFullYear(),selected_date.getMonth() - 1,selected_date.getDate(),0,0,0);
		setSelectedDateString();

		//retrieve new calendar
		getCalendarContent();

		//update mini calendar
		setTimeout('updateMiniCalSelection();',500);
		
		//YAHOO.onesite.calendar.cal1.previousMonth();
	}
	else if (calendar_layout == 'day') {
		selected_date = new Date(selected_date.getFullYear(),selected_date.getMonth(),selected_date.getDate() - 1,0,0,0);
		setSelectedDateString();
		
		//retrieve new calendar
		getCalendarContent();
		
		//update mini calendar
		setTimeout('updateMiniCalSelection();',500);
	}
}


/*******************************************************************************
 *	Moves the main calendar to day,week,month that contains today.
 */
function calendarToday() {
	showCalendarLoading();
	//blurCalendar();

	if (calendar_layout == 'month') {
		selected_date = new Date();
		var month = selected_date.getMonth();
		var day = selected_date.getDate();
		var year = selected_date.getFullYear();
		setSelectedDateString();

		//retrieve new calendar
		getCalendarContent();

		//update mini calendar
		setTimeout('updateMiniCalSelection();',500);

		YAHOO.onesite.calendar.cal1.setYear(year);
		YAHOO.onesite.calendar.cal1.setMonth(month);
		YAHOO.onesite.calendar.cal1.render();
	}
	else if (calendar_layout == 'day') {
		selected_date = new Date();
		var month = selected_date.getMonth();
		var day = selected_date.getDate();
		var year = selected_date.getFullYear();
		setSelectedDateString();

		//retrieve new calendar
		getCalendarContent();

		//update mini calendar
		setTimeout('updateMiniCalSelection();',500);

		YAHOO.onesite.calendar.cal1.setYear(year);
		YAHOO.onesite.calendar.cal1.setMonth(month);
		YAHOO.onesite.calendar.cal1.render();
	}
}


/*******************************************************************************
 *	Displays the loading screen and image while waiting for an ajax request.
 */
function showCalendarLoading() {
	blurCalendar();

	var parentElm = document.getElementById('calendarMain');
	var coordinates = getCoordinates(parentElm);
	
	var tmp_height = parentElm.offsetHeight;
	var tmp_width = parentElm.offsetWidth;
	if (tmp_height < 200) {
		tmp_height = calendarMainHeight;
	}

	var loadingdiv = document.createElement("div");
	loadingdiv.style.background = 'white';
	loadingdiv.style.filter = 'alpha(opacity=50)';
	loadingdiv.style.opacity = '.5';
	loadingdiv.style.width = tmp_width + 'px';
	loadingdiv.style.height = tmp_height + 'px';
	loadingdiv.style.position = 'absolute';
	loadingdiv.style.top = coordinates.y + 'px';
	loadingdiv.style.left = coordinates.x + 'px';
	loadingdiv.style.verticalAlign = 'middle';
	loadingdiv.style.textAlign = 'center';
	loadingdiv.innerHTML = '<img src="' + loading_image_url + '" '
												+ 'style="position:relative; top:150px;" />';

	//add to docpane
	document.getElementById('calendarMain').appendChild(loadingdiv);
}


/*******************************************************************************
 *	This function is called when a user submits their changes to an event
 *	from the edit event form. Makes ajax request to update event.
 */
function updateEventInfo(eventId) {
	//exit if invalid data
	if (!verify_event_form())
		return false;

	showCalendarLoading();

	//format info
	var chkbox = document.getElementById('calendar_all_day');
	if (chkbox.checked == true) {
		var all_day = 1;
	}
	else {
		var all_day = 0;
	}

	var begin_string = document.editEventForm.begin.value;
	var begin_date = new Date(begin_string);
	var end_string = document.editEventForm.end.value;
	var end_date = new Date(end_string);
	if (all_day == 0) {
		begin_date.setHours(document.editEventForm.beginHour.value-0);
		begin_date.setMinutes(document.editEventForm.beginMinute.value-0);
		end_date.setHours(document.editEventForm.endHour.value-0);
		end_date.setMinutes(document.editEventForm.endMinute.value-0);
	}

	//retrieve the edit screen
	YAHOO.util.Connect.setForm(document.editEventForm);
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'POST',
				ajax_url + '?a=update_event_info&cal_ids=' + calendar_ids_string
										+ '&ce_id=' + eventId
										+ '&all_day=' + all_day
										+ '&timezone=' + timezone
										+ '&user_id=' + user_id
										+ '&user_relation=' + user_relation
										+ '&ms=' + new Date().getTime(),
				{
								success: handleUpdateEventInfo,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This function is called when the ajax request submitted in updateEventInfo
 *	has finished and returned. We redirect user to the main calendar screen.
 */
function handleUpdateEventInfo(req) {
	//printResponse(req);
	var calContainer = document.getElementById('calendarMain');
	//calContainer.innerHTML = req.responseText;
	calContainer.innerHTML = '';

	//call printCalendarContent to refresh calendar with requested layout
	getCalendarContent();
}


/*******************************************************************************
 *	This function is called when a user selectes that they want to create
 *	a new event. Loads the create event form through an ajax request.
 */
function createEvent(year,month,day) {
	//alert(year + ' ' + month + ' ' + day);
	showCalendarLoading();

	var selected_calendar = calendar_ids[0];
	
	//set default date to selected date if passed 0's
	if (year == 0 || day == 0) {
		year = selected_date.getFullYear();
		day = selected_date.getDate();
		month = selected_date.getMonth() + 1;
	}

	//retrieve the edit screen
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'GET',
				ajax_url + '?a=create_event&cal_ids=' + calendar_ids_string
										+ '&year=' + year
										+ '&month=' + month
										+ '&day=' + day
										+ '&timezone=' + timezone
										+ '&selected_calendar_id=' + selected_calendar
										+ '&user_id=' + user_id
										+ '&user_relation=' + user_relation
										+ '&ms=' + new Date().getTime(),
				{
								success: handleCreateEvent,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This function is called when the ajax request submitted in createEvent
 *	has finished and returned. We output the create event form to the screen.
 */
function handleCreateEvent(req) {
	var calContainer = document.getElementById('calendarMain');
	calContainer.innerHTML = req.responseText;
	
	var month_array = get_local_months(lang_glob);
	var day_short = get_local_short_days(lang_glob);

	YAHOO.onesite.calendar.cal2 = new YAHOO.widget.Calendar("cal2","calendarBegin", { title:"Choose start date:", close:true } );
	YAHOO.onesite.calendar.cal2.cfg.setProperty("MONTHS_LONG", month_array); 
	YAHOO.onesite.calendar.cal2.cfg.setProperty("WEEKDAYS_SHORT", day_short); 
	YAHOO.onesite.calendar.cal2.render();

	//listener to show the 1-up Calendar when the button is clicked
	YAHOO.util.Event.addListener("beginDateSelect", "focus", YAHOO.onesite.calendar.cal2.show, YAHOO.onesite.calendar.cal2, true);

	//listener for when a date is selected
	YAHOO.onesite.calendar.cal2.selectEvent.subscribe(selectBeginDateEvent, YAHOO.onesite.calendar.cal2, true);


	YAHOO.onesite.calendar.cal3 = new YAHOO.widget.Calendar("cal3","calendarEnd", { title:"Choose end date:", close:true } );
	YAHOO.onesite.calendar.cal3.cfg.setProperty("MONTHS_LONG", month_array); 
	YAHOO.onesite.calendar.cal3.cfg.setProperty("WEEKDAYS_SHORT", day_short); 
	YAHOO.onesite.calendar.cal3.render();

	//listener to show the 1-up Calendar when the button is clicked
	YAHOO.util.Event.addListener("endDateSelect", "focus", YAHOO.onesite.calendar.cal3.show, YAHOO.onesite.calendar.cal3, true);

	//listener for when a date is selected
	YAHOO.onesite.calendar.cal3.selectEvent.subscribe(selectEndDateEvent, YAHOO.onesite.calendar.cal3, true);

	//put cursor to the title input
	document.getElementById('event_form_title').focus();
}


/*******************************************************************************
 *	This function submits a form to create a new calendar event in the db.
 */
function createEventSubmit() {
	//exit if invalid data
	if (!verify_event_form())
		return false;

	showCalendarLoading();

	//format info
	var chkbox = document.getElementById('calendar_all_day');
	if (chkbox.checked == true) {
		var all_day = 1;
	}
	else {
		var all_day = 0;
	}

	var begin_string = document.createEventForm.begin.value;
	var begin_date = new Date(begin_string);
	var end_string = document.createEventForm.end.value;
	var end_date = new Date(end_string);
	if (all_day == 0) {
		begin_date.setHours(document.createEventForm.beginHour.value-0);
		begin_date.setMinutes(document.createEventForm.beginMinute.value-0);
		end_date.setHours(document.createEventForm.endHour.value-0);
		end_date.setMinutes(document.createEventForm.endMinute.value-0);
	}

	var selected_calendar = calendar_ids[0];

	//retrieve the edit screen
	YAHOO.util.Connect.setForm(document.createEventForm);
	var connectionObject = YAHOO.util.Connect.asyncRequest(
				'POST',
				ajax_url + '?a=create_event_submit&cal_ids=' + calendar_ids_string
										+ '&selected_calendar_id=' + selected_calendar
										+ '&all_day=' + all_day
										+ '&timezone=' + timezone
										+ '&user_id=' + user_id
										+ '&node_id=' + node_id
										+ '&user_relation=' + user_relation
										+ '&ms=' + new Date().getTime(),
				{
								success: handleCreateEventSubmit,
								failure: reportError,
								timout: ajax_timeout
				}
	);
}


/*******************************************************************************
 *	This function is called when the ajax request submitted in createEventSubmit
 *	has finished and returned. We redirect user to the main calendar screen.
 */
function handleCreateEventSubmit(req) {
	//printResponse(req);
	var calContainer = document.getElementById('calendarMain');
	//calContainer.innerHTML = req.responseText;
	calContainer.innerHTML = '';
	
	//try to get event type
	var redirect = req.responseText;
	
	//if a personal event, reload main calendar
	if (redirect.length <= 20) {
		//call printCalendarContent to refresh calendar with requested layout
		getCalendarContent();
	}
	//else redirect to gathering management page
	else {
		//redirect...
		window.location = redirect;
	}
}


/*******************************************************************************
 *	This function does input error checking for both the edit event form and
 *	the create event form. Verifies that all required info has been entered.
 *	Also verifies that the end date is after the begin date.
 */
function verify_event_form() {
	var form_error = '';

	//verify title
	if (document.getElementById('event_form_title').value.length < 1)
		form_error = form_error.concat("Invalid title \n");

	//verify end is after begin
	var begin_date = new Date(document.getElementById('beginDateSelect').value);
	var end_date = new Date(document.getElementById('endDateSelect').value);

	var chkbox = document.getElementById('calendar_all_day');
	if (chkbox.checked == true) {
		var all_day = 1;
	}
	else {
		var all_day = 0;
	}

	if (all_day == 0) {
		begin_date.setHours(document.getElementById('beginHour').value-0);
		begin_date.setMinutes(document.getElementById('beginMinute').value-0);
		end_date.setHours(document.getElementById('endHour').value-0);
		end_date.setMinutes(document.getElementById('endMinute').value-0);
	}

	if (end_date < begin_date)
		form_error = form_error.concat("Please select an end date that is after the begin date \n");

	//print error(s) to screen
	if (form_error.length > 0) {
		alert(form_error);
		return false;
	}
	else {
		return true;
	}
}


/*******************************************************************************
 *	Shows the quicknav calendar.
 */
function showNav() {
	blurCalendar();
	YAHOO.onesite.calendar.cal1.show();
}


/*******************************************************************************
 *	Hide the quicknav calendar.
 */
function hideNav() {
	blurCalendar();
	YAHOO.onesite.calendar.cal1.hide();
}

