var OCalendar = Class.create(
{	
	container:null,
	feed:null,
	initialize:function(container, userId, options)
	{
		this.options = options || {};
		
		//don't load the calendar if we don't have any place to put it
		if(container)
		{
			this.container = container;			
			this.loadCalendar(userId);
		}
	},
	//load the calendar
	loadCalendar:function(userId)
	{
		var uri = 'https://www.google.com/calendar/feeds/'+userId+'/public/full';
		var query = new google.gdata.calendar.CalendarEventQuery(uri);
		query.setParam('futureevents',true);
		query.setParam('orderby','starttime');
		query.setParam('sortorder','ascending');
		query.setParam('max-results',10);
		
		//?futureevents=true&orderby=starttime&sortorder=ascending&max-results=8';
		
		var service = new google.gdata.calendar.CalendarService();
		
		var that = this;
		service.getEventsFeed(
			query, 
			function(transport)
			{
				that.setFeed(transport.feed);
			},
			function(error)
			{
				console.error(error);
			}
		);
	},
	setFeed:function(feed)
	{
		this.feed = feed;
		this.addEntries(feed.getEntries());
	},
	addEntries:function(entries)
	{
		//we need to make sure that we only show the first event if it is recurring
		var recurringEvents = {};
		
		for(var i = 0, len = Math.min(entries.length, 8); i < len; i++)
		{	
			if(!entries[i].gd$when || !entries[i].gd$when[0].startTime)
			{
				console.error("This entry has no start time!",entries[i]);
				continue;
			}
		
			var description = entries[i].title.getText();
			//recurring events have the same title so just skip it cause we have it
			if(recurringEvents[description])
				continue;
				
			recurringEvents[description] = true;
				
			var dte = this.formatDate(entries[i].gd$when[0].startTime);
			
			this.container.appendChild(OBuilder('div',{className:'Division'},[
				OBuilder('span',{className:'Key'},dte),//entries[i].gd.getValue().date.toDateString()),
				OBuilder('span',{className:'Description'},description)
			]));
		}
	},
	formatDate:function(dateString)
	{	
		return dateString.substr(5,2) + '/' + dateString.substr(8, 2) + '/' + dateString.substr(0,4);
		/*
		var dte = new Date(dateString.substr(0,4), dateString.substr(5,2), dateString.substr(8, 2));
		return (dte.getMonth() + 1) + '/' + dte.getDate() + '/' + dte.getFullYear();
		*/
	}
});
