/* RFB - www.tridig.com - created 03.21.2008 */
/* RFB - www.tridig.com - last modified 09.08.2008 */

/* Loads the Google data JavaScript client library */
google.load("gdata", "1");

function init() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */  
function loadCalendar(calendarUrl) {
  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(10);

  service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) {
	var ignoreError = false;

	if (e instanceof Error) {
		// Ignore 'unsupported browser' if the user is running Safari; Google will
		// tell us that the browser is unsupported, but then everything seems to
		// work fine anyway.
		if(e.message.indexOf('Unsupported browser') == 0) {
			if((typeof navigator != 'undefined') && (typeof navigator.userAgent != 'undefined')) {
				if(navigator.userAgent.indexOf('Safari') != -1) {
					ignoreError = true;
				}
			}
		}

		if(!ignoreError) {
			/* alert with the error line number, file and message */
			alert('Error at line ' + e.lineNumber + ' in ' + e.fileName + '\n' + 'Message: ' + e.message);
			/* if available, output HTTP error code and status text */
			if (e.cause) {
				var status = e.cause.status;
				var statusText = e.cause.statusText;
				alert('Root cause: HTTP error ' + status + ' with status text of: ' + statusText);
			}
		}
	} else {
		alert(e.toString());
	}

	if(!ignoreError)
		document.getElementById('nextUpcomingEvent').innerHTML = 'See events calendar';
}

/**
 * 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 entries = feedRoot.feed.getEntries();
	
	var anchorText = 'No upcoming event available';
	if(entries.length > 0) {
		var entry = entries[0];
		var title = entry.getTitle().getText();
	    var startDateTime = null;
	    var startJSDate = null;
	    var times = entry.getTimes();
	    if (times.length > 0) {
	      startDateTime = times[0].getStartTime();
	      startJSDate = startDateTime.getDate();
	    }

	    var dateString = '';
	 	if(startJSDate != null)
			dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();

		if(dateString.length > 0)
			anchorText = dateString + ' - ' + title;
		else
			anchorText = title;
	}
	
	var anchor = document.getElementById("nextUpcomingEvent");
	if(!anchor.innerHTML.length) {	// Don't write to it if the error handler has already written a message
		var anchorTextNode = document.createTextNode(anchorText);
		anchor.appendChild(anchorTextNode);
	}
}

google.setOnLoadCallback(init);
