(function ($) {
    $.ajaxCalendar = function (options) {
        var opts = $.extend({
            schedulePath: '',
            startDate: new Date(),
            noEventsOnDay: 'No events on this date',
            noEventsToday: 'No events today',
            noEventsInMonth: 'No events in this month'
        }, options);
        var monthesList = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

        function getDaysInMonth(month, year) {
            return new Date(year, month + 1, 0).getDate();
        }

        function setNoEventsMessage(isToday) {
            if (isToday) {
                $('#no-calendar-events .event-info').html(opts.noEventsToday);
            } else {
                $('#no-calendar-events .event-info').html(opts.noEventsOnDay);
            }
        }
        $('.calendar-event').live('click', function (e) {
            var day = $(this).text();
            $('.event-schedule').addClass('none');
            $('#event-schedule-' + day).removeClass('none');
            $('#calendar').find('.current').removeClass('current');
            $(this).addClass('current');
            e.preventDefault();
        });
        $('.no-calendar-event').live('click', function (e) {
            if ($('#calendar').find('.calendar-event').length) {
                $('.event-schedule').addClass('none');
                $('#no-calendar-events').removeClass('none');
                $('#calendar').find('.current').removeClass('current');
                $(this).addClass('current');
                if ($(this).hasClass('today')) {
                    setNoEventsMessage(true);
                } else {
                    setNoEventsMessage(false);
                }
            }
            e.preventDefault();
        });

        function drawCalendar(date) {
            $('#calendar > .calendar-cap').css('opacity', '0.7').fadeIn(200);
            var month = date.getMonth();
            var year = date.getFullYear();
            if (month == 11) {
                var nextMonth = 0;
                var nextYear = year + 1;
            } else {
                var nextMonth = month + 1;
                var nextYear = year;
            }
            if (month == 0) {
                var prevMonth = 11;
                var prevYear = year - 1;
            } else {
                var prevMonth = month - 1;
                var prevYear = year;
            }
            var daysInMonth = getDaysInMonth(month, year);
            var daysInPrevMonth = getDaysInMonth(prevMonth, prevYear);
            var firstDayOfMonth = new Date(year, month, 1).getDay();
            $.ajax({
                url: opts.schedulePath + '?tmpl=sfs-template&start=' + (month + 1) + '/01/' + year + '&end=' + (nextMonth + 1) + '/1/' + nextYear,
                dataType: 'xml',
                success: function (xml) {
                    $('#calendar-now').html('<span>' + monthesList[month] + ' ' + year + '</span>');
                    $('#calendar-next').html(monthesList[nextMonth] + ' <span class="arr">&raquo;</span>');
                    $('#calendar-prev').html('<span class="arr">&laquo;</span> ' + monthesList[prevMonth]);
                    $('#calendar-body').html('');
                    $('#calendar > .event-schedule').remove();
                    var calendarCounter = daysInMonth + firstDayOfMonth;
                    if (calendarCounter % 7 != 0) {
                        calendarCounter += 7 - (calendarCounter % 7);
                    }
                    for (var z = 1; z <= calendarCounter; z++) {
                        var actualDay = z - firstDayOfMonth;
                        if ((z - 1) % 7 == 0) {
                            var tr = $('<tr></tr>');
                            $('#calendar-body').append(tr);
                        }
                        var td = $('<td></td>');
                        if (actualDay <= 0) {
                            td.html(daysInPrevMonth + actualDay);
                            td.addClass('inactive');
                        } else if (actualDay <= daysInMonth) {
                            td.html('<a href="#" rel="' + actualDay + '">' + actualDay + '</a>');
                            td.attr('id', 'calendar-day-' + actualDay);
                            td.addClass('no-calendar-event');
                        } else {
                            td.html(actualDay - daysInMonth);
                            td.addClass('inactive');
                        }
                        tr.append(td);
                    }
                    $(xml).find('event').each(function () {
                        var eDate = $(this).attr('date');
                        if (eDate) {
                            var eDate = eDate.split('/');
                            var eMonth = parseInt(eDate[0]);
                            var eDay = parseInt(eDate[1]);
                            var eYear = '',
                                eTime = '';
                            if (eDate[2].length > 4) {
                                var eYearTime = eDate[2].split(' ');
                                eYear = parseInt(eYearTime[0]);
                                eTime = eYearTime[1] + ' ' + eYearTime[2];
                            } else {
                                eYear = parseInt(eDate[2]);
                            }
                        }
                        if (month != eMonth - 1) {
                            return;
                        }
                        $('#calendar-day-' + eDay).removeClass('no-calendar-event').addClass('calendar-event');
                        var currentEventId = 'event-schedule-' + eDay;
                        if ($('#' + currentEventId).length == 0) {
                            $('#calendar').append('<div id="' + currentEventId + '" class="event-schedule none"></div>');
                            $('#' + currentEventId).append('<span class="event-date">' + monthesList[eMonth - 1] + ' ' + eDay + ', ' + eYear + '</span>');
                        }
                        var sport = ($(this).attr('sport') != '') ? $(this).attr('sport') : '';
                        var notes = ($(this).attr('notes') != '') ? $(this).attr('notes') : '';
                        var teams = new Array();
                        $(this).find('team').each(function () {
                            teams.push([$(this).attr('name'), $(this).attr('result')]);
                        });
                        var status = '';
                        var neutralSite = $(this).attr('neutral');
                        var statusCode = parseInt($(this).attr('statusCode'), 10);
                        var statusText = $(this).attr('status');
                        if (!isNaN(statusCode)) {
                            switch (statusCode) {
                            case -2:
                                if ($(this).attr('tba') == 'true') {
                                    status = 'TBA';
                                } else {
                                    status = statusText ? statusText : eTime;
                                }
                                break;
                            case 0:
                                status = statusText;
                            default:
                                status = statusText;
                            }
                        }
                        if (typeof teams[0] == 'undefined') {
                            teams[0] = new Array('', '');
                        }
                        if (typeof teams[1] == 'undefined') {
                            teams[1] = new Array('', '');
                        }
                        var eventHTML = '<div class="event-info">' + '<div class="row"><span class="sport">' + sport + '</span></div>' + '<div class="row"><span class="float-right result">' + teams[0][1] + '</span><span class="team">' + teams[0][0] + '</span></div>';
                        if (teams[1][0].length) {
                            eventHTML += '<div class="row"><span class="float-right result">' + teams[1][1] + '</span><span class="team">';
                            if (neutralSite.length) {
                                eventHTML += 'vs '
                            } else {
                                eventHTML += 'at ';
                            }
                            eventHTML += teams[1][0] + '</span></div>';
                            if (neutralSite.length) {
                                eventHTML += '<div class="row"><span class="neutral-site">@ ' + neutralSite + '</span></div>';
                            }
                        }
                        if (status) {
                            eventHTML += '<div class="row"><span class="status">' + status + ((! statusText && $(this).attr('timezone') != undefined) ? (' <span style="font-size:0.8em">(' + $(this).attr('timezone') + ')</span>') : '') + '</span></div>';
                        }
                        var linksHTML = '',
                            linkCollection = $(this).find('link');
                        linkCollection.each(function (i) {
                            linksHTML += '<a href="' + $(this).attr('url') + '">' + $(this).attr('name') + '</a>';
                            if (linkCollection.length != i + 1) {
                                linksHTML += ' | ';
                            }
                        });
                        if (notes.length) {
                            eventHTML += '<div class="row"><span class="note">' + notes + '</span></div>';
                        }
                        eventHTML += '<div class="row links">' + linksHTML + '</div></div>';
                        $('#' + currentEventId).append(eventHTML);
                    });
                    if ($('#calendar .event-schedule').length == 0) {
                        $('#calendar').append('<div id="no-calendar-events" class="event-schedule"><div class="event-info">' + opts.noEventsInMonth + '</div></div>');
                        var todayDate = new Date();
                        if (month == todayDate.getMonth()) {
                            activeDate = todayDate.getDate();
                            $('#calendar-day-' + activeDate).addClass('today');
                        }
                    } else {
                        $('#calendar').append('<div id="no-calendar-events" class="event-schedule none"><div class="event-info"></div></div>');
                        var activeDate;
                        var todayDate = new Date();
                        if (month == todayDate.getMonth()) {
                            activeDate = todayDate.getDate();
                            $('#calendar-day-' + activeDate).addClass('today');
                        } else {
                            activeDate = 1;
                        }
                        if ($('#event-schedule-' + activeDate).length) {
                            $('#event-schedule-' + activeDate).removeClass('none');
                        } else {
                            if (month == todayDate.getMonth()) {
                                $('#no-calendar-events').removeClass('none');
                                setNoEventsMessage(true);
                            } else {
                                activeDate = $('#calendar .calendar-event:first').children('a').attr('rel');
                                $('#event-schedule-' + activeDate).removeClass('none');
                            }
                        }
                        $('#calendar-day-' + activeDate).addClass('current');
                    }
                    $('#calendar-prev').unbind('click').click(function () {
                        drawCalendar(new Date(prevYear, prevMonth, 1));
                        return false
                    });
                    $('#calendar-next').unbind('click').click(function () {
                        drawCalendar(new Date(nextYear, nextMonth, 1));
                        return false
                    });
                    $('.calendar-cap').fadeOut(400, function () {
                        $(this).hide()
                    });
                    $('#calendar').show();
                },
                error: function () {
                    console.log('ajax calendar : bad schedule url');
                }
            });
        }
        drawCalendar(opts.startDate);
    }
})(jQuery);
