
var Ctrl_Calendar_Datepicker = Ctrl_Class.extend({
    options: {
        hidden: false,
        autoRender: true,
        nextText: '►',
        prevText: '◄',
        headerFormat: 'F y',
        linkTemplate: null
    },
    
    init: function(element, options) {
        this.options = jQuery.extend(this.options, options);
        
        this.range = [];
        this.target = $(element);
        this.target.addClass('ctrl-datepicker');
        
        this.ID = element.replace(/#/, '');
        
        this.options.hidden? this.target.hide() : this.target.show();
        
        this.now = new Date();
        this.now.setDate(1);
        
       this.options.autoRender? this.render() : function(){};
    },
    
    render: function() {
        this.target.empty();
        var days = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
        
        var table = $(document.createElement('table'));
        
        var dpHeader = $('<thead class="dp-header"><tr></tr></thead>');
        var prevBtn = $(document.createElement('a'))
        .attr({ 'href': '#', 'class': 'dp-prev' })
        .text(this.options.prevText)
        .bind('click', {instance: this},
            function(e) { e.data.instance.prev(); return false; }
        );
        
        var nextBtn = $(document.createElement('a'))
        .attr({ 'href': '#', 'class': 'dp-next' })
        .text(this.options.nextText)
        .bind('click', {instance: this},
            function(e) { e.data.instance.next(); return false; }
        );
        
        this.monthHeader = $('<td colspan="5" class="dp-month">' + this.now.format(this.options.headerFormat) + '</td>');
        
        var dow = $('<tr class="dp-dow"></tr>').html('<td>S</td><td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td>');
        
        dpHeader.find('tr').append($('<td></td>').append(prevBtn))
                    .append(this.monthHeader)
                    .append($('<td></td>').append(nextBtn));
        dpHeader.append(dow);
        
        this.dpBody = $(document.createElement('tbody'));
        this.renderBody();
        
        table.append(dpHeader).append(this.dpBody);
        this.target.append(table);

    },
    
    renderBody: function() {
        this.dpBody.empty();
        
        var d = this.now.clone();
        d.setDate(1);
        
        if(d.getDay() < 3) {
            d.setDate(d.getDate() - 7); // If the first day of the month is early in the week, draw the week before.
        }
        
        d = d.getFirstDayOfWeek();
        
        this.range[0] = d.clone();
        
        var today = new Date();
        
        that = this;
        for(var j=0; j<6; j++) {
            var row = $(document.createElement('tr'));
            
            for(var i=0; i<7; i++) {
                var classes = ['day'];
                
                if(this.now.getMonth() != d.getMonth())
                    classes.push('notInMonth');
                
                if(today.toLocaleDateString() == d.toLocaleDateString())
                    classes.push('today');
                
                var dFormatted = d.format('Ymd');
                var html = d.getDate();
                if(this.options.linkTemplate !== null) {
                    html = '<a href="'+ this.options.linkTemplate.parameterize({date: dFormatted}) +'">'+d.getDate()+'</a>';
                }
                    
                var dE = $(document.createElement('td')).attr({
                    'id': this.ID + '_dp-day-' + dFormatted,
                    'class': classes.join(' ')
                }).html(html);
                /*
                .click(function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    var day = this.id.substr(this.id.lastIndexOf('-')+1);
                    that.trigger('click', [day, this, e]);
                    return false;
                });
                */
                
                dE.appendTo(row);
                d.setDate(d.getDate() + 1);
            }
            
            row.appendTo(this.dpBody);
        }
        
        this.range[1] = d.clone();
    },
    
    showDate: function(date) {
        if(date instanceof Date)
            this.now = date.clone();
        
        this.monthHeader.html(this.now.format(this.options.headerFormat));
        this.renderBody();
    },
    
    prev: function() {
        this.now.setMonth(this.now.getMonth() - 1);
        this.showDate();
    },
    next: function() {
        this.now.setMonth(this.now.getMonth() + 1);
        this.showDate();
    },
    
    show: function() {
        this.target.fadeIn(300);
    },
    hide: function() {
        this.target.fadeOut(300);
    },
    
    disableDay: function(date) {},
    disableDays: function(array) {},
    enableDay: function(date) {},
    enableDays: function(array) {},
    
    highlightDay: function(date, toggle) {
        toggle = toggle || true;
        
        if(toggle == true) {
            this.removeHighlights();
        }
        
        var id = this.ID + '_dp-day-' + date.format('Ymd');
        var el = $('#'+id);
        
        el.addClass('highlight');
    },
    
    
    highlightDayRange: function(date1, date2, toggle) {
        toggle = toggle || true;
        
        if(toggle == true)
            this.removeHighlights();
        
        
        
        if(date1 == date2) {
            if(date1.format('Ym') != this.now.format('Ym'))
                this.showDate(date1);
            var id = this.ID + '_dp-day-' + date1.format('Ymd');
            $('#'+id).addClass('highlight');            
        } else {
            date1 = date1.clone();
            date2 = date2.clone();
            for(date1; date1<=date2; date1.setDate(date1.getDate()+1)) {
                var id = this.ID + '_dp-day-' + date1.format('Ymd');
                
                var elem = $('#'+id);
                if(elem)
                    elem.addClass('highlight');
            }
        }
    },
    
    removeHighlights: function() {
       this.target.find('.day').removeClass('highlight');        
    }
});