/*
 * Tabs jQuery plugin
 * Author: Dmytro Danylov
 */
(function($) {
	$.fn.tabs = function(options) {
		var options = $.extend({
			speed: 200,
			startTab : 0,
			tabActiveClass : "tabs_active"
		}, options);
		
		return this.each(function()
		{
			var prev = options.startTab; // Previously selected tab index
			var wait = false;
			
			// Reference to tabs container
			var container = $(this);
			
			// Get tabs containers
			var tabsContainers = container.children("div");
			// Get navigation
			var tabsNav = container.prev().children().children();
			// Hide all tab containers
			tabsContainers.each(function()
			{
				var tab = $(this);
				this.height = tab.height();
				tab.css({position: 'absolute', top: 0, left: 0, 'z-index': 0, visibility: 'hidden', width: tab.css('width')});
			});
			// Show first tab container only
			tabsContainers.eq(options.startTab).css({'z-index': 1, visibility: 'visible'});
			tabsNav.eq(options.startTab).addClass(options.tabActiveClass);
			
			// Set timeout is used to fix some problem with outerHeight() method in Google Chrome
			setTimeout(function() {
				container.css({height: tabsContainers.eq(options.startTab).outerHeight(true)});
			}, 400);
			
			// Function to switch tabs
			function changeTab(idx, height)
			{
				// Hide previous
				tabsContainers.eq(prev).css('z-index', 0);
				prevTemp = prev;
				prev = idx;
				// Show selected
				tabsContainers.eq(idx).stop().css({'z-index': 1, visibility: 'visible', opacity: 0}).animate({opacity: 1}, options.speed, function()
				{
					// Hide previous tab
					tabsContainers.eq(prevTemp).css('visibility', 'hidden');
					container.stop().animate({height: height}, options.speed);
				});
			}
			
			// Start tabs
			var i = 0;
			tabsNav.each(function() {
				this.idx = i;
				
				var link = $(this);
				link.bind('click', function(e)
				{
					e.preventDefault();
					if (prev == this.idx)
						return false;
					tabsNav.eq(prev).removeClass(options.tabActiveClass);
					$(this).addClass(options.tabActiveClass);
					changeTab(this.idx, tabsContainers.eq(this.idx).outerHeight(true));
				});
				++i;
			});
		});
	};
})(jQuery);
