(function($)
{
	var headerLabels = [jsTranslate("Su"), jsTranslate("Mo"), jsTranslate("Tu"), jsTranslate("We"), jsTranslate("Th"), jsTranslate("Fr"), jsTranslate("Sa")];
	
	var publicMethods =
	{
		setSize: function(in_size)
		{
			$(this).data('sizedirty', true);

			$(this).data('size', in_size);
			$(this).find('#minicalendar_container').css({ 'width': in_size, 'height': 285});
			$(this).find('#minicalendar_container2').css({ 'width': in_size, 'height': 285});
			$(this).find('#minicalendar_container3').css({ 'width': in_size, 'height': 285});
			
			calcsize = Math.floor( in_size / 7 );
			$(this).find('[id^=monthCalGridLabel]').css({ 'height' : ( 285 - 1) + 'px', 'width' : ( calcsize - 1) + 'px', 'line-height' : calcsize + 'px'});
			$(this).find('[id^=monthCalGridDay]').css({ 'height' : ( 285 - 1) + 'px', 'width' : ( calcsize - 1) + 'px', 'line-height' : calcsize + 'px'});
		},
		setTotalDays: function(in_total)
		{
			$(this).data('totalDays', in_total);
			var allSelectors = $(this).find('[id^=monthCalGridDay]');
			var hiddenSelectors = $(this).find('[id^=monthCalGridDay]:hidden');

			if(allSelectors.length > in_total)
			{
				allSelectors.slice(in_total).each(function() { $(this).hide(); } );
			}
			else if (allSelectors.length - hiddenSelectors.length  < in_total)
			{
				allSelectors.slice(allSelectors.length - hiddenSelectors.length).each(function() { $(this).show(); } );				
			}
		},
		makeSmall: function()
		{
			$(this).monthCal('setSize', 210);
			$(this).monthCal('setTotalDays', 42);
		},
		makeBig: function()
		{
			$(this).monthCal('setSize', 285);
			$(this).monthCal('setTotalDays', 42);
		},
		refresh: function()
		{
			$(this).monthCal("changeDate", $(this).data('showDate').getFullYear(), $(this).data('showDate').getMonth(), $(this).data('showDate').getDate(), true);
		},
		setSelectedDate: function(date) {
			$(this).data("selectedDate", new Date(date));
			$(this).monthCal("changeDate", date.getFullYear(), date.getMonth(), date.getDate());
		},
		changeDate: function(year, month, day, refresh)
		{
			if (year === undefined || month === undefined)
			{
				 return false;
			}

			var sameMonth = ((new Date(year, month, (day) ? day : 1)).getMonth() == $(this).data('showDate').getMonth()
					&& 	(new Date(year, month, (day) ? day : 1)).getFullYear() == $(this).data('showDate').getFullYear())
					? 	true : false && ($(this).data('sizedirty') == false);
			$(this).data('sizedirty', false);
			var firstChild = $(this).children(":first");
			var secondChild = firstChild.children(":first");
			var thirdChild = secondChild.children(":first");
			var children = new Array(firstChild, secondChild, thirdChild);
			var size = $(this).data('size');
			var calcsize = Math.floor( size / 7 );
			var DayPos = (! (new Date(year, month, (day) ? day : 1) > $(this).data('showDate')) ) ? ":first" : ":last";
			var currentTotalDays = $(this).data('totalDays');

			var showDate = $(this).data('showDate');
			showDate.setFullYear(year);
			showDate.setMonth(month);
			showDate.setDate(day ? day : 1);
			var controlDate = new Date(showDate);
			controlDate.setDate(1);
			controlDate.setDate(-(controlDate.getDay() - 1));
			if(!sameMonth || !children[1].find('#monthCalGridLabel0').length)
			{
				for (var i = 0; i < 7; i ++)
				{
					selector = children[1].find('#monthCalGridLabel' + i);
	
					if(!selector.length)
					{
						selector = children[1].children(DayPos);
						selector.append("<div id=\"monthCalGridLabel" + i + "\"></div>");
						selector = children[1].find('#monthCalGridLabel' + i);
					}
					selector.replaceWith("<div id=\"monthCalGridLabel" + i + "\" class=\"monthCalGridDay "+ ($(this).data('smallText') ? "" : "DayName") +"\" " +
							"style=\"width: " + (calcsize - 1) +
							"px; height: " + ( calcsize - 1) +
							"px; line-height: " + calcsize +
							"px; color: #7A8FA9; font-weight: bold; font-size: " + ($(this).data('smallText') ? "10pt" : "12pt") +
							";\">" + headerLabels[i] + "</div>");
				}
			}

			var DayCounter = 0;
			var processDays = (!sameMonth || !children[1].find('#monthCalGridDay0').length);
			var maximum_days = 42;
			var backgroundClass = "dayPickerSelectedBG" + (($(this).data("smallText")) ? "Small" : "");
			children[1].find('.' + backgroundClass).removeClass(backgroundClass);

			while (DayCounter < maximum_days) {
				var eventsInDay = false;
				selector = children[1].find('#monthCalGridDay' + DayCounter);

				if(processDays)
				{
					if(!selector.length)
					{
						selector = children[1].children(DayPos);
						selector.append("<div id='monthCalGridDay" + DayCounter + "'></div>");
						selector = children[1].find('#monthCalGridDay' + DayCounter);
					}
					selector.replaceWith("<div id='monthCalGridDay" + DayCounter + "' class=\"monthCalGridDay " + (( controlDate.getMonth() == showDate.getMonth()) ? "current " : "prev ") + ((eventsInDay) ? "newcalendar_calgridday" + (($(this).data('smallText')) ? "_small" : "") : "") + "\" style=\"width: " + (calcsize - 1) +
						"px; height: " + (calcsize - 1) +
						"px; line-height: " + calcsize +
						"px; color: " + (( controlDate.getMonth() == showDate.getMonth()) ? "#B9C4D2" : "#DDE0E3") +
						"; font-size: " + ($(this).data('smallText') ? "12pt" : "14pt") +
						"; font-weight: " + ((eventsInDay) ? "bold" : "normal") +
						"; \">" +
						"<div class=\"holdDate\">" + controlDate.getDate() + "</div>" + "</div>");
					if(DayCounter > currentTotalDays)
					{
						//reselect changes
						children[1].find('#monthCalGridDay' + DayCounter).hide();
					}
				}
					
				selectedDate = $(this).data('selectedDate');
				if (
					controlDate.getMonth() == showDate.getMonth()
				&& 	controlDate.getFullYear() == selectedDate.getFullYear()
				&&	controlDate.getMonth() == selectedDate.getMonth()
				&&	controlDate.getDate() == selectedDate.getDate()
				)
				{
					children[1].find('#monthCalGridDay' + DayCounter).addClass(backgroundClass);
				}
				if (controlDate.getMonth() == showDate.getMonth())
				{
					var il = $(this).data('highlightRanges').length;
					for (var i = 0; i < il; i ++)
					{
						if(
							controlDate >= $(this).data('highlightRanges')[i].start
						&&	controlDate <= $(this).data('highlightRanges')[i].end)
						{
							selector.children(":last").css("background-color", "#fdf4ab");
							break;
						}
					}
				}
				
				if(processDays)
				{
					// reselect
					dayBox = children[1].find('#monthCalGridDay' + DayCounter);
					dayBox.data("this", this);
					dayBox.data("thisDate", new Date(controlDate));
					dayBox.mousedown(function()
					{
						_this = $(this).data('this');
	
						dateRangeHolder = $(_this).data('dateRangeHolder');
						if ($(_this).data('dateRange'))
						{
							dateRangeHolder = [new Date($(this).data("thisDate"))];
						}
						$(_this).data('dateRangeHolder', dateRangeHolder);
					});
					dayBox.mouseup(function()
					{
						_this = $(this).data('this');
	
						if ($(_this).data('dateRange'))
						{
							dateRangeHolder = $(_this).data('dateRangeHolder');
							dateRangeHolder.push(new Date($(this).data("thisDate")));
							if (dateRangeHolder.length == 2)
							{
								if (dateRangeHolder[0] > dateRangeHolder[1])
								{
									dateRangeHolder.push(dateRangeHolder.shift());
								}
								$(_this).monthCal("addDateRange", "userSelect", new Date(dateRangeHolder[0]), new Date(dateRangeHolder[1]));
								if ($(_this).data('dateRangeSelect'))
								{
									$(_this).data('dateRangeSelect')(new Date(dateRangeHolder[0]), new Date(dateRangeHolder[1]));
								}
							}
							dateRangeHolder.length = 0;
							$(_this).data('dateRangeHolder', dateRangeHolder);
						}
					});
					dayBox.mouseover(function()
					{
						_this = $(this).data('this');
						if ($(_this).data('dateRangeHolder') != undefined && $(_this).data('dateRangeHolder').length)
						{
							$(_this).monthCal("dateRangeHover", new Date($(_this).data('dateRangeHolder')[0]), new Date($(this).data("thisDate")));
						}
					});
					dayBox.click(function()
					{
						_this = $(this).data('this');
						thisDate = $(this).data('thisDate');
						$(_this).data('selectedDate', thisDate);
						$(_this).monthCal("changeDate", thisDate.getFullYear(), thisDate.getMonth(), thisDate.getDate());
						if ($(_this).data('select'))
						{
							$(_this).data('select')(thisDate);
						}
					});
				}
				controlDate.setDate(controlDate.getDate() + 1);
				DayCounter ++;
			}

			$(this).attr("unselectable", "on").css("-moz-user-select", "none").each(function()
			{
				this.onselectstart = function()
				{
					return false;
				};
			});

			if(refresh && $(this).data('eventHints').length)
			{
				publicMethods['renderEventHints'].apply(this, new Array());
			}
			if (!refresh && $(this).data('monthRender')) $(this).data('monthRender')(showDate);
			
			$(this).data('showDate', showDate);
		},
		dateRangeHover: function(start, end)
		{
			if (start > end)
			{
				var OrgStart = start;
				start = end;
				end = OrgStart;
			}

			$(this).children(":first").children(":first").children(":first").children().each(function()
			{
				if ($(this).data("thisDate") && $(this).data("thisDate") >= start && $(this).data("thisDate") <= end)
				{
					if(	$(this).css("background-color") != "#dbebf7" 
					&& 	$(this).css("background-color") != "rgb(219, 235, 247)") 
					{
						$(this).data("orgBgColor", ($(this).css("background-color")) ? (($(this).css("background-color") == "#ecf0d1" || $(this).css("background-color") == "rgb(236, 240, 209)") ? "#fdf4ab" : $(this).css("background-color")) : "white");
					}
					$(this).css("background-color", ($(this).data("orgBgColor") == "#fdf4ab" || $(this).data("orgBgColor") == "rgb(253, 244, 171)") ? "#ecf0d1" : "#dbebf7");
				}
				else if ($(this).data("orgBgColor"))
				{
					$(this).css("background-color", $(this).data("orgBgColor"));
				}
			});
		},
		addDateRange: function(id, start, end)
		{
			if (!id || !start || !end)
			{
				return false;
			}

			var il = $(this).data('highlightRanges').length;
			for (var i = 0; i < il; i ++)
			{
				if ($(this).data('highlightRanges')[i].id == id)
				{
					$(this).data('highlightRanges').splice(i, 1);
					break;
				}
			}
			$(this).data('highlightRanges').push({"id": id, "start": start, "end": end});
			$(this).data('selectedDate', new Date(start));
			showDate = new Date(start);
		
			$(this).monthCal("changeDate", $(this).data('showDate').getFullYear(), $(this).data('showDate').getMonth(), $(this).data('showDate').getDate());
		},
		clearEventHints: function()
		{
			if( $(this).data("eventHints").length)
				$(this).data('eventHints', new Array());
		},
		addEventHint: function(date, count) {
			if (typeof($(this).data("eventHints")) == "function") return false;
			alreadyInMemory = false;
			var il = $(this).data("eventHints").length;
			for (var i = 0; i < il; i ++) {
				if ($(this).data("eventHints")[i][0].getLongDate() == date.getLongDate()) {
					$(this).data("eventHints")[i][1] += 1;
					alreadyInMemory = true;
					break;
				}
			}
			if (!alreadyInMemory) $(this).data("eventHints").push([date, 1]);
		},
		setEventHint: function(date, count, ifNull) {
			if (typeof($(this).data("eventHints")) == "function") return false;
			alreadyInMemory = false;
			var il = $(this).data("eventHints").length;
			for (var i = 0; i < il; i ++) {
				if ($(this).data("eventHints")[i][0].getLongDate() == date.getLongDate()) {
					if (!ifNull || !$(this).data("eventHints")[i][1]) $(this).data("eventHints")[i][1] = count;
					alreadyInMemory = true;
					break;
				}
			}
			if (!alreadyInMemory) $(this).data("eventHints").push([date, count]);
		},
		removeEventHint: function(date)
		{
			var eventHints = $(this).data("eventHints");
			if (typeof(eventHints) == "function") return false;
			
			var il = eventHints.length;
			for (var i = 0; i < il; i ++) {
				if (eventHints[i][0].getLongDate() == date.getLongDate()) {
					$(this).data("eventHints")[i][1] -= 1;
					if($(this).data("eventHints")[i][1] <= 0)
					{
						$(this).data("eventHints", $.merge($(this).data("eventHints").slice(0, i), $(this).data("eventHints").slice(i+1)));
					}
					break;
				}
			}
		},
		renderEventHints: function()
		{
			var DayCounter = 0;
			var total =  $(this).data('totalDays');
			var eventHintsLength = $(this).data("eventHints").length;
			var currentControlDate = new Date($(this).data('showDate'));
			currentControlDate.setDate(1);
			currentControlDate.setDate(-(currentControlDate.getDay() - 1));
			
			var dateDivs = $('#miniCalendar').children('div').children('div').children('div');
			
			while (DayCounter < total)
			{
				var currentControlDateLong = currentControlDate.getLongDate();
				var eventsInDay = false;
				if (typeof($(this).data("eventHints")) == "function")
				{
					eventsInDay = $(this).data("eventHints")(currentControlDate);
				}
				else
				{
					for (var i = 0; i < eventHintsLength; i ++)
					{
						if (	$(this).data("eventHints")[i][1]
							&& 	$(this).data("eventHints")[i][0].getLongDate() == currentControlDateLong
							)
						{
							eventsInDay = true;
							break;
						}
					}
				}
				if(eventsInDay)
				{
					dateDivs.children('div:eq(' + (7 + DayCounter) + ')').addClass((eventsInDay ? "newcalendar_calgridday" + ( $(this).data('smallText') ? "_small" : "") : ""));
				}
				else
				{
					dateDivs.children('div:eq(' + (7 + DayCounter) + ')').removeClass('newcalendar_calgridday').removeClass('newcalendar_calgridday_small');
				}
				DayCounter ++;
				currentControlDate.setDate(currentControlDate.getDate() + 1);
			}		
		}
	};

	$.fn.monthCal = function(method)
	{
		if (typeof(method) === "object" || !method)
		{
			$(this).data('highlightRanges', []);
			$(this).data('dateRangeHolder', []);
			$(this).data('showDate', method.showDate);
			$(this).data('selectedDate', new Date((method.selectedDate) ? method.selectedDate : method.showDate));
			$(this).data('monthRender', method.monthRender);
			$(this).data('eventHints', (method.eventHints) ? method.eventHints : []);
			$(this).data('size', method.size);
			$(this).data('size', Math.floor(parseFloat($(this).data('size')) / 7) * 7);
			$(this).data('smallText', (method.smallText) ? true : false);
			$(this).data('totalDays', method.small ? 35 : 42);
			$(this).data('small', method.small);
			$(this).data("sizeIsSmall", method.small);
			
			if (method.highlightRanges)
			{
				$(this).data('highlightRanges', method.highlightRanges);
			}
			
			if (method.select)
			{
				$(this).data('select', method.select);
			}
			$(this).data('dateRange', false);

			if (method.dateRange)
			{
				$(this).data('dateRange', true);
			}
			
			if (method.dateRangeSelect)
			{
				$(this).data('dateRangeSelect', method.dateRangeSelect);
			}
			$(this).append("<div id='minicalendar_container' style=\"overflow: hidden; width: " + $(this).data('size') + "px; height: " + $(this).data('size') + "px;\"><div id='minicalendar_container2' style=\"width: " + $(this).data('size') + "px; height: " + $(this).data('size') + "px;\"><div id='minicalendar_container3' style=\"float: left; width: " + $(this).data('size') + "px; height: " + $(this).data('size') + "px;\"></div></div></div>");
			$(this).monthCal("changeDate", $(this).data('showDate').getFullYear(), $(this).data('showDate').getMonth(), $(this).data('showDate').getDate());
			
			return $;
		}
		else if (publicMethods[method])
		{
			return publicMethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else
		{
			$.error("Method " +  method + " does not exist on jQuery.monthCal");
		}
	};
})(jQuery);

(function($){
	var MONTH_SELECTOR_OFFSET = 23;
	var MONTH_SELECTOR_OFFSET_LARGE = 54;
	var MONTH_TEXT_SIZE = 13;
	var MONTH_TEXT_SIZE_LARGE = 33;

	var publicMethods = {
		selectMonth: function(month, thisOnly) {
			if (month == $(this).data("selectedDate").getMonth()) return false;

			$(this).children("#monthSelector" + $(this).data("selectedDate").getMonth()).removeClass("monthSelectorButtonSelected");

			var thisLink = this;
			
			if($(this).data('sizeIsSmall'))
			{
				$(this).removeClass('month_selector_button_selected');
				$(this).addClass('month_selector_button_selector_small');		
			}
			else
			{
				$(this).removeClass('month_selector_button_selector_small');	
				$(this).addClass('month_selector_button_selected');
			}

	        $(this).animate({
				backgroundPosition: ((($(this).data("sizeIsSmall")) ? MONTH_SELECTOR_OFFSET : MONTH_SELECTOR_OFFSET_LARGE) + (month * (($(this).data("sizeIsSmall")) ? MONTH_TEXT_SIZE : MONTH_TEXT_SIZE_LARGE))) + "px 0px"
			}, "fast", "linear", function() {
				$(thisLink).children("#monthSelector" + month).addClass("monthSelectorButtonSelected");

				$(thisLink).data("selectedDate").setMonth(month);

				if (!thisOnly) {
					$(this).data("calendarSelector")($(thisLink).data("selectedDate").getFullYear(), $(thisLink).data("selectedDate").getMonth(), $(thisLink).data("selectedDate").getDate());
				}
	        });
		},
		selectYear: function(year, thisOnly) 
		{
			var thisLink = this;

			$(this).data("selectedDate").setFullYear(year);
			$("#yearSelectorPrev").empty().append(($(this).data("sizeIsSmall")) ? ($(this).data("selectedDate").getFullYear() - 1).toString().substring(2, 4) : ($(this).data("selectedDate").getFullYear() - 1));
			$("#yearSelectorCurrent").empty().append(($(this).data("sizeIsSmall")) ? $(this).data("selectedDate").getFullYear().toString().substring(2, 4) : $(this).data("selectedDate").getFullYear());
			$("#yearSelectorNext").empty().append(($(this).data("sizeIsSmall")) ? ($(this).data("selectedDate").getFullYear() + 1).toString().substring(2, 4) : ($(this).data("selectedDate").getFullYear() + 1));

			if (!thisOnly) {
				$(this).data("calendarSelector")($(thisLink).data("selectedDate").getFullYear(), $(thisLink).data("selectedDate").getMonth(), $(thisLink).data("selectedDate").getDate());
			}
		},
		nextYear: function() {
			$(this).monthSelector("selectYear", $(this).data("selectedDate").getFullYear() + 1);
		},
		prevYear: function() {
			$(this).monthSelector("selectYear", $(this).data("selectedDate").getFullYear() - 1);
		},
		makeSmall: function() {

			if ($(this).data("sizeIsSmall") != undefined && $(this).data("sizeIsSmall")) return false;
			$(this).removeClass('month_selector_button_selected');
			$(this).addClass('month_selector_button_selected_small');
			var monthLabels = new Date();
			for (var i = 0; i < 12; i ++) {
				monthLabels.setMonth(i, 1);
				$(this).children("#monthSelector" + i).empty().css("width", MONTH_TEXT_SIZE + "px").append(monthLabels.getMonthExt().substring(0, 1));
			}
			$(this).children("#yearSelectorPrev").empty().css("width", "40px").append(($(this).data("selectedDate").getFullYear() - 1).toString().substring(2, 4));
			$(this).children("#yearSelectorCurrent").empty().css("width", "40px").append($(this).data("selectedDate").getFullYear().toString().substring(2, 4));
			$(this).children("#yearSelectorNext").empty().css("width", "40px").append(($(this).data("selectedDate").getFullYear() + 1).toString().substring(2, 4));
			$(this).css("background-position", (MONTH_SELECTOR_OFFSET + ($(this).data("selectedDate").getMonth() * MONTH_TEXT_SIZE)) + "px 0px");

			$(this).data("sizeIsSmall", true);
			$(this).data('small', true);
		},
		makeBig: function() {
			
			if ($(this).data("sizeIsSmall") != undefined && !$(this).data("sizeIsSmall")) return false;
			$(this).removeClass('month_selector_button_selected_small');
			$(this).addClass('month_selector_button_selected');
			var monthLabels = new Date();
			for (var i = 0; i < 12; i ++) {
				monthLabels.setMonth(i, 1);
				$(this).children("#monthSelector" + i).empty().css("width", "33px").append(monthLabels.getMonthExt());
			}
			$(this).children("#yearSelectorPrev").empty().css("width", "40px").append(($(this).data("selectedDate").getFullYear() - 1).toString());
			$(this).children("#yearSelectorCurrent").empty().css("width", "40px").append($(this).data("selectedDate").getFullYear().toString());
			$(this).children("#yearSelectorNext").empty().css("width", "40px").append(($(this).data("selectedDate").getFullYear() + 1).toString());
			$(this).css("background-position", (MONTH_SELECTOR_OFFSET_LARGE + ($(this).data("selectedDate").getMonth() * MONTH_TEXT_SIZE_LARGE)) + "px 0px");

			$(this).data("sizeIsSmall", false);
			$(this).data('small', false);
		}
	};

	$.fn.monthSelector = function(method) {
		if (publicMethods[method]) {
			return publicMethods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof(method) === "object" || !method) {
			var thisLink = this;
			
			$(this).data('small', method.small);
			$(this).data("calendarSelector", method.calendarSelector);
			$(this).data("selectedDate", new Date((method.selectedDate) ? method.selectedDate : todaysDate));

			$(this).append("<div id=\"yearSelectorButtonLeft\">&nbsp;</div>")
			
			$("#yearSelectorButtonLeft").click(function() {
				$(thisLink).monthSelector("prevYear");
			});
			$(this).append("<div id=\"yearSelectorPrev\" class=\"monthSelectorButton\" style=\"width: 40px; border-right: 1px solid #97a9b6;\">" + ($(this).data("selectedDate").getFullYear() - 1) + "</div>");
			$("#yearSelectorPrev").click(function() {
				$(thisLink).monthSelector("prevYear");
			});

			$(this).append("<div style=\"float: left; overflow: hidden; width: 5px; height: 19px;\">&nbsp;</div>");

			var labels = new Date();
			for (var month = 0; month < 12; month ++) {
				labels.setMonth(month, 1);
				if($(this).data('small'))
				{
					monthText = labels.getMonthExt().substring(0, 1);
					width = MONTH_TEXT_SIZE;
				}
				else
				{
					monthText =  labels.getMonthExt();
					width = MONTH_TEXT_SIZE_LARGE;
				}
				$(this).append("<div id=\"monthSelector" + month + "\" month=\"" + month + "\" class=\"monthSelectorButton" + ((labels.getMonth() == $(this).data("selectedDate").getMonth()) ? " monthSelectorButtonSelected" : "") + "\" style=\"width: " + width + "px;\">" +  monthText + "</div>");

				$("#monthSelector" + month).data("month", month);
				$("#monthSelector" + month).click(function() {
					$(thisLink).monthSelector("selectMonth", $(this).data("month"));
				});
			}

			$(this).append("");
			$(this).append("<div id=\"yearSelectorNext\" class=\"monthSelectorButton\" style=\"width: 40px; border-left: 1px solid #97A9B6;\">" + ($(this).data("selectedDate").getFullYear() + 1) + "</div>");
			$("#yearSelectorNext").click(function() {
				$(thisLink).monthSelector("nextYear");
			});
			$(this).append("<div id=\"yearSelectorButtonRight\">&nbsp;</div>");
			$("#yearSelectorButtonRight").click(function() {
				$(thisLink).monthSelector("nextYear");
			});

			return $;
		} else {
			$.error("Method " +  method + " does not exist on jQuery.monthSelector");
		}
	};
})(jQuery);