var timeline = {

/* =======================================
	Settings & init
======================================= */

	config: function() {
		this.pxPerDay = 115;
		this.lineHeight = 45;
		this.monthNames = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'];
		this.specialDates = ['2009-09-15'];
		this.specialDatesNames = ['Prinsjesdag'];
		this.firstDate = null;
		this.lastDate = null;
		this.months = null;
	},

	init: function() {
		this.config();
		$('.timeline .vevent').each(function (i) {
			if (!timeline.firstDate || timeline.toDate($(this).find('.dtstart').attr('title')) < timeline.firstDate) {
				timeline.firstDate = timeline.toDate($(this).find('.dtstart').attr('title'));
			}
			if (!timeline.lastDate || timeline.toDate($(this).find('.dtstart').attr('title')) > timeline.lastDate) {
				timeline.lastDate = timeline.toDate($(this).find('.dtstart').attr('title'));
			}
		});
		if ($('.timeline .vevent').length > 0) {
			$('body').addClass('tl_active');
			$('.timeline').after(timeline.templates.tlContainer);
			this.renderDays();
			this.renderSpecialDates();
			this.jumpTo(new Date());
		}
		$('.wrapper').click(function(){
			$('.tl_event_detail').remove();
		});
	},



/* =======================================
	Render
======================================= */

	renderDays: function() {
		var timespanDays = (this.lastDate - this.firstDate) / 86400000;
		$('.tl_content').css({
			width: (timespanDays+1) * timeline.pxPerDay
		});
		var ts_start = this.firstDate.getTime();
		var thisDate = new Date(ts_start);
		for (var i=0; i<=timespanDays; i++) {
			var thisDateStr = this.toString(thisDate);
			var weekend = (thisDate.getDay() == 0 || thisDate.getDay() == 6) ? ' weekend' : '';
			var special = jQuery.inArray(thisDateStr, this.specialDates);
			$('.tl_content').append(
				timeline.templates.tlDay(i, weekend, special, thisDate)
			);
			this.renderEvents(timeline.toString(thisDate), i);
			thisDate.setDate(thisDate.getDate()+1);
		}
		$('.tl_content').css({
			height: document.getElementById('tl_container').scrollHeight + 30
		});
	},

	renderEvents: function(thisDateStr, day) {
		var n = 0;
		$('.timeline .vevent').each(function (i) {
			if ($(this).find('.dtstart').attr('title') == thisDateStr) {
				var self = this;
				$('.tl_content').append(
					timeline.templates.tlEvent(
						day * timeline.pxPerDay,
						n * (timeline.lineHeight+15) + 45,
						timeline.pxPerDay - 10
					).append(
						timeline.templates.tlEventSummary($(self).find('.summary').text()).click(function() {
							timeline.showEvent(
								$(self).find('.summary').text(),
								$(self).find('.data').text(),
								$(self).find('.description').html(),
								this.parentNode
							);
							return false;
						})
					)
				);
				n++;
			}
		});
	},

	renderSpecialDates: function() {
		$('#tl_container').after(timeline.templates.tlSpecial);
		$('#tl_special').append(
			$('<li/>').append(
				$('<a/>').attr('href', '#').text('Vandaag').click(function() {
					timeline.jumpTo(new Date());
					return false;
				})
			)
		);
		$(this.specialDates).each(function (i) {
			$('#tl_special').append(
				$('<li/>').append(
					$('<a/>').attr('href', '#').text(timeline.specialDatesNames[i]).click(function() {
						var targetDate = timeline.toDate(timeline.specialDates[i]);
						targetDate.setHours(targetDate.getHours()+21);
						timeline.jumpTo(targetDate);
						return false;
					})
				)
			);
		});
	},

	showEvent: function(evSummary, evDate, evDescription, eventLink) {
		$('.tl_event_detail').remove();
		var offset = $(eventLink).offset();
		$('body').append(
			timeline.templates.tlEventDetail(offset.top, evSummary, evDate, evDescription).append(
				timeline.templates.closeBtn.click(function(){
					$('.tl_event_detail').remove();
					return false;
				})
			).hide().fadeIn(500)
		);
		vpHeight = window.innerHeight
			|| document.documentElement && document.documentElement.clientHeight
			|| document.body.clientHeight;
		if (offset.left + this.pxPerDay/2 > document.body.clientWidth / 2) {
			$('.tl_event_detail').css({ right: document.body.clientWidth - offset.left + 10 });
		} else {
			$('.tl_event_detail').css({ left: offset.left + $(eventLink).width() });
		}
		if (window.pageYOffset && offset.top + $('.tl_event_detail').height() > vpHeight - 35) {
			$('.tl_event_detail').css({ top: vpHeight - $('.tl_event_detail').height() - 35 + window.pageYOffset });
		}
	},



/* =======================================
	Templates
======================================= */

	templates: {
		tlContainer: $('<div/>').attr('id', 'tl_container').css({
			position: 'relative',
			overflow: 'auto',
			overflowY: 'hidden'
		}).append(
			$('<div/>').addClass('tl_content').css({
				position: 'relative'
			})
		),
		tlDay: function(i, weekend, special, thisDate) {
			return $('<div class="tl_day' + weekend + (special > -1 ? ' special special-'+special : '') + '"/>').css({
				position: 'relative',
				float: 'left',
				opacity: 0.8,
				width: timeline.pxPerDay,
				height: '100%'
			}).html(
				'<span class="tl_day_day">' + thisDate.getDate() + '</span> ' + 
				'<span class="tl_day_month">' + timeline.monthNames[thisDate.getMonth()] + '</span>'
			);
		},
		tlEvent: function(l, t, w) {
			return $('<div/>').addClass('tl_event').css({
				position: 'absolute',
				zIndex: 1000,
				left: l,
				top: t,
				width: w
			});
		},
		tlEventSummary: function(summary) {
			return $('<a/>').attr('href', '#').addClass('tl_event_summary').css({
				display: 'block'
			}).html(summary);
		},
		tlEventDetail: function(t, evSummary, evDate, evDescription) {
			return $('<div/>').addClass('tl_event_detail').css({
				position: 'absolute',
				top: t,
				zIndex: 2000,
				opacity: 0.9
			}).append(
				$('<div/>').addClass('content').html(
					'<h2>' + evSummary + '</h2>' +
					'<p class="data">' + evDate + '</p>' +
					evDescription
				)
			);
		},
		tlSpecial: $('<ul/>').addClass('item-list').attr('id', 'tl_special').html('<h2>Direct naar&hellip;</h2>'),
		closeBtn: $('<a/>').addClass('close').attr({
			href: '#',
			title: 'Sluit'
		}).css({
			display: 'block',
			position: 'absolute',
			right: '-5px',
			top: '-5px',
			width: 16,
			height: 16,
			textIndent: '-1234em',
			cursor: 'pointer',
			zIndex: 3000
		}).text('Sluit')
	},



/* =======================================
	Helpers
======================================= */

	jumpTo: function(toDate) {
		var diffDays = (toDate - this.firstDate) / 86400000;
		//document.getElementById("tl_container").scrollLeft = Math.round((diffDays-1) * this.pxPerDay);
		$('#tl_container').animate({scrollLeft: Math.round((diffDays-1) * this.pxPerDay)}, 1000);
	},

	toDate: function(string) {
		if (string) {
			return new Date(
				string.substr(0,4),
				Math.abs(string.substr(5,2))-1,
				Math.abs(string.substr(8,2))
			);
		} else {
			return;
		}
	},

	toString: function(d) {
		return (
			d.getFullYear() + '-'
			+ ((d.getMonth()<9)?'0':'') + (d.getMonth()+1) + '-'
			+ ((d.getDate()<10)?'0':'') + d.getDate()
		);
	}

}



if (window.XMLHttpRequest) {
	$(document).ready(function() {
		timeline.init();
	}); 
}
