
/* Copyright (c) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/* Loads the Google data JavaScript client library */
google.load("gdata", "1.x");
 
function init() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
  loadCalendarByAddress('voyagervikings@gmail.com');
}
 
/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 * 
 * @param {int} num is the number to add a leading zero, if less than 10
 */
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);
  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) {
  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 now = new Date();
  var previousDate = now - 1;
  var prevFlag = false;
  
  var entries = feedRoot.feed.getEntries();
  var eventDiv = document.getElementById('googleevents');
  if (eventDiv.childNodes.length > 0) {
    eventDiv.removeChild(eventDiv.childNodes[0]);
  }
  
  /* create a new unordered list */
  var ul = document.createElement('ul');
  ul.setAttribute('class', 'upcomingevents2');
  ul.setAttribute('className', 'upcomingevents2');
  /* 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 startDateTime = null;
    var startJSDate = null;
	//var description = entry.getDescription().getText();
	var description = ' ' + entry.getContent().getText();




    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 = myDate(startJSDate);
	
    if (dateString != previousDate) {
      if (prevFlag == true) {
		  li.appendChild(ul2);
		  ul.appendChild(li);		   
	  }
	  
	  prevFlag = true;
	  previousDate = dateString;
	  var li = document.createElement('li');
      li.appendChild(document.createTextNode(dateString));
	  var ul2 = document.createElement('ul');
	}

    var li2 = 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', entryLinkHref);
	  entryLink.setAttribute('target','blank');
      entryLink.appendChild(document.createTextNode(title));
      li2.appendChild(entryLink);
      li2.appendChild(document.createTextNode(description));
    } else {
     // li2.appendChild(document.createTextNode(title + ' - ' + dateString));
    }	    
 
    if (prevFlag == true) {
		li.appendChild(ul2);
		ul.appendChild(li);		   
	}
	  
	/* append the list item onto the unordered list */
    ul2.appendChild(li2);
  }
  eventDiv.appendChild(ul);
}

function myDate(date)
{
	var day_names = new Array ( );
	day_names[day_names.length] = "Sun";
	day_names[day_names.length] = "Mon";
	day_names[day_names.length] = "Tue";
	day_names[day_names.length] = "Wed";
	day_names[day_names.length] = "Thu";
	day_names[day_names.length] = "Fri";
	day_names[day_names.length] = "Sat";

	var month_names = new Array ( );
	month_names[month_names.length] = "Jan";
	month_names[month_names.length] = "Feb";
	month_names[month_names.length] = "Mar";
	month_names[month_names.length] = "Apr";
	month_names[month_names.length] = "May";
	month_names[month_names.length] = "Jun";
	month_names[month_names.length] = "Jul";
	month_names[month_names.length] = "Aug";
	month_names[month_names.length] = "Sep";
	month_names[month_names.length] = "Oct";
	month_names[month_names.length] = "Nov";
	month_names[month_names.length] = "Dec";

	var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getYear();
			
		var rString = day_names[D] + ' ' + month_names[m] + ' ' + d.toString();
	//	var rString = day_names[D] + ' ' + month_names[m] + ' ' + d.toString() + ' ' + y.toString();
		
		return rString;		
}

google.setOnLoadCallback(init);
