(function($) {
  	$.fn.compactCal = function(options) {
    	debug("starting calendar");
    	
		// build main options before element iteration
    	var opts = $.extend({}, $.fn.compactCal.defaults, options);
                         
		// iterate and reformat each matched element
    	return this.each(function() {
			// get this reference for functions
			$thisCal = $(this);                   
			
			// setup prev/next handlers                   
			$(".prev", $thisCal).click(function (e) {                     
				$(".next", $thisCal).removeClass("toofar");
				if($(".current",$thisCal).prev().length != 0) {
					$thisCal.compactCal.showMonth($(".current",$thisCal).prev());
					// "disable" button if the next one isn't there
					if($(".current",$thisCal).prev().prev().length == 0) {
						$(this).addClass("toofar");
					}
				}       				
				e.preventDefault();
			});
			$(".next", $thisCal).click(function (e) {
				$(".prev", $thisCal).removeClass("toofar");
				if($(".current",$thisCal).next().length != 0) {
					$thisCal.compactCal.showMonth($(".current",$thisCal).next());
					// "disable" button if the next one isn't there
					if($(".current",$thisCal).next().next().length == 0) {
						$(this).addClass("toofar");
					}
				}
				e.preventDefault();
			});
			         
			
			// setup a tags throughout all months		      
			$("table a", $thisCal).hover(
			  	function () {
			    	$("#eventInfo ul").html($(this).next().html()); 
					var p = $(this).position();  
					$("#eventInfo").attr("style","position:absolute; left:" + (p.left + opts.offsetLeft) + "px; top:" + (p.top - $("#eventInfo").height() + opts.offsetTop) + "px;");
					$("#eventInfo").stop().fadeIn();					
			  	},
			  	function () {
			    	$("#eventInfo").stop().fadeOut();
			  	}
			);   
	    });
  	};
      
	// show the new month
	$.fn.compactCal.showMonth = function($newMonth) {
    	var $oldMonth = $("#monthViews .current", $thisCal);

		// show / hide
		$oldMonth.fadeOut().queue(function () {
			// show new month table
			$newMonth.fadeIn();

			// change text
			$("#monthLabel", $thisCal).html($newMonth.find("caption").html());

			// set new month to "current"
			$oldMonth.attr("class","");
			$newMonth.attr("class","current");                    
			
			// take out of queue so we can animate again later
			$(this).dequeue();
		});  
		
  	};

	// defaults
  	$.fn.compactCal.defaults = {
    	offsetLeft: -35,
    	offsetTop: 32
  	};

  	function debug(message) {
    	if (window.console && window.console.log)
      		window.console.log(message);
  	};
})(jQuery);
