Ext.onReady(function(){
    initializeTabGroups();
});

function initializeTabGroups(){
    var headerGroups = Ext.select('.tabHeader').elements;
    var contentGroups = Ext.select('.tabContent').elements;
    var i;
    
    if(headerGroups.length !== contentGroups.length){
        //something is wrong, because there's more tab sets than content sets on the page
        return;
    }
    
    if (headerGroups) for( i = 0 ; i < headerGroups.length ; i++){
        var headerGroup = headerGroups[0];  // current tab group
        var contentGroup = contentGroups[0];  // current tab group
        
        //tabs and content divs in this tab group
        var tabsElementArray = Ext.select('li',true,headerGroup).elements;
        var contentsElementArray = Ext.select('div.contentSection',true,contentGroup).elements;
        
        //map on click for the tab li's to the appropriate select function
        hookupTabs(tabsElementArray, contentsElementArray);
    }
    
    
}

function hookupTabs(tabsElementArray, contentsElementArray){
    var i;
    //go through this tabgroup's tabs and map out the on clicks
    if(tabsElementArray) for( i = 0 ; i < tabsElementArray.length ; i++){
        var tab = tabsElementArray[i];
        var content = contentsElementArray[i];
        
        //just believe in the voodoo that happens next
        tab.on('click', function(currentContent){
            return function(){
                selectTab(tabsElementArray, contentsElementArray, this, currentContent);
            };
        }(content));
    }
}

function selectTab(tabsElementArray, contentsElementArray, currentTab, currentContent) {
    var j;
    //unselect everything else first
    for( j = 0 ; j < tabsElementArray.length ; j++){
        tabsElementArray[j].removeClass('current');
        contentsElementArray[j].removeClass('current');
    }

    //select the tab and show the content
    currentTab.addClass('current');
    currentContent.addClass('current');
}
