(function($) {
	var ready = true;
	var direction = '';
	var currentOffset = 0;
	
	function setupCalendar(data) {
		$('.calendar h2').html('<strong>Calendar</strong><br />'+data.date);
		if(!data.next) $('.next-week').hide(); else $('.next-week').show();
		if(!data.prev) $('.prev-week').hide().parent().css('marginLeft', '85px'); else $('.prev-week').show().parent().css('marginLeft', '0');
		var left = (direction == 'left' ? 285 : -285);
		var nDiv = $('<div class="calendar-info">'+data.html+'</div>').css({ position:'absolute', left:left, top:'90px' }).appendTo('.calendar');
		$('.calendar-info').animate({ left:'-='+(left-20) }, 500, function() { 
			$('.calendar-info').not(':last').remove(); 
			if ($('.calendar').height()<$('.calendar-info').height()+80) $('.calendar').css({ height:$('.calendar-info').height()+80  });
			$('.calendar .loading').fadeTo({duration:'normal', queue:false}, 0); 
			ready = true; 
		});
	}
	
	function matchHeights() {
		var l = 0;
		$('.match').each(function() { if($(this).height()>l) l=$(this).height(); }).each(function() { $(this).height(l); });
		$('.calendar').css({ height:$('.calendar-info').height()+100 });
	}
	
	$(document).ready(function() {
		$('<p class="calendar-controls"><a class="prev-week blue btn left tiny" href="weekend.php?d=-7">&lt; Previous</a> <a class="next-week blue btn left tiny" href="weekend.php?d=7" style="margin-left:5px;">Next &gt;</a></p>').insertBefore('.calendar-info').find('a').hide();
		$.getJSON('ajax-data.php', { action:'calendar-init' }, function(data) { if(data.next) $('.next-week').show(); if(data.prev) $('.prev-week').show(); });
		
		$('.calendar').css({ overflow:'hidden', position:'relative', height:$('.calendar-info').height()+100 });
		$('.calendar-info').css({ position:'absolute', top:'90px', left:'20px' });
		$('<img class="loading" src="/images/ajax-loader-arrows.gif" alt="loading..." />').appendTo('.calendar').fadeTo('fast', 0);
		$('.calendar-controls a').click(function(e) { 
			e.preventDefault(); 
			$('.calendar .loading').fadeTo({ duration:'normal', delay:1, queue:false }, 0.6);
			if(ready) {
				ready = false;
				if($(this).text().indexOf('Next')>=0) {
					currentOffset += 7;
					direction = 'left';
				} else {
					currentOffset -= 7;
					direction = 'right';
				}
				$.getJSON('ajax-data.php', { action:'calendar', d:currentOffset }, setupCalendar);
			}
		});
	});
	window.onload = matchHeights;
})(jQuery);