/**
 *  Awards paging functionality
 */
Pace.Awards = Class.create({
    // Constructor
    initialize: function(type)
    {
        this.parent = $(type.id); // area that is getting pagination
        if (this.parent == null) return; // make sure it exists
    
        // set up methods
        this.buildCache(type.paginationLabel);
        this.displayPage(0);
        this.insertHTML();
        this.buildPagination();
        this.attachEvents();
    },
    
    // Private Methods
    buildCache: function(paginationLabel)
    {
        this.pages = this.parent.select('div.page');
        this.pageHash = {};
        this.container = new Element('div', {className: 'pagination'});
        this.content = new Element('strong').insert(paginationLabel);
    },
    
    attachEvents: function()
    {
        this.content.observe('click', this.onPaginationClick.bind(this));
    },
    
    onPaginationClick: function(event)
    {
        Event.stop(event); // stop default click event
        
        var element = Event.element(event);
        
        // make sure link was clicked
        if (element.tagName != 'A') return;
        
        // make sure clicked link loses focus
        $(element).blur();
        // remove 'active' class name from prev
        this.content.select('a.active')[0].removeClassName('active');
        // add 'active' class name to current
        element.addClassName('active');
        
        this.displayPage(element.hash.substr(1));
    },
    
    insertHTML: function()
    {
        this.container.insert(this.content);
        this.parent.insert(this.container);
    },
    
    displayPage: function(page)
    {
        this.pages.invoke('hide');
        
        if (page == 0)
        {
            this.pages[0].show();
            return;
        }
        this.pageHash[page].show();
    },
    
    buildPagination: function()
    {
        var title, link;
        this.pages.each(function(page, i){
            title = page.select('h3')[0].select('strong')[0].innerHTML;
            
            this.pageHash[title] = page;
            
            link = new Element('a', {href: '#' + title, className: (i == 0) ? 'active' : ''}).update(title);
            this.content.insert((i == 0) ? '&nbsp;' : '&nbsp;| ').insert(link);
        }.bind(this));
    }
});

Pace.Awards.Type = [
    {id: 'fiery-foods', paginationLabel: 'Fiery Food Challenge:'},
    {id: 'scovie', paginationLabel: 'Scovie Awards:'}
];

document.observe('dom:loaded', function(){
    $A(Pace.Awards.Type).each(function(type){
        new Pace.Awards(type);
    });
});
