var calendarUrl = 'http://www.google.com/calendar/feeds/gmocalendar@gmail.com/public/full';
var chatType = (get_param('pagename') == 'gmo__action__open_chat') ? 'open chat' : 'virtual bible study';


google.load("gdata", "2.x");
$(document).ready(function() {
	google.gdata.client.init(handleGDError);
	var service = new google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
	var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
	query.setOrderBy('starttime');
	query.setSortOrder('ascending');
	query.setFutureEvents(true);
	query.setSingleEvents(true);
	query.setMaxResults(50);
	service.getEventsFeed(query, listEvents, handleGDError);
});

// Callback for errors
function handleGDError(e) {
	$('#jsSourceFinal').hide();
	if (e instanceof Error) {
		console.log('Error at line ' + e.lineNumber + 'in ' + e.fileName + '\nMessage: ' + e.message);
		if (e.cause)
			console.log('Root cause: HTTP error ' + e.cause.status + ' with status text of: ' + e.cause.statusText);
	}
	else console.log(e.toString());
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents(feedRoot) {
	var monthArray = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	var totalShown = 0;
	var html = '';
	var chatCurrentlyOpen = false;
	
	// Loop through event feed, filter out open chat / virtual bible studies
	var entries = feedRoot.feed.getEntries();
	for (var i = 0; (totalShown < 5 && i < entries.length); i++) {
		var entry = entries[i];
		var title = entry.getTitle().getText().toLowerCase();
		if (title == chatType) {
			var times = entry.getTimes();
			if (times.length > 0) {
				totalShown++;
				var startDateTime = times[0].getStartTime();
				var startJSDate = startDateTime.getDate();
				var endJSDate = times[0].getEndTime().getDate();
				
				var dateString = monthArray[startJSDate.getMonth()] + ' ' + startJSDate.getDate();
				if (!startDateTime.isDateOnly())
					dateString += ' @ ' + readableDate(startJSDate);
				
				// Check if chat is currently going on
				var d = new Date();
				if (d >= startJSDate && d < endJSDate) {
					var summary = entry.getContent().getText();

					// Chat currently open
					var roomType = (chatType == 'open chat') ? 'OpenChat' : 'Bible_Study' + parseInt(summary);
					html += '<li class="current_chat_open"><a href="#" onclick="roomSwitch(\'' + roomType + '\')">' + dateString + ' - This chat session is currently open! Scroll down below to enter this chat room.</a></li>';
					
					// Open first available chat
					if (!chatCurrentlyOpen) roomSwitch(roomType);
					chatCurrentlyOpen = true;
				}
				// Chat not open
				else
					html += '<li>' + dateString + '</li>';
			}
		}
	}
	if (totalShown == 0)
		html = '<li>No Chats Scheduled</li>';
	$('#chat_schedule_container').html('<ul>' + html + '</ul>');
}
function readableDate(d) {
	var hours = (d.getHours() == 0) ? 12 : (d.getHours() > 12) ? (d.getHours() - 12) : d.getHours();
	var meridian = (d.getHours() > 12) ? 'pm' : 'am';
	return (hours + ':' + padNumber(d.getMinutes()) + ' ' + meridian);
}
function padNumber(n) { return (n > 9) ? n : ("0" + n); }
function roomSwitch(room) {
	var html = '<APPLET CODEBASE="http://host7.parachat.com/pchat/applet" ARCHIVE="papplet.jar" CODE="pclient.main.ChatClient.class" width="726" height="522" style="margin:-13px 0 0 -18px;">';
	html += '<PARAM NAME="cabbase" VALUE="papplet.cab">';
	html += '<PARAM NAME="Net.Site" VALUE="8582">';
	html += '<param name="Col.MainBg" value="dbdbce">';
	html += '<PARAM NAME="Net.Room" VALUE="' + room + '">';
	html += 'Sorry, your browser is not Java enabled, please visit <a href="http://www.parachat.com/faq/java.html">our Java support pages</a>';
	html += '</APPLET>';

//	$('.applet_selector').empty().append(html);
	$('.applet_selector').html(html);
	return false;
}