CBCR3.namespace("CBCR3.TabPanel");

CBCR3.TabPanel.TabPanel = Class.create({

	container:null,
	collection:null,
	selected:null,
	tabClass:null,

	initialize:function(options)
	{
		this.container = $(options.container);		
		this.tabClass = (options.tabClass || this.tabClass);
		this.activateTabs();
		this.hideAllContent();
		this.selectFirst();
        this.setWidths();
	},	
	
	activateTabs:function()
	{		
		var self = this;		
		
		this.getCollection().each(function(item){
			if(!item.content.empty())
				item.tab.observe("click", self.onTabClick.bind(self));            
			else
				item.tab.addClassName("disabled");				
		});
	},

    setWidths:function()
    {
        var items = this.getCollection();
        var tabWidth = Math.round(this.container.getWidth()/items.length);

        for(var i = 0; i < items.length; i++)
        {
           items[i].tab.setStyle({
               width:(tabWidth-1) + "px"
           });
        }
        
        items.last().tab.setStyle({
            width:(tabWidth -1)+"px",
            marginRight:"0"
        });
    },        
		
	
	selectFirst:function()
	{
		this.setSelected( this.getCollection()[0].tab );
	},
	
    onTabClick:function(event) 
	{
        this.hideAllContent();
        this.clearAllTabs();
        this.setSelected(event.target);
    },
	
	setSelected:function(element)
	{
        $(element.readAttribute("for")).setStyle({display: "block"});
		element.addClassName("selected");
		
	},
    
    clearAllTabs:function()
    {
        this.getCollection().each(function(item){
			item.tab.removeClassName("selected");
        });
    
    },

    hideAllContent:function()
    {
        this.getCollection().each(function(item) {
            if(item.content)
            {
                item.content.setStyle({ display: "none" });
                var viewMoreButton = item.content.down(".viewMoreButton");
                if(viewMoreButton)
                {
                    viewMoreButton.observe("click", function(event){
                        event.target.up().select("li").each(function(item){
                            item.setStyle({display:"block"});
                        });
                        event.target.remove();
                    });
                }
            }
        });
    },

	
	getCollection:function()
	{
		if (this.collection == null) 
			this.collection = this.populateCollection();		
		return this.collection;
	}, 
	
	populateCollection:function()
	{
		var tabItems = this.container.select("." + this.tabClass);
			
		var collection = new Array();
		
		for(var i = 0; i < tabItems.length; i++)
		{
			var tab = tabItems[i]; 
			var content = $(tab.readAttribute("for"));            
			
			collection[i] = {
				tab: tab, 
				content: content
			};
		}
		
		return collection;			
	},

    onShowAllClick:function(event)
    {

    }
});
