(function($) {
	$(document).ready(function() {
		$('.EventCalendarWidget')
		.each(function() {
			// initialize options
			var options = {};
			$('input[type=hidden]', this)
			.each(function() {
				var name = $(this).attr('name');
				var value = $(this).attr('value');
				options[name] = value;
			})
			;
			this.options = options;
			
			// initialize datepicker
			$(this).datepicker({
				dateFormat: 'yy-mm-dd',
				showButtonPanel: true,
				onSelect: function(dateText) {
					location.href = this.options.calendar + dateText;
				},
				beforeShowDay: (!this.options.live) ? null : function(date) {
					if(!this.events)
						return [ !(this.options.async && this.requesting) ];
					
					var year = 1900 + date.getYear();
					var month = date.getMonth() + 1;
					var day = date.getDate();
					var dateText = year.toString() + '-' + ('0' + month.toString()).substring(month.toString().length - 1) + '-' + ('0' + day.toString()).substring(day.toString().length - 1);
					
					if((events = this.events[dateText]))
						return [ true, '', events.join(', ') ];
					
					return [ false ];
				},
				onChangeMonthYear: (!this.options.live) ? null : function(year, month, inst) {
					// generate text version of date
					var dateText = year.toString() + '-' + ('0' + month.toString()).substring(month.toString().length - 1);
					
					// event controller url
					var controller = this.options.controller + '/' + dateText;
					
					// abort previous requests
					if(this.request)
						this.request.abort();
					
					// get events for new month
					var calendar = this;
					this.request = $.ajax({
						url: controller,
						dataType: 'json',
						async: this.options.async,
						timeout: this.options.timeout,
						global: false,
						beforeSend: function() {
							calendar.requesting = true;
						},
						success: function(json) {
							calendar.events = json;
						},
						complete: function() {
							calendar.requesting = false;
							if(calendar.options.async)
								$(inst).datepicker('update');
						}
					});
				}
			});
		})
		;
	});
})(jQuery);