var EventsFilter = Class.create();
EventsFilter.prototype = {
    initialize : function () {
        this.getKindRegex = /=([\w]+)$/;
        this.filterElement = $('eventsFilter');
        if (!this.filterElement) { return; }
        this.blocks = $A($$('.event'));
        this.filterLinks = $A($$('ul.filter a'));

        this.boundedProcessClick = this.processClick.bindAsEventListener(this);
        this.filterElement.observe('click', this.boundedProcessClick);
    },
    
    processClick : function (e) {
        var el = Event.element(e);
        if (el.match('a')) {
            var result = this.getKindRegex.exec(el.href);
            if (result) {
                this.makeLinkActive(el);
                this.showBlocksByKind(result[1]);
                this.showDaySeparator();
            }
        }
    },
    
    makeLinkActive : function (link) {
        this.filterLinks.each(function (filterLink) {
            if (filterLink == link) {
                filterLink.addClassName('active');
            } else {
                filterLink.removeClassName('active');
            }
        });
    },
    
    showBlocksByKind : function (kind) {
        this.blocks.each(function (block) {
            if (kind == 'all' || block.hasClassName(kind)) {
                block.show();
            } else {
                block.hide();
            } 
        });        
    },
    
    showDaySeparator : function () {
        $$('.separateDay').each(function (el) {
            var blocks = [];
            var firstChild = el.down();
            if (firstChild.match('.event')) { blocks.push(firstChild); }
            firstChild.siblings().each(function (sibling) {
                if (sibling.match('.event')) { blocks.push(sibling); }
            });
            var visible = false;
            blocks.each(function (block) {
                visible |= block.visible();
            });
            if (!visible) {
                el.hide();
            } else {
                el.show();
            }
        });
    }
};

var eventsFilter = new EventsFilter();
