﻿(function ($) {

    function calendarWidget(el, params) {

        var now = new Date();
        var _dts = { year: now.getYear() + 1900, month: now.getMonth(), day: null };
        if ($(el).attr('month') != undefined) {
            _dts.month = parseInt($(el).attr('month')) - 1;
            _dts.year = parseInt($(el).attr('year'));
        }
        var opts = {
            month: _dts.month,
            year: _dts.year,
            day: _dts.day,
            showNav: null, /* 'left', 'right', 'both'*/
            navFN: null, /* fn for navigation buttons, accepts 1 parameter: increment (+n|-n)*/
            restrictYear: false,
            backSelect: true,
            tariffs: false, /* adds 3 span.ctInternal after span.day for days with numbers */
            legenda: false, /* adds span.lOption after span.day for days with legenda support */
            dayVeil: false, /* adds span.dayVeil before span.day for colored days support */
            bindedTo: null,
            backImgCss: 'bkwdButton',
            fwdImgCss: 'frwdButton',
            closeImgCss: 'crossClose',
            dateToHighlite: now,
            self: this /* element, calendar belogns to */
        };

        $.extend(opts, params);

        month = i = parseInt(opts.month);
        year = parseInt(opts.year);
        var m = 0;
        var table = '';
        if (opts.showNav != null) {
            table += ('<div class="calendar-current-month-nav" style="text-align:center">');
            if (opts.showNav == 'both') {
                table += ('<img name="closeDP" style="float:right;width:10px;margin:3px 3px" src="/images/spacer.gif" class="' + opts.closeImgCss + '"></a>');
                table += ('<img name="nextMonth" style="float:right" src="/images/spacer.gif" class="' + opts.fwdImgCss + '"></a>');
                if (!(!opts.backSelect && new Date().getMonth() == month && new Date().getFullYear() == year)) {
                    table += ('<img name="prevMonth" style="float:left" src="/images/spacer.gif" class="' + opts.backImgCss + '"></a>');
                }
            }
            else if (opts.showNav == 'left') {
                table += ('<a name="prevMonth" style="float:left;display:block" class="' + opts.backImgCss + '"></a>');
            }
            else if (opts.showNav == 'right') {
                table += ('<a name="nextMonth" style="float:right;display:block" class="' + opts.fwdImgCss + '"></a>');
            }
            table += ('<span class="calendar-current-month-header" >' + monthNames[month] + '&nbsp;' + year + '</span>');
            table += ('</div>');
        }
        else {
            table += ('<span class="calendar-current-month-header" style="text-align:center">' + monthNames[month] + ' ' + year + '</span>');
        }
        table += ('<table cellspacing="0" cellpadding="0" class="calendar-month" id="calendar-month' + i + ' " cellspacing="0">');

        table += '<tr>';

        for (d = 0; d < 7; d++) {
            table += '<th class="weekday">' + dayNames[d] + '</th>';
        }

        table += '</tr>';

        var days = getDaysInMonth(month, year);
        var firstDayDate = new Date(year, month, 1);
        var firstDay = firstDayDate.getDay() - 1;
        firstDay = firstDay == -1 ? 6 : firstDay;

        var prev_m = month == 0 ? 11 : month - 1;
        var prev_y = prev_m == 11 ? year - 1 : year;
        var prev_days = getDaysInMonth(prev_m, prev_y);
        firstDay = (firstDay == 0 && firstDayDate) ? 7 : firstDay;

        var i = 0;
        for (j = 0; j < 42; j++) {
            var dayContent = '';
            if (opts.dayVeil) dayContent = '<span class="dayVeil">&nbsp;</span>' + dayContent;
            if (opts.tariffs) {
                dayContent += '<br/>';
                dayContent += '<span class="ctInternal lotmentBooking">&nbsp;</span>';
                dayContent += '<span class="ctInternal specTariff">&nbsp;</span>';
                dayContent += '<span class="ctInternal baseTariff">&nbsp;</span>';
            }
            if (opts.legenda) {
                dayContent += '<span class="lOption">&nbsp;</span>';
                dayContent += '<span class="lOption">&nbsp;</span>';
                dayContent += '<span class="lOption">&nbsp;</span>';
                dayContent += '<span class="lOption">&nbsp;</span>';
                dayContent += '<span class="lOption">&nbsp;</span>';
            }

            if ((j < firstDay)) {
                table += ('<td class="other-month"><span class="day">' + (prev_days - firstDay + j + 1) + '</span>' + dayContent + '</td>');
            } else if ((j >= firstDay + getDaysInMonth(month, year)) || (!opts.backSelect && (new Date(year, month, i + 1) < new Date(now.getFullYear(), now.getMonth(), now.getDate())))) {
                i = i + 1;
                table += ('<td class="other-month"><span class="day">' + i + '</span>' + dayContent + '</td>');
            } else {/*current month*/
                var dayNumber = (j - firstDay + 1);
                if (opts.tariffs) {
                    dayContent = '<span class="day tariffsDay">' + dayNumber + '</span>' + dayContent;
                }
                else if (opts.legenda) {
                    dayContent = '<span class="day legendDay">' + dayNumber + '</span>' + dayContent;
                }
                else {
                    dayContent = '<span class="day">' + dayNumber + '</span>' + dayContent;
                }
                highlited = new Date(year, month, dayNumber).toDateString() == opts.dateToHighlite.toDateString();
                table += ('<td class="current-month cmTariff" selectable="yes" ' + (highlited ? 'style="border:solid 1px #000"' : '') + ' id="cmDay_' + year + '-' + (month + 1) + '-' + dayNumber + '">' + dayContent + '</td>');
            }
            if (j % 7 == 6) table += ('</tr>');
        }

        table += ('</table>');

        el.html(table);
        var navFN = {
            incr: opts.navFN || function (incr) {
                var s, e;
                if (incr > 0) { s = 0; e = 11; }
                else { s = 11; e = 0; }
                if (opts.month == s) {
                    opts.month = opts.restrictYear ? opts.month : e;
                    opts.year = opts.restrictYear ? opts.year : opts.year + incr;
                } else { opts.month = opts.month + incr; }
                calendarWidget(el, opts);
            }
        };
        if (opts.showNav != null) {
            $('.calendar-current-month-nav [name="prevMonth"]', el).unbind('click').bind('click', function () {
                navFN.incr(-1);
            });
            $('.calendar-current-month-nav [name="nextMonth"]', el).unbind('click').bind('click', function () {
                navFN.incr(1);
            });
        }
        this.mOver = function () {
            $(this).attr('class', ($(this).attr('class') + ' dayHover'));
        };
        this.mOut = function () {
            $(this).attr('class', $(this).attr('class').replace(' dayHover', ''));
        };
        this.dayPicked = function (event) {
            event.stopPropagation();
            var datePicker = $(this).closest('.date-picker');
            var datePicked = $(this).attr('id').split('_')[1];
            var bindedTo = opts.bindedTo == null ? datePicker.prev() : opts.bindedTo;
            if (bindedTo.attr('value') != undefined) {
                bindedTo.attr('value', datePicked);
            } else if (typeof datePicked == "string" && (i = datePicked.indexOf('<')) >= 0 && datePicked.indexOf('>') > i) {
                bindedTo.html(datePicked);
            } else {
                bindedTo.text(datePicked);
            }
            if (typeof (opts.onDayClick) == 'function') opts.onDayClick.call(opts.self, datePicked);
            datePicker.remove();
        };
        if (opts.onDayClick) {
            $('.current-month', el).bind('mousedown', this.dayPicked);
            $('.current-month', el).bind('mouseover', this.mOver).bind('mouseout', this.mOut);
        }
    }

    function getDaysInMonth(month, year) {
        var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if ((month == 1) && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
            return 29;
        } else {
            return daysInMonth[month];
        }
    }


    // jQuery plugin initialisation
    $.fn.calendarWidget = function (params) {
        calendarWidget(this, params);
        return this;
    };

})(jQuery);
