/*

Author:			Vinh Do
Date:			Sept 15, 2011
Description:	Create a mini calendar to show events

*/

(function($) {

    $.fn.mini_calendar = function(p) {

        var _dayShort = p && (p.dayShort != null) ? p.dayShort : ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
		    _monthNames = p && (p.monthNames != null) ? p.monthNames : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			_currentDate = p && (p.currentDate != null) ? p.currentDate : new Date(),
			_startDay = p && (p.startDay != null) ? p.startDay : 0,
			_source = p && (p.source != null) ? p.source : "",
			_url = p && (p.url != null) ? p.url : "";

        var _container = $(this),
			_month = _currentDate.getMonth(),
			_year = _currentDate.getFullYear(),
			_left = $("<span>").attr({ "id": "left" }).css({ "cursor": "pointer", "padding-right": "5px" }).append("&lt;&lt;"),
			_center = $("<span>").attr({ "id": "center", "class":"month" }).css({ "cursor": "pointer" }).append(_monthNames[_month] + "&nbsp;" + _year),
			_right = $("<span>").attr({ "id": "right" }).css({ "cursor": "pointer", "padding-right": "5px" }).append("&gt;&gt;"),
			_body = $("<tbody>");

        var _days = ['0', '1', '2', '3', '4', '5', '6'];

        var _startDate = new Date(_year, _month, 1),
			_endDate = new Date(_year, _month + 1, 0);

        // build calendar header
        _container.empty().append(
			$("<table>").attr({ "width": "100%" }).append(
				$("<caption>").append(
					$("<table>").attr({ "width": "100%" }).append(
						$("<tr>").append(
							$("<td>").attr({ "align": "left" }).append(
								_left
							)
						).append(
							$("<td>").append(
								_center
							)
						).append(
							$("<td>").attr({ "align": "right" }).append(
								_right
							)
						)
					)
				)
			).append(
				$("<colgroup>").append(
					$("<col>").addClass("weekend")
				).append(
					$("<col>").attr({ "span": "5" }).addClass("weekday")
				).append(
					$("<col>").addClass("weekend")
				)
			).append(
				$("<thead>").append(
					$("<tr>").append(
						$("<th>").append(_dayShort[0])
					).append(
						$("<th>").append(_dayShort[1])
					).append(
						$("<th>").append(_dayShort[2])
					).append(
						$("<th>").append(_dayShort[3])
					).append(
						$("<th>").append(_dayShort[4])
					).append(
						$("<th>").append(_dayShort[5])
					).append(
						$("<th>").append(_dayShort[6])
					)
				)
			).append(_body)
		);

        // load calendar
        LoadCalendar();

        // bind left / right click
        _left.click(function() {
            if (_month <= 0) {
                _month = 11;
                _year--;
            }
            else {
                _month--;
            }
            UpdateCalendarInfo();
        });
        _right.click(function() {
            if (_month >= 11) {
                _month = 0;
                _year++;
            }
            else {
                _month++;
            }
            UpdateCalendarInfo();
        });
        _center.click(function() {
            var param = "startDate=" + Format(_startDate, '/') + "&endDate=" + Format(_endDate, '/');
            if ($.trim(_url) != "") {
                document.location = (_url + ((_url.indexOf('?') < 0) ? "?" : "&") + param);
            }
            //		    alert(param);
        });

        function Format(dateElement, separator) {
            var m = dateElement.getMonth() + 1;
            var d = dateElement.getDate();
            var y = dateElement.getFullYear();

            return (m < 10 ? '0' + m : m) + separator + (d < 10 ? '0' + d : d) + separator + y;
        }

        function LoadCalendar() {

            var dateWithEvent = [];

            if ($.trim(_source) != "") {
                $.ajax({
                    url: _source,
                    async: false,
                    dataType: 'json',
                    contentType: "application/x-www-form-urlencoded",
                    data: { startDate: Format(_startDate, '/'), endDate: Format(_endDate, '/') },
                    type: "POST",
                    error: function() {
                        //alert("error");
                    },
                    success: function(data) {
                        var i = 0;
                        // get the dates with 'HasEvent' boolean flag = true
                        $.each(data, function(index, item) {
                            if (item.HasEvent) {
                                dateWithEvent[i] = item.EventDate;//.format;
                                i++;
                            }
                        });
                    }
                });
            }


            var startDate = new Date(_year, _month, (_startDate.getDate() - (_startDate.getDay() - _startDay))),
				endDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + 41);

            var tmpDate = startDate;
            _body.empty().append($("<tr>"));
            var trTag = _body.children("tr:last");
            for (i = 0; tmpDate.getTime() < endDate.getTime(); i++) {

                if (i > 0) {
                    tmpDate = new Date(tmpDate.getFullYear(), tmpDate.getMonth(), tmpDate.getDate() + 1);
                    if ((i % _dayShort.length) <= 0) {
                        _body.append($("<tr>"));
                        trTag = _body.children("tr:last");
                    }
                }

                var tdTags = $("<td>");

                //alert(dateWithEvent);
                if (tmpDate.getMonth() == _month) {

                    var compareDate = Format(tmpDate, '/'); // format the date to match the dateWithEvent[] structure
                    //alert(compareDate);
                    tdTags.attr({ "id": tmpDate.getMonth() + '_' + tmpDate.getDate() }).append(tmpDate.getDate());
                    if ($.inArray(compareDate, dateWithEvent) >= 0) {
                        // if the calendar date exists in dateWithEvent[]
                        trTag.append(
							tdTags.css({ "cursor": "pointer" }).addClass("day daywithevent").click(function() {
							    if ($.trim(_url) != "") {
							        var date = new Date(_year, $(this).attr("id").split("_")[0], $(this).attr("id").split("_")[1]);
							        var param = "StartDate=" + Format(date, '/') + "&EndDate=" + Format(date, '/');
							        if ($.trim(_url) != "") {
							            document.location = (_url + ((_url.indexOf('?') < 0) ? "?" : "&") + param);
							        }
							    }
							    //								alert(new Date(_year, _month, $.trim($(this).text())));
							})
						);
                    }
                    else {
                        trTag.append(
							tdTags.css({ "cursor": "default" }).addClass("day")
						);
                    }
                }
                else {
                    trTag.append(tdTags);
                }
            }
        }

        function UpdateCalendarInfo() {
            _center.empty().append(_monthNames[_month] + "&nbsp;" + _year);
            _startDate = new Date(_year, _month, 1);
            _endDate = new Date(_year, _month + 1, 0);
            LoadCalendar();
        }
    };

})(jQuery);

