﻿(function($) {
    function Right(str, n) {
        if (n <= 0)
            return "";
        else if (n > String(str).length)
            return str;
        else {
            var iLen = String(str).length;
            return String(str).substring(iLen, iLen - n);
        }
    }

    function calendarWidget(el, params) {

        var now = new Date();
        var thismonth = now.getMonth();
        var thisyear = now.getFullYear();
        var thisday = now.getDate();
        //alert(thisyear + '/' + thismonth + '/' + thisday);
        var opts = {
            month: thismonth,
            year: thisyear
        };

        $.extend(opts, params);

        var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        month = i = parseInt(opts.month);
        year = parseInt(opts.year);
        var m = 0;
        var table = '';

        table += ('<table class="calendar-month main" ' + 'id="calendar-month' + i + ' " cellspacing="0"  cellpadding="5">');
        table += ('<tr>');
        table += ('<td class="header"  colspan="7">');
        table += ('<table class="header" width="100%" border="0" cellspacing="0" cellpadding="0">');
        table += ('<tr>');
        table += ('<td align="left"><div class="btn_prev"><a href="#" class="PreviousMonth_"> <img src="images/spacer.gif" width="13" height="30" border="0"/></a></div></td>');
        table += ('<td align="center">' + monthNames[month] + ' ' + year + '</td>');
        table += ('<td align="right"><div class="btn_next"><a href="#" class="NextMonth_"><img src="images/spacer.gif" width="13" height="30" border="0"/></a></div></td>');
        table += ('</tr>');
        table += ('</table>');
        table += ('</td>');

        table += '</tr>';
        table += '<tr>';
        for (d = 0; d < 7; d++) {
            table += '<th class="weekday header">' + dayNames[d] + '</th>';
        }

        table += '</tr>';

        var days = getDaysInMonth(month, year);
        var firstDayDate = new Date(year, month, 1);
        var firstDay = firstDayDate.getDay();

        var prev_days = getDaysInMonth(month, year);
        var firstDayDate = new Date(year, month, 1);
        var firstDay = firstDayDate.getDay();

        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++) {

            if ((j < firstDay)) {
                table += ('<td class="other-month tdClass">' + (prev_days - firstDay + j + 1) + '</td>');
            } else if ((j >= firstDay + getDaysInMonth(month, year))) {
                i = i + 1;

                table += ('<td class="other-month tdClass ">' + i + '</td>');
            } else {
                var days = (j - firstDay + 1);

                var month_ = month + 1;

                if (days == thisday && month == thismonth && year == thisyear) {
                    table += ('<td class="tdClass today current-month day' + (j - firstDay + 1) + '">' + (j - firstDay + 1) + '</td>');

                }
                else {
                    table += ('<td class="tdClass current-month day' + (j - firstDay + 1) + '">' + (j - firstDay + 1) + '</td>');
                }

            }
            if (j % 7 == 6) table += ('</tr>');
        }

        table += ('</table>');


        el.html(table);

        //===============================
        //Checking which day have event
        //===============================
        var month_ = month + 1;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "../Default3.aspx/Get_Record",
            data: "{'Month':'" + month_ + "','Year':'" + year + "'}",
            dataType: "json",
            success:
                            function(msg) {

                                if (msg.d == '0') {
                                    //alert(days);

                                }
                                else {
                                    var count = msg.d.split("^").length;

                                    var item = msg.d.split("^");


                                    var e;
                                    for (e = 0; e < count; e++) {
                                        // alert(item[e]);
                                        $('.day' + item[e]).addClass('eventDate date_has_event');
                                        $('.day' + item[e]).addClass('ClickD' + item[e]);
                                        var PopEvent = "<span style='display: none;' class=dd" + item[e] + ">" + item[e] + "</span>";
                                        $(PopEvent).appendTo($('.day' + item[e]));
                                        var click = $('.ClickD' + item[e]);
                                        var trigger = $(this);

                                        MouseClick(item[e], month_, year);

                                        /* $([trigger.get(0), click.get(0)]).click(function() {
                                       
                                        //                                            var Day_ = $('.dd' + item[e]);
                                        //                                            alert(Day_);
                                        //                                            var NowDate = $('.Date');
                                        //                                            var abc = Day_.get(0).value;
                                        //                                            alert(abc);
                                        });*/
                                    }


                                }
                            },
            error:
                      function(XMLHttpRequest, textStatus, errorThrown) {
                          alert('error get data!');
                      }
        });



        //===============================
        //Build Pop Up Event
        //===============================

        function MouseClick(day, Month, Year) {

            var click = $('.ClickD' + day);
            click.bind('click', function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "../Default2.aspx/Get_Record",
                    data: "{'Day':'" + day + "','Month':'" + month_ + "','Year':'" + Year + "'}",
                    dataType: "json",
                    success:
                      function(msg) {
                          if (msg.d == '0') {
                          }
                          else {
                              var NowDate = $('.Date');

                              var RealDay = Right(day, 2);
                              var popup_ = $('.pop_UpCalander');
                              popup_.css({ 'display': 'none' });
                              popup_.slideUp("slow");
                              var Containt = $('.Containt');
                              Containt.html('');
                              var item = msg.d.split("^");
                              var PopEvent = item[1];
                              NowDate[0].innerHTML = RealDay + " " + monthNames[Month-1] + " " + Year;
                              $(PopEvent).appendTo(Containt);
                              popup_.slideDown("slow");
                              popup_.css({ 'display': 'block' });
                          }
                      },
                    error:
                      function(XMLHttpRequest, textStatus, errorThrown) {
                          alert('error get data!');
                      }
                });
            });
        }

        $('a.NextMonth_').bind('click', function() {
            if (params.month == 11) {
                params.month = 0;
                params.year = params.year + 1;

            }
            else {
                params.month = params.month + 1;
            }
            calendarWidget(el, params);
            var popup_ = $('.pop_UpCalander');
            popup_.slideUp("fast");
            popup_.css({ 'display': 'none' });

            return false;
        });
        $('a.PreviousMonth_').bind('click', function() {
            if (params.month == 0) {
                params.month = 11;
                params.year = params.year - 1;
            }
            else {
                params.month = params.month - 1;
            }
            calendarWidget(el, params);
            var popup_ = $('.pop_UpCalander');
            popup_.slideUp("fast");
            popup_.css({ 'display': 'none' });
            return false;
        });


    }

    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);
        var j;


        return this;
    };

})(jQuery);
