
//Initialize
var autotabs = new autotabObject();

//This is the magic:
$(document).ready(function(){
	autotabs.create('#autotabs');
});

//Methods for the autotabs object

autotabObject.prototype.create=function(jq_selector){
	
	if ( $(jq_selector).length!=1) {return false;}

	//Fire all events that want's to be fired before the tabs are made
	for(var i=0;i<this.beforeTabsEvents.length;i++){
		this.beforeTabsEvents[i]();
	}
	
	var myObjectRef=this;
	var nameAttrib='nname';
	//Insert inside
	$(jq_selector).prepend('<ul class="autotabs_nav"></ul>');
	//Insert before
	//$('.autotabs').before('<ul id="nav"></ul>');
	$('a.tab',$(jq_selector)).each(
		function(i){
			
			if( !$(this).attr(nameAttrib) ){
				if ( $(this).attr('name') ){
					$(this).attr(nameAttrib,$(this).attr('name'));
				}else{
					$(this).attr(nameAttrib,$(this).html());
				}
			}
			myObjectRef.tabs[$(this).attr(nameAttrib)]=this;
			$(this).attr('href','#'+$(this).attr(nameAttrib));
			$(this).html('<span class="right"><span class="center">'+$(this).html()+'</span></span>');
			$(this).click(
				function(){
				//Disable the old pane
				$(myObjectRef.currentPane).hide();
				$(myObjectRef.currentTab).removeClass('active');
				//Update the attributes
				myObjectRef.currentPane='#'+$(this).attr(nameAttrib);
				myObjectRef.currentTab=this;
				//Enable the new pane
				$(myObjectRef.currentPane).show();
				$(myObjectRef.currentTab).addClass('active');				
				$(this).blur();
				var tabname=$(this).attr(nameAttrib);
				for(var i=0;i<myObjectRef.onShowEvents.length;i++){
					if ( myObjectRef.onShowEvents[i].tab==tabname || myObjectRef.onShowEvents[i].tab=="" ){
						myObjectRef.onShowEvents[i].event(tabname);
					}
				}
				return false;
				}
			);	
			$(this).next().attr('id',$(this).attr(nameAttrib));
			$(this).next().addClass('pane');
			$(this).next().hide();
			$('.autotabs_nav',$(jq_selector)).append($('<li></li>').append($(this)));
		}
	);
	var nav_a=$('.autotabs_nav a',$(jq_selector));
	$(nav_a[0]).addClass('start');

	this.currentTab= nav_a[0];
	this.currentPane='#'+$(this.currentTab).attr(nameAttrib);
	
	var last=nav_a.get(nav_a.length-1);
	$($(last).children()[0]).attr('class','end');
	
	this.select(this.defaultTab?this.defaultTab:$(this.currentTab).attr(nameAttrib));
//	$(this.currentTab).click();

}


autotabObject.prototype.select= function(tab){
	$(this.tabs[tab]).click();
}


function autotabInternalEventObj(event,tab){
	this.event=event;
	if ( tab == undefined ) { tab = ""; }
	this.tab=tab;
}

function autotabObject(){
	this.beforeTabsEvents= new Array();
	this.onShowEvents= new Array();
	this.tabs=new Array();
	this.currentTab=null;
}

autotabObject.prototype.beforeTabsEvent = function (event){
		this.beforeTabsEvents[this.beforeTabsEvents.length]=event;
}

autotabObject.prototype.onShowEvent = function (event,tab){
		this.onShowEvents[this.onShowEvents.length]=new autotabInternalEventObj(event,tab);
}

