/* Copyright (c) 2009, Apple Inc. All rights reserved. */

/**
* Represents a single upcoming events list.
* There can be multiple lists on one page -- all updating whenever the upcomingEventsService publishes 'GOT_UPCOMING_EVENTS'
**/
var UpcomingEventsViewController = Class.create({
	initialize: function(element, inOptWebCalendarURL)
	{
		this.element = $(element);
		this.webCalendarURL = inOptWebCalendarURL;
		publisher().subscribe(this.gotErrorFromServer.bind(this), 'ERROR_FROM_SERVER');
		publisher().subscribe(this.gotUpcomingEvents.bind(this), 'GOT_UPCOMING_EVENTS');
		upcomingEventsService().reload();
		this.drawTooltips();
	},
	drawTooltips: function()
	{
		d.body.appendChild(Builder.node('div', {id:'appointment_tooltip', className:'tooltip', style:'display:none'}, [
			Builder.node('h2', {id:'appointment_tooltip_summary'}),
			Builder.node('h4', {id:'appointment_tooltip_time_string'}),
			Builder.node('dl', [
				Builder.node('dt', Loc.tt_location),
				Builder.node('dd', {id:'appointment_tooltip_location'}),
				Builder.node('dt', Loc.tt_description),
				Builder.node('dd', {id:'appointment_tooltip_description'})
			])
		]));
	},
	gotErrorFromServer: function(inNotificationType, inPubObj, inUserObj)
	{
		this.element.hide();
		this.element.update('');
		this.element.appendChild(Builder.node('li', {}, Loc.error_from_caldav));
		this.element.show();
	},
	gotUpcomingEvents: function(inNotificationType, inUpcomingEvents)
	{
		this.element.hide();
		this.element.update(''); // clearing out any existing children...

		var n = inUpcomingEvents.length;
		if (n > 0) {
			for (var i=0; i < n; i++)
			{
				var e = inUpcomingEvents[i];
				var tooltipValues = {
					summary: e.summary(),
					time_string: Loc.getTimeRangeDisplayString(e.startDate(), e.duration()),
					location: e.location(),
					description: e.description()
				};
				var url = '#';
				if (this.webCalendarURL) {
					url = this.webCalendarURL + '?dtstart=' + (parseInt(e.startDate(true))) + '#uid=' + encodeURIComponent(e.uid);
				}
				this.element.appendChild(Builder.node('li', { className: 'EntryListItem' }, [
					Builder.node('a', { href: url, uid: e.uid }, [
						e.summary()
					]),
					Builder.node('span', { className: 'snippet' }, [
						tooltipValues.time_string
					])
				]));
				this.element.lastChild.tooltipElement = 'appointment_tooltip';
				this.element.lastChild.tooltipValues = tooltipValues;
				tooltipManager().observe(this.element.lastChild);
			}
		} else {
			this.element.appendChild(Builder.node('li', {}, Loc.no_upcoming_events));
		}
		
		this.element.show();
	}
});

if (window.loaded) loaded('calupcoming.js');