// JavaScript Document 
	
// Tab-u-lator Scripts
// Created: 1.26.2011
// Author: Sam Napolitano
// URL: http://www.napolitopia.com/

$(document).ready(function(){
	
	function init_tabs(){

		var sections = $('#tabbed_content > section');
		var articles = $('#tabbed_content > section > article');
		var headers = $('#tabbed_content > section > header');
		headers.prependTo('#tabbed_content').wrapAll('<div id="tabbed_headers" />');
		articles.prependTo('#tabbed_content').insertAfter('#tabbed_headers').wrapAll('<div id="tabbed_articles" />');
		sections.remove();
	
		//hide all articles
		articles.each(function(){
			$(this).hide();
		});
		//setup the first artice and header for load
		articles.first().addClass('visible').show();
		headers.first().addClass('active');
		
		//Now lets make some magic
		headers.each(function(index){
			//console.log(index + ":" + $(articles[index]).html());
			var header = $(headers[index]);
			var article = $(articles[index]);
			//console.log($(header).html() + ":" + $(article).html());
			$(header).children('a').first().click(function(ev){
				//everything we need to transition
				var thisHeader = header;
				var thisArticle = article;
				var lastHeader = $('#tabbed_content > #tabbed_headers > header.active').first();
				var lastArticle = $('#tabbed_content > #tabbed_articles > article.visible').first();
				// if we get a click while animation is going on, just dont do anything.
				if(lastArticle.length < 1){
					ev.preventDefault();
				}else{
					if($(thisHeader).hasClass('active') == false){
						//prevent the link
						ev.preventDefault();
						// remove class from headers and articles.. this prevents undesired clicks while animating
						headers.each(function(){
							$(this).removeClass('active');
						});
						articles.each(function(){
							$(this).removeClass('visible');
						});
						//add the active state to the header so it doesnt look funny. 
						$(thisHeader).addClass('active');
						thisArticle.children('*').hide();
						//animate aways!!
						lastArticle.children('*').fadeOut( 300, function(){
							lastArticle.hide();
							thisArticle.show();
							thisArticle.children('*').fadeIn( 300, function(){
								$(thisArticle).addClass('visible');
							});
						});
						//end animationators 
					}
				}

			});
			
		});
		
	}
	
	init_tabs();
	
});
