Event.observe(window, 'load', function(){
    var most_viewed = new TabContents('most-viewed');
    most_viewed.create();
    var recent = new TabContents('recent-items');
    recent.create();
    // var recent = new TabContents('event-calendar');
    // recent.create();
});

var TabContents = Class.create()
TabContents.prototype = {
    id: null,
    pages: null,
    initialize: function(id) {
        this.id = id;
        this.tabs = new Array();
        this.pages = new Array();
    },
    create: function() {
        if(!$(this.id)) return;
        // selected index
        var sel = 0;
        var tab_elements = $(this.id).getElementsByClassName('tab');
        for(i=0; i<tab_elements.length; i++) {
            if (Element.classNames(tab_elements[i]).include('selected')) {
                sel=i;
                break;
            }
        }
        // tab page
        var p = 0;
        $A($(this.id).getElementsByClassName('tabPage')).each( function(node){
            this.pages[p] = new TabPage(node, p);
            this.pages[p].setStyle((p==sel));
            p++;
        }.bind(this));
        // tab
        var t = 0;
        $A(tab_elements).each( function(node){
            node.index = t;
            node.onclick = function(){ this.selectTab(node.index);return false }.bind(this);
            this.tabs[node.index] = new Tab(node, node.index);
            this.tabs[node.index].setStyle((node.index==sel));
            t++;
        }.bind(this));
    },
    selectTab: function(index) {
        var t = 0;
        $A(this.tabs).each(function(tab){
            tab.setStyle((t==index));
            t++;
        });
        var p = 0;
        $A(this.pages).each(function(page){
            page.setStyle((p==index));
            p++;
        });
    }
}

var TabPage = Class.create();
TabPage.prototype = {
    node: null,
    index: null,
    active: false,
    initialize: function(node, index) {
        this.node = node;
        this.index = index;
    },
    setStyle: function(active){
        this.active = (active);
        if(this.active){
            this.node.style.visibility = 'visible';
            this.node.style.position = '';
        }else{
            this.node.style.visibility = 'hidden';
            this.node.style.position = 'absolute';
        }
    }
}

var Tab = Class.create();
Tab.prototype = {
    node: null,
    index: null,
    active: false,
    initialize: function(node, index) {
        this.node = node;
        this.index = index;
    },
    setStyle: function(active){
        this.active = (active);
        if(this.active){
            this.node.className = 'tab selected'
        }else{
            this.node.className = 'tab'
        }
    }
}
