/* Datepicker plugin
------------------------------------------------------------------------------------------------ */

(function($){
    $.fn.datepicker = function(options){

        var now = new Date();

        var defaults = {
            hideInput           : false,
            disablePast         : true,
            disableWeekend      : false,
            month               : now.getMonth(),
            year                : now.getFullYear(),
            format              : 'd.m.y',
            speed               : 200
        };

        var options     = $.extend(defaults, options),
            dp_count    = 0;

        return this.each(function() {

            var op  = options,
                el  = $(this),
                mp  = ( $(this).parent().is('label')) ? $(this).parent() : $(this);

            dp_count++;

            // Hide label

            $('label[for=' + $(el).attr('id') + ']').hide();

            // Generate main .datepicker

            if (op.hideInput == true) {
                el.hide();
            }

            $('<div id="dp'+dp_count+'" class="datepicker"><h2>init</h2><a class="dpprev" href="#" title="'+back+'">'+back+'</a><a class="dpnext" href="#" title="'+next+'">'+next+'</a><table><thead><tr></tr></thead><tbody></tbody></table></div>').insertAfter(mp);

            var datepicker = $("#dp"+dp_count);

            $.each(days_list, function(index, value) {
                $("thead tr", datepicker).append('<th>' + value + '</th>')
            });

            //Measure fill

            for (t=0;t<=6;t++) {
                $("table", datepicker).append("<tr><td class='dpday dpclickable active'>19</td><td class='dpday dpclickable'>20</td><td class='dpday dpclickable'>21</td><td class='dpday dpclickable'>22</td><td class='dpday dpclickable'>23</td><td class='dpday'>24</td><td class='dpday'>25</td></tr>");
            }

            // CSS settings
            
            datepicker.css({
                'width'         : $('table', datepicker).outerWidth() + 'px',
                'overflow'      : 'hidden'
            });

            // Fill init selected month

            fillDateTable(datepicker, el, op.month, op.year, op);

            // Generate the buttons

            $('a', datepicker).click(function(event) {
                event.preventDefault();

                mont        = jQuery.inArray($("h2 .dpmonth", datepicker).html(), mont_list);
                year        = $("h2 .dpyear", datepicker).html();
                direction   = $(this).hasClass("dpprev");

                if (direction) {
                    mont--;
                }
                else {
                    mont++;
                }

                if (mont > 11) {
                    mont = 0;
                    year++;
                }

                if (mont < 0) {
                    mont = 11;
                    year--;
                }

                // Refill in selected direction

                $("table", datepicker).stop(true, true).animate({
                    'marginLeft' : (direction) ? '100%' : '-100%'
                }, op.speed, function() {
                    fillDateTable(datepicker, el, mont, year, op);
                    $("table", datepicker).css({
                        'marginLeft' : (direction) ? '-100%' : '100%'
                    }).animate({
                        'marginLeft' : 0
                    }, op.speed);
                });

            });
        });

        // Fill the .datepicker with data
        function fillDateTable(datepicker, el, mont, year, op){
            $("h2", datepicker).html('<span class="dpmonth">'+mont_list[mont] +'</span> <span class="dpyear">'+ year+'</span>');
            $("tbody tr", datepicker).remove();
            $("tbody", datepicker).append( generateMonthTable(mont, year, op));
            $('tbody td.dpclickable', datepicker).click(function(){
                var format = op.format;
                format = format.replace('m', ((jQuery.inArray($("h2 .dpmonth", datepicker).html(), mont_list))+1));
                format = format.replace('d', $(this).html());
                format = format.replace('y', $("h2 .dpyear", datepicker).html());
                el.val(format)
                $('tbody td.active', datepicker).removeClass("active");
                $(this).addClass("active");
            });
        }

        // Generate the tbody
        function generateMonthTable(mont, year, op){
            var date = new Date(year, mont)
            var days = date.getDate();
            var firs = (date.getDay());
            if(firs == 0) firs = 7; // begin with Sundays
            var last = (new Date((new Date(year, mont+1,1))-1)).getDate();
            var now = new Date();
            var html = "<tr>";
            var d = 1;
            for(c=1;c<= Math.ceil(((last+(firs-1))/7))*7 ;c++){
                var tdclass = '';
                var dday = new Date(year, mont, d)  
                var isPast = now>dday;  
                var isWeekend = !(!((c % 7 == 0) || ((c+1) % 7 == 0)));
                if(c>=firs && d<=last) tdclass += "dpday";
                if(isWeekend && d<=last) tdclass += " dpweekend";
                if(isPast) tdclass += " dppast";
                
                if(!(isPast && op.disablePast) && !(isWeekend && op.disableWeekend) && c>=firs && d<=last)
                   tdclass += " dpclickable";
                if(mont==now.getMonth() && year==now.getFullYear() && d==now.getDate() && c>=firs) tdclass += " dptoday";
                html += "<td class='"+tdclass+"'>";
                if(c>=firs&&d<=last) html += d++;
                html += "</td>";
                if (c % 7 == 0 && d<=last) html += "</tr><tr>";
            }
        return html + "</tr>";
        }
    };
})(jQuery);
