
var tabbey=(function(){
	
	//all initialized tabs;
	var _tabs={};

	var _setupTabbey=function(tabId){
		var tabInfo=_tabs[tabId];
		
		var tabUL=tabInfo.tab.find("ul.tabbey");
		tabUL.find("li:first a").addClass("first");
		tabUL.find("li:last a").addClass("last");
		//add classes to all tabs
		$.each(tabUL.find("li"), function(i,elem){
			var e=$(elem);
			e.addClass("tab_"+i);
			//bind onclick event listener
			e.find("a").bind("click",function(){
				_selectTab(tabId, i);
			});
		});
		//hide all content (default)
		tabInfo.tab.find("div.content").hide();
		
		//show startup tab
		_selectTab(tabId,tabInfo.active);
		
	}
	
	//activates a certain tab
	var _selectTab=function(tabId, index){
		var tabInfo=_tabs[tabId];
		
		//remove "active" tab class and hide content of that tab
		tabInfo.tab.find("ul.tabbey li:nth-child("+(tabInfo.active+1)+")").removeClass("active");
		tabInfo.tab.find("div.content").hide();
		
		//show new active tab
		tabInfo.tab.find("ul.tabbey li:nth-child("+(index+1)+")").addClass("active");
		
		if (index===tabInfo.showall){ //show all contents of all tabs
			tabInfo.tab.find("div.content").show();
		}
		else{ //only show the desired content of the selected tab (and hide the old selected one)
			
			tabInfo.tab.find("div.content.tab_" + index).show();	
		}
		
		//store the active tab to the tabinfo
		tabInfo.active=index;
	}

	return{
		/*
		 * Sets up a Tabbey Box with tabs. Handles multiple tabbeys
		 * @param
		 * tabId: the div wrapper id, in which the tabbey logic is
		 * startTab: indice of the active tab at the beginning (indice starts by 0)
		 * allTab: incidice of special tab, which displays the content of all tabs  (indice starts by 0)
		 */
		init:function( tabId, startTab, allTab ){
			if (typeof tabId !== "undefined") {
				var tabStoreId=tabId;
				if (typeof _tabs[tabStoreId] !== "undefined") {
					tabStoreId = tabId + Math.round( Math.random() * 1000000 );
				}
				if (typeof startTab === "undefined") {
					var startTab = 0;
				}
				if (typeof allTab === "undefined") {
					var allTab = -1;
				}
				var tab=$("#"+tabId+":not(.tabbeySetup)");
				tab.addClass("tabbeySetup");
				//store tabbey data
				_tabs[tabStoreId]={
						"tab":tab,
						"active":startTab,
						"showall":allTab
				};
				//setup the tabbey with its tabs and css classes
				_setupTabbey(tabStoreId);
			}
		}
	}
})();
