var feedAddr = "http://www.google.com/calendar/feeds/0ueoh7ipigtv29obl1fgascmlo%40group.calendar.google.com/public/full";

/* 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);
  // load the code.google.com developer calendar
  loadDeveloperCalendar();
}

/**
 * Loads the Google Developers Event Calendar
 */
function loadDeveloperCalendar() {
  loadCalendar( feedAddr );
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */ 
function loadCalendarByAddress(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  loadCalendar(calendarUrl);
}

/**
 * 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(false);
  query.setSingleEvents(true);
  query.setMaxResults(5);

  var today = new Date();
  var twoDaysAhead = new Date( today.getFullYear(), today.getMonth(), today.getDate() + 5 );

  query.setMinimumStartTime( new google.gdata.DateTime( today ) );
  query.setMaximumStartTime( new google.gdata.DateTime( twoDaysAhead ) );

  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) {
  // fail silently
}

/**
 * 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 eventDiv = document.getElementById('events');
  if (eventDiv.childNodes.length > 0) {
    eventDiv.removeChild(eventDiv.childNodes[0]);
  }	  
  /* create a new unordered list */
  var ul = document.createElement('ul');
  var titleLi = document.createElement('li');
  titleLi.innerHTML = "<strong>Coming up:</strong>";
  ul.appendChild( titleLi );
  /* set the calendarTitle div with the name of the calendar */
 // document.getElementById('calendarTitle').innerHTML = "Calendar: " + feedRoot.feed.title.$t;
  /* loop through each event in the feed */
  var len = entries.length;
  var today = new Date();
  for (var i = 0; i < len; i++) {
    var entry = entries[i];
    var title = entry.getTitle().getText();
   	var locations = entry.getLocations();
   	var where = '';
   	if( locations.length > 0 )
   		where = locations[ 0 ].getValueString();
    
    var startDateTime = null;
    var startJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
    //if( startJSDate == null ) continue;
    var entryLinkHref = null;
    if (entry.getHtmlLink() != null) {
      entryLinkHref = entry.getHtmlLink().getHref();
    }
    var sday = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][ startJSDate.getDay() ]; 
    var sd = String( startJSDate.getDate() );
    var sm = String( startJSDate.getMonth() + 1);
    while( sd.length < 2 ) sd = '0' + sd;
    while( sm.length < 2 ) sm = '0' + sm;
    var dateString = sday + ' ' + sd + '/' + sm;
    
    //check today
    
    if( today.getFullYear() == startJSDate.getFullYear() && today.getMonth() == startJSDate.getMonth() && today.getDate() == startJSDate.getDate() )
    {
    	dateString = 'Today';
    }else if( today.getFullYear() == startJSDate.getFullYear() && today.getMonth() == startJSDate.getMonth() && (today.getDate()+1) == startJSDate.getDate() )
    {
    	dateString = 'Tomorrow';
    }else
    {
    
    }
        
    var timeString = '';
    if (!startDateTime.isDateOnly()) {
      timeString = startJSDate.getHours() + ":" + 
          padNumber(startJSDate.getMinutes());
    }
    var li = document.createElement('li');

    /* if we have a link to the event, create an 'a' element */
    if (entryLinkHref != null) {
      entryLink = document.createElement('a');
      entryLink.setAttribute('href', 'http://www.londonbikepololeague.com/fixtures/');
      entryLink.appendChild(document.createTextNode(title));
      
      li.appendChild( document.createTextNode( dateString + ': ' ) );
      li.appendChild(entryLink);
     
      if( where != '' || timeString != '' )
      {
        var sfx = ' - ';
      
      	if( where != '' )
     		sfx += where;
     	
		if( timeString != '' )
      		sfx += ' ' + timeString;
      		
      	li.appendChild(document.createTextNode( sfx ));
     	 
      }
      /*
      li.appendChild(entryLink);
      if( where != '' )
     	 li.appendChild(document.createTextNode(' - ' + where + ' - ' + dateString));
      else
      	 li.appendChild(document.createTextNode(' - ' + dateString));
      } else {
      li.appendChild(document.createTextNode(title + ' - ' + dateString));
      */
    }	    

    /* append the list item onto the unordered list */
    ul.appendChild(li);
  }
  eventDiv.appendChild(ul);
}

google.setOnLoadCallback(init);
