var Tabs = Class.create({
	initialize:function(id,selTabNo){
		if( $(id) == null ) return;
		this.id = id;
		this.selTabNo = ( selTabNo == null )?0:selTabNo;
		this.tabGroup = $( this.id );
		if( this.tabGroup == null ) return;
		if( $( 'ulTabs' + this.id ) != null ) return;//Tabs exist
		var tabHTML = "";
		if( Tabs.list == null ) Tabs.list = {};
		Tabs.list[ this.id ] = this;
		var selTabNo = this.selTabNo;
		$A( this.tabGroup.immediateDescendants() ).each(function(e,i){
		
			var paneId = e.identify();//Get the pane Id - and assign one if required
			var pane = $(paneId);
			pane.addClassName("tabPane");
			var tabName = pane.readAttribute("tabName");
			if( tabName == null ) tabName = "Tab " + (i+1);
			$( pane ).style.display = (i==0)?"block":"none";
			var liId = paneId + "tab";
			tabHTML = tabHTML + '<li id="' + liId + '"';
			tabHTML = tabHTML + ' class="tab' + (i==0?' first':'') + (i==selTabNo?' sel':'') + '"';
			tabHTML = tabHTML + '>';
			tabHTML = tabHTML + '<a href="#" onclick="Tabs.list[\'' + id + '\'].selTab(' + i + ');return false;">';
			tabHTML = tabHTML + tabName.escapeHTML();
			tabHTML = tabHTML + '</a></li>';
			
		}
		);

		tabHTML = '<ul class="tabnav" id="ulTabs' + this.id + '">' + tabHTML + '</ul>';
		this.tabGroup.insert({top:tabHTML});
	},
	selTab:function(tabNo){
		if( tabNo == this.selTabNo ) return;
		var tabs = $$( "#" + this.tabGroup.id + " .tabPane" );
		var tabPane = tabs[ tabNo ];
		var selTabPane = tabs[ this.selTabNo ];
		selTabPane.style.display = "none";
		tabPane.style.display = "block";

		var tab = $( tabPane.id + "tab" );
		var selTab = $( selTabPane.id + "tab" );
		tab.addClassName('sel');
		selTab.removeClassName('sel');
		
		var subInputs = $A( $$( "#" + tabPane.id + " input[type=text],#" + tabPane.id + " textarea" ) );
		try {
			var firstVisInput = subInputs.first(function(e){return !e.visible();});
			if( firstVisInput ) firstVisInput.focus();
		} catch(e) {
		
		}
		this.selTabNo = tabNo;
		selTabPane = tabs[ this.selTabNo ];
		
		if( selTabPane.getAttribute( "onTabClick" ) ) eval( selTabPane.getAttribute( "onTabClick" ).toString() );
		
		return false;
	}
});
function tabsAutoInit(){
	$$(".autoTabs").each(
		function(o){
			new Tabs( o.identify() );
		}
	);
}
document.observe( "dom:loaded", tabsAutoInit );
