// DYNAMIC TABS SCRIPT: v. 1.0 - Josh Stauffer
/*
 * History:
 *
 * 1.0 : First version. Expect bugs.
 *
 */

$(document).ready(function() {

	// Default Action
	$(".dynamic-tab-title, .dynamic-tab-content").hide(); // Hide all content
	$(".dynamic-tabs li:first").addClass("active").show(); // Activate first tab
	$(".dynamic-tab-title, .dynamic-tab-content:first").show(); // Show first tab content

	// Switch Tabs
	rotate = function(){
		$(".dynamic-tabs li").removeClass("active"); // Remove all active class
		$active.addClass("active"); // Add active class (the $active is declared in the rotateSwitch function)
		$(".dynamic-tab-title, .dynamic-tab-content").hide(); // Hide title and all tab content
		var activeTitle = $active.find("a").attr("title"); // Find the title attribute value
		var activeTab = $active.find("a").attr("href"); // Find the href attribute value to identify the active tab + content
		$(".dynamic-tab-title").html(activeTitle); // Set the html
		$(".dynamic-tab-title").fadeIn(800); // Fade in the active content
		$(activeTab).fadeIn(800); // Fade in the active content
	};

	// Rotation + Timing Event
	rotateSwitch = function(){
		var cycleCounter = 0;
		var maxCycles = 1; // Cycle through the tabs this many times.
		play = setInterval(function(){ // Set timer - this will repeat itself every 3 seconds
			$active = $(".dynamic-tabs li.active").next();
			if ( $active.length === 0) { // If end of tabs...
				$active = $(".dynamic-tabs li:first"); // go back to first
				cycleCounter++;
				if ( cycleCounter >= maxCycles ) {
					clearInterval(play); // Stop the timer
				}
			}
			rotate(); // Trigger the paging and slider function
		}, 5000); // Timer speed in milliseconds (3 seconds)
	};

	rotateSwitch(); // Run function on launch

	// On Click Event
	$(".dynamic-tabs li").click(function() {
		$active = $(this); // Activate the clicked tab
		clearInterval(play); // Stop the timer
		rotate(); // Trigger rotation immediately
		return false; // Prevent browser jump to link anchor
	});

});
