/**
 * @author Frukt Kuubis
 * @copyright Frukt Kuubis OÜ 2009
 */

var Tabs = (function(){
	/* get current selected tab object */
	function _getSelectedTab(){
		return $('div.tabs div.strip a.selected').get(0);
	}
	
	/* return tab id from tab object */
	function _getTabId(tab){
		if(!tab || $(tab).attr('id').length < 1){ return false; }
		var exp = $(tab).attr('id').split('-');
		return exp[1];
	}
	
	/* check if tab is first */
	function _isFirstTab(tabId){
		var first = $('div.tabs div.strip a:first');
		return (!first || first.attr('id') != 'tab-'+tabId) ? false : true;
	}
	
	/* check if tab is last */
	function _isLastTab(tabId){
		var last = $('div.tabs div.strip a:last');
		return (!last || last.attr('id') != 'tab-'+tabId) ? false : true;
	}
	
	return {
		switchTab: function(tabId){
			var currentTab = _getSelectedTab();
			var currentTabId = _getTabId(currentTab);
			
			// do nothing if clicked on the same tab
			if(currentTabId == tabId){ return false; }
			
			$('div.tabs div.strip span:not(span:first, span:last)').attr('class', 'split-2to2');

			// set current active tab styles			
			$(currentTab).removeClass('selected');
			if(_isFirstTab(currentTabId)){ $(currentTab).prev().attr('class', 'split-first'); }
			else if(_isLastTab(currentTabId)){ $(currentTab).next().attr('class', 'split-last'); }
			
			// set clicked tab styles
			var newTab = $('#tab-'+tabId);
			var isNewFirst = _isFirstTab(tabId);
			var isNewLast = _isLastTab(tabId);
			$(newTab).addClass('selected');
			if(isNewFirst){
				$(newTab).prev().attr('class', 'split-first-active');
				$(newTab).next().attr('class', (isNewLast ? 'split-last-active' : 'split-1to2'));
			}else if(isNewLast){
				$(newTab).next().attr('class', 'split-last-active');
				$(newTab).prev().attr('class', (isNewFirst ? 'split-first-active' : 'split-2to1'));
			}else{
				$(newTab).next().attr('class', 'split-1to2');
				$(newTab).prev().attr('class', 'split-2to1');
			}
			
			// show/hide tab content
			$('#content-'+currentTabId).addClass('hidden');
			$('#content-'+tabId).removeClass('hidden');
		}
	}
}());

