// JavaScript Document

/* Loads the Google data JavaScript client library */
google.load("gdata", "1");

/**
 *  callback function for google loaded event
 */
function init() {
   // init the Google data JS client library with an error handler
   google.gdata.client.init(handleGDError);
   
   writeNextEvent();
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * 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) {
  // not sure what this was for:  document.getElementById('jsSourceFinal').setAttribute('style', display:none');

   /**
     * Disable for now because it google "unsupported browser" for Safari 3.x and Opera
	 * every time we're called
	 *
   if (e instanceof Error) {
    alert('Error at line ' + e.lineNumber +
          ' in ' + e.fileName + '\n' +
          'Message: ' + e.message);
    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());
  }
  */
}

function writeNextEvent(){
   writeNextEventByAddress('ntfu5orfopqufnhvvs1i2ns5b4%40group.calendar.google.com');
}

function writeNextEventByAddress(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  queryNextEvent(calendarUrl);
}

/** 
  *  Creates the query and initiates the calendar feed
  */
function queryNextEvent(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(1);

  service.getEventsFeed(query, processFeed, handleGDError);
  
}

/**
  * Callback to process the calendar feed.  Writes the next event text
  * to a span with the id "nextevent".
  */
function processFeed(feedRoot) {
   var entries = feedRoot.feed.getEntries();
   
   // write the event text to element with id "nextevent"
   var nextEventSpan = document.getElementById("nextevent");
   if (nextEventSpan == null) return;
   
   var txtElement = document.createElement("p");
   if (entries.length > 0)
   {
      var eventEntry = entries[0];
	  // wrap the entry text in a hyperlink pointing to the full calendar page
	  var entryLink = document.createElement("a");
      entryLink.setAttribute("href", "../calendar.htm");
	  formatNextEvent(eventEntry, entryLink);
      
      txtElement.appendChild( entryLink );
   }

  nextEventSpan.appendChild(txtElement);
}

/**
  * Appends the given element with a text node describing the next event
  * domElement      the event to format
  * htElement       the DOM element to append the child to
  */
function formatNextEvent(eventEntry, domElement)
{
   domElement.appendChild(document.createTextNode(eventEntry.getTitle().getText()));
   domElement.appendChild(document.createElement("br"));
   domElement.appendChild(document.createTextNode(formatDate(eventEntry)));
   domElement.appendChild(document.createElement("br"));
   domElement.appendChild(document.createTextNode(formatLocation(eventEntry)));
}

/**
  * Returns a string formatted with the  the start and end date for the event.
  */
function formatDate(eventEntry)
{
	var dateString = "";

	var times = eventEntry.getTimes();
	if (times.length > 0) {
		var startDateTime = times[0].getStartTime();
		var startJSDate = startDateTime.getDate();
		dateString = makeDateString(startJSDate, true, !startDateTime.isDateOnly());

		var endDateTime = times[0].getEndTime();
		var endJSDate = endDateTime.getDate();
		var differentEndDay = 
		   (endJSDate.getDate() != startJSDate.getDate() 
            || endJSDate.getMonth() != startJSDate.getMonth());
		var endDateString = makeDateString(endJSDate, differentEndDay, !endDateTime.isDateOnly());
		if (endDateString != null) {
			dateString += " - " + endDateString;
		}
	}
	
	return dateString;
}

/** 
  * Formats a date string, optionally including date and/or time.
  * Returns a formatted string or null if no date or time.
  */
function makeDateString(jsDate, includeDate, includeTime)
{
    var str = null;
	if (includeDate) {
		str = formatMonthDay(jsDate);
	}
	if (includeTime) {
		if (str == null) 
		   str = "";
		else 
		   str += " ";
		str += formatTimeAmPm(jsDate);
	}
	
	return str;
}

/**
  * format date with 3 letter month abbreviation and day
  */
 function formatMonthDay(jsDate)
 {
	 var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	 return months[jsDate.getMonth()] + " " + jsDate.getDate();
 }
 
/**
  * formats time string with AM/PM
  */
 function formatTimeAmPm(jsDate)
 {
	var hours = jsDate.getHours();
	var amPmStr;
	if (hours > 12)
	{
		hours -= 12;
		amPmStr = "pm";
	}
	else
	{
		amPmStr = "am";
	}
 	
	return hours + ":" + padNumber(jsDate.getMinutes()) + amPmStr;

 }
 
/**
  * Returns a string with the event location
  */
function formatLocation(eventEntry)
{
   var str = "";
   var locations = eventEntry.getLocations();
   if (locations.length > 0)
   {
      if (locations[0].getValueString() != undefined)
	     str = locations[0].getValueString();
   }
   
   return str;
}

/**
  * Call init when google library finishes loading
  */
google.setOnLoadCallback(init);