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

function init() {
google.gdata.client.init(function (str) {}); 
  // loadCalendarByAddress('developer-calendar@google.com');
  loadCalendarByAddress('qsa583pqp22qa1plkgojd3vdvk@group.calendar.google.com');
}

function emptyError() {
	
}

/**
 * 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(true);
  query.setSingleEvents(true);
	if (full_listing == false) {
		query.setMaxResults(3);
	} else {
		query.setMaxResults(20);
	}

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

/**
 * 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) {
  document.getElementById('jsSourceFinal').setAttribute('style', 
      'display:none');
  if (e instanceof Error) {
    /* 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());
  }
}

/**
 * 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();
// alert entries;
	var eventDiv = document.getElementById('events');
	if (eventDiv.childNodes.length > 0) {
		eventDiv.removeChild(eventDiv.childNodes[0]);
	}
	
	// if (full_listing == false) {
		var h3 = document.createElement('h3');
		h3.appendChild(document.createTextNode("Forthcoming Events"));
	// }
	
  /* create a new unordered list */
	var ul = document.createElement('ul');
  /* 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;
	for (var i = 0; i < len; i++) {
		var entry = entries[i];
		var title = entry.getTitle().getText();
		var description = entry.getContent().getText();
		var location = entry.getLocations()[0].getValueString();
		var startDateTime = null;
		var startJSDate = null;
		var times = entry.getTimes();
		if (times.length > 0) {
			startDateTime = times[0].getStartTime();
			startJSDate = startDateTime.getDate();
		}
		var entryLinkHref = null;
		if (entry.getHtmlLink() != null) {
			entryLinkHref = entry.getHtmlLink().getHref();
		}
		
		// var dateString = startJSDate.getDate() + "/" + (startJSDate.getMonth() + 1) + "/" + (startJSDate.getYear());
		
		var month = (startJSDate.getMonth() + 1);
		var smart_month = new Array();
		smart_month[1] = "January";
		smart_month[2] = "February";
		smart_month[3] = "March";
		smart_month[4] = "April";
		smart_month[5] = "May";
		smart_month[6] = "June";
		smart_month[7] = "July";
		smart_month[8] = "August";
		smart_month[9] = "September";
		smart_month[10] = "October";
		smart_month[11] = "November";
		smart_month[12] = "December";
		var dateYear = startJSDate.getYear() - 100;
		dateYear = dateYear + 2000;
		var dateString = startJSDate.getDate() + " " + smart_month[month] + " " + dateYear;
		
		if (!startDateTime.isDateOnly()) {
			dateString += " @ " + startJSDate.getHours() + ":" + 
			padNumber(startJSDate.getMinutes());
		}
		var li = document.createElement('li');
		
		datestyle = document.createElement('small');
		
		// Nicely format the date.
		
		
		datestyle.appendChild(document.createTextNode(dateString + " "));
		li.appendChild(datestyle);

		titlestyle = document.createElement('strong');
		if (location != null) {
			entryLink = document.createElement('a');
			
			
			if (full_listing == true) {
				entryLink.setAttribute('href', "http://maps.google.co.uk/maps?q=" + location);
				entryLink.setAttribute('title', "View location on Google Maps (opens a new window)");
				entryLink.setAttribute('name', "event" + i);
				entryLink.setAttribute('target', "_blank");
			} else {
				entryLink.setAttribute('href', "events/#" + i);
			}
			
		
			entryLink.appendChild(document.createTextNode(title));
			titlestyle.appendChild(entryLink);
		} else {
			titlestyle.appendChild(document.createTextNode(title));
		}
		li.appendChild(titlestyle);
		
		if (full_listing == true) {
			li.appendChild(document.createTextNode(description));	    
		}
		
		ul.appendChild(li);
	}
	
	if (full_listing == false) {
		var seemore = document.createElement('p');
		var seemorelink = document.createElement('a');
		seemorelink.setAttribute('href', "events/");
		seemorelink.setAttribute('class', "txtButton");
		seemorelink.appendChild(document.createTextNode("See our full calendar"));
		seemore.appendChild(seemorelink);
	}
	if (full_listing == false) {
		eventDiv.appendChild(h3);
	}
	eventDiv.appendChild(ul);
	if (full_listing == false) {
		eventDiv.appendChild(seemore);
	}
}

google.setOnLoadCallback(init);