/* Functions for Retrieving Events from Google Calendar */

/* 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);
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return '0' + num;
  }
  return num;
}

function mapDay(day_num) {
	var dayMap = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
	return dayMap[day_num];
}

function mapMonth(day_num) {
	var dayMonth = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	return dayMonth[day_num];
}

function extractTime(date) {
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var time = '';
	var ampm = 'am';

	// DLC fix (11/22/11)
	// Library staff enter 11:59pm for closing dates that are 
	// supposed to represent 12:00am
	if (hours == 23 && minutes == 59) {
		minutes = 0;
		hours = 0;
	}
	// end DLC fix
	
	if (minutes < 10){
		minutes = '0' + minutes;
	}
	
	if (hours == 0){
		hours = 12;
	}
	else if(hours > 11){
		ampm = 'pm';
		if (hours != 12) {
			hours -= 12;
		}
	} 
	
	if (minutes == '00') {
		time = hours + ampm;
	}
	else {
		time = hours + ':' + minutes + ampm;
	}
	return time;
}

function loadCalendar(calendarAddress, firstDay, lastDay) {

  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';

  var service = new 
      google.gdata.calendar.CalendarService('gcal-loader');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setSingleEvents(true);
  
  // Set the calendar timezone, defaulting to America/New_York
  //var timeZone = new google.gdata.calendar.TimeZoneProperty();
  //timeZone.setValue('America/New_York');
  //query.setTimeZone(timeZone);

  firstDay.setHours(0);
  firstDay.setMinutes(0);
  firstDay.setSeconds(0); 

  /* If we have an end date, retrieve all events within given range */
  if (lastDay != null) {
	  lastDay.setHours(23);
	  lastDay.setMinutes(59);
	  lastDay.setSeconds(59); 
  /* If no end date, we're retrieving today's events only. 
  *  Set end time to tomorrow at 0:0:0 because All Day Events end after today at 23:59:59 *  and before tomorrow at 0:0:0. */
  } else {
    var lastDay = new Date();
  	lastDay.add(1).days();
  	lastDay.setHours(0);
  	lastDay.setMinutes(0);
  	lastDay.setSeconds(0); 
  }
   
  var gMinDate = new google.gdata.DateTime(firstDay);
  var gMaxDate = new google.gdata.DateTime(lastDay);
 
  query.setMinimumStartTime(gMinDate);
  query.setMaximumStartTime(gMaxDate);
  
  query.setRecurrenceExpansionEnd(gMaxDate);
  
  service.getEventsFeed(query, listEvents, handleGDError);
}

/* Extracts hours - Called by listEvents() */


/**
 * 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());
  }
}

google.setOnLoadCallback(init);
