(function($) {
	$.fn.edenCalendar = function(opts)
	{
		opts = $.extend({}, $.fn.edenCalendar.defaults, opts);
		
		return this.each(function(){
			$this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			$("[rel=back]").click(function(){
				$.fn.edenCalendar.changeMonth($this,"-1");
			});
			$("[rel=next]").click(function(){
				$.fn.edenCalendar.changeMonth($this,"+1");
			});
			$this.data("opts",o)
			currDate = $(".month", $this).attr("rel").split("-");
			currMonth = parseFloat(currDate[0]);
			currYear = parseFloat(currDate[1]);
			$.ajax({
				type:"POST",
				data:{month:currMonth,year:currYear},
				url:SETTINGS.webRoot + "/calendar/index/get-month/",
				success:function(data){
					$(".month",$this).replaceWith(data);
					if(o.onDayClick != false) $.fn.edenCalendar.initDays($this, o);
				}
			});
		});
	}

	$.fn.edenCalendar.changeMonth = function(cal,delta)
	{
		currDate = $(".month", cal).attr("rel").split("-");
		currMonth = parseFloat(currDate[0]);
		currYear = parseFloat(currDate[1]);
		newMonth = currMonth;
		newYear = currYear;
		
		if(delta.indexOf("-")==0)
		{
			newMonth = currMonth-1;
		}else if(delta.indexOf("+")==0){
			newMonth = currMonth+1;
		}
		
		if(newMonth < 1)
		{
			newMonth = 12;
			newYear = currYear-1;
		}else if(newMonth > 12)
		{
			newMonth = 1;
			newYear = currYear+1;
		}
		
		$(".month", cal).attr("rel", newMonth + "-" + newYear)
		
		$.ajax({
			type:"POST",
			data:{month:newMonth,year:newYear},
			url:SETTINGS.webRoot + "/calendar/index/get-month/",
			success:function(data){
				$(".month", cal).replaceWith(data);
				if(cal.data("opts").onDayClick != false) $.fn.edenCalendar.initDays(cal, cal.data("opts"));
			}
		});
	}
	
	$.fn.edenCalendar.initDays = function(cal, opts)
	{
		if(opts.onDayClick == null)
		{
			$(".day",cal).not(".offday").click(function(){
				if($(".eventlist", this).length)
				{
					$("#eventDetails").remove();
					popup = $("<div id='eventDetails'></div>").html($(".eventlist", this).html()).appendTo(cal);
					popup.click(function(){
						$(this).remove();
					});
				}
			});
		}else{
			$(".day",cal).not(".offday").click(opts.onDayClick);
		}			
	};

	// Establish the defaults
	$.fn.edenCalendar.defaults = {
		onDayClick:null
	};
	
})(jQuery);