var TabedControl = Class.create();

TabedControl.prototype = {
    
    initialize: function(tabName, controlName) {
    
        var index = 1;
        
        this.tabName = tabName;
        this.controlName = controlName;
        this.selectedTabIndex = 1;
        
        var tabIndex = 1;
        var startTabIndex = document.cookie.indexOf('tabIndex=');        
        if (startTabIndex != -1)
            tabIndex = document.cookie.substr(startTabIndex + 9, 1);            
                        
        while ($(this.tabName + index) != null) {		    		    		    
		    
		    var control = $(this.controlName + index);		    
		    control.onclick = this.showTab.bindAsEventListener(this);
		    
		    if (index != 1) {
		        var tab = $(this.tabName + index);
		        Element.hide(tab);
		    }
		    		    		    
		    index++;		    
		}		        
		
		this.makeTab(tabIndex);
    },
    
    showTab: function(event) {
        
        var tabElement = Event.element(event);
        var tabId = tabElement.id;
	    var tabIndex = tabId.substr(this.controlName.length);	    
	    
	    this.makeTab(tabIndex);
        
    },
    
    makeTab: function(tabIndex) {
    
        if (tabIndex != this.selectedTabIndex) {
            
            Element.show($(this.tabName + tabIndex));
            Element.hide($(this.tabName + this.selectedTabIndex));
            
            var oldControl = this.findControl($(this.controlName + this.selectedTabIndex));            
            oldControl.className = 'normalcontrol';
            
            var newControl = this.findControl($(this.controlName + tabIndex));
            newControl.className = 'selectcontrol';
            
            this.selectedTabIndex = tabIndex;
            
            document.cookie = 'tabIndex=' + tabIndex + ';';
        }
    },
    
    findControl: function(element) {
        
        while (element.parentNode.className.indexOf('control') == -1) {
                element = element.parentNode;
        }
        
        return element.parentNode;
    }
};