(function($) {
	
	$.fn.dbrlEvents = function(options) {
		
		var date = new Date();
		
		var url = "http://www.dbrl.org/api.calendar.php?f=json&callback=?";

		var defaults = {			
			year: date.getFullYear(),
			month: null,
			day: null,
			location: null,
			type: null,
			audience: null,
			tag: null,
			id: null,
			limit: 5,
			featured: null
		};
		
				
		$(this).each(function() {
									 
			var $events = $(this);									 
			
			$events.buildURL = function(url) {
				$events.url = url;
				
				if ($events.config.year) {
					$events.url += '&y=' + $events.config.year;
				}
				if ($events.config.month) {
					$events.url += '&m=' + $events.config.month;
				}
				if ($events.config.day) {
					$events.url += '&d=' + $events.config.day;
				}
				if ($events.config.location) {
					$events.url += '&w=' + $events.config.location;
				}
				if ($events.config.type) {
					$events.url += '&e=' + $events.config.type;
				}
				if ($events.config.audience) {
					$events.url += '&a=' + $events.config.audience;
				}
				if ($events.config.tag) {
					$events.url += '&t=' + $events.config.tag;
				}
				if ($events.config.id) {
					$events.url += '&i=' + $events.config.id;
				}
				if ($events.config.limit) {
					$events.url += '&l=' + $events.config.limit;
				}
				if ($events.config.featured) {
					$events.url += '&z=' + $events.config.featured;
				}
			};
						
			$events.getEvents = function() {
				$.getJSON($events.url, function(data) {
					//console.log(data);
					
					var $listItems = '';
					var $list = $('<ul class="dbrl-events">').appendTo($events);
					
					$.each(data.events, function(i, item) {
						//$("<li>").append(item.title + '<br />' + item.nicedateshort + ' &#0155; ' + item.nicetime).appendTo($list);								  
						$listItems += '<li><span class="dbrl-title"><a href="http://www.dbrl.org/calendar?i=' + item.id + '" target="_blank">' + item.title + '</a></span><br />' + item.location_long + '<br />' + item.nicedateshort + '</li>';
														  
					});
					
					$list.html($listItems);					
				});
			};
			
			// it's GO TIME
			$events.init = function() {
				//console.log(defaults);
				$events.config = $.extend(defaults, options);
				//console.log($events.config);
	
				$events.buildURL(url);
				
				//console.log($events.url);	
				
				$events.getEvents();
			};
			
			$events.init();
			
		});
		
	}
})(jQuery);
