(function($){
	$.fn.calendar = function(options) {
		$this = this;
		
		var defaults = {
				script: 'calendar.php',
				width: '345px',
				height: 'auto',
				minHeight: '200px'
		};
		
		var options = $.extend({}, defaults, options);
		
		var ajax = false;
		var getCalendar = function(t, l, m, y) {
			if (ajax == true) {
				return null;
			}
			ajax = true;
			$.post(options.script, {
				month: m,
				year: y
			}, function(data) {
				t.html(data);
				
				l.hide();
				t.css('opacity', '1');
				
				t.find('a.nextMonth')
					.click(function(e) {
						e.preventDefault();
						l.show();
						t.css('opacity', '0.3');
						var dp = $(this).attr('rel').split('-');
						getCalendar(t, l, dp[1], dp[0]);
					})
				;
				
				t.find('a.prevMonth')
					.click(function(e) {
						e.preventDefault();
						l.show();
						t.css('opacity', '0.3');						
						var dp = $(this).attr('rel').split('-');
						getCalendar(t, l, dp[1], dp[0]);
					})
				;
				ajax = false;
			});	
		};
		
		this.each(function() {
			$(this)
				.html('<div class="calendar_loader"></div>')
				.find('div.calendar_loader')
					.css({
						'position': 'absolute',
						'width': '32px',
						'height': '32px',
						'border': '3px solid #CCCCCC',
						'background': 'url("./images/loading.gif") no-repeat scroll 50% 50% #FFFFFF',
						'z-index': '1000',
						'-moz-border-radius': '10px',
						'left': '50%',
						'top': '50%'
					})
			;
			
			$(this).css({
				'width': options.width,
				'height': options.height,
				'minHeight': options.minHeight,
				'position': 'relative'
			});
			
			$(this)
				.append('<table class="calendar"></table>')
				.find('table.calendar')
					.css('opacity', '0.3')
			;
			
			table = $(this).find('table.calendar');
			loader = $(this).find('div.calendar_loader');
			date = new Date();
			getCalendar(table, loader, date.getMonth()+1, date.getFullYear());
		});
		return this;
	}
})(jQuery);
