<?php

global $tab_id, $tab_items;
$tab_id = 0;
$tab_items = array();

function gfxbucket_tab_func( $atts, $content ) {
	global $tab_id, $tab_items;

	$tab_id++;
	$tab_items = array();

	$content = do_shortcode( $content );
	$tab_nav = '';
	$tab_content = '';
	$counter = 0;

	foreach( $tab_items as $item ) {
		if( $counter == 0 ) {
			$tab_nav .= '<li role="presentation" class="active"><a href="#tab-' . $tab_id . '-' . $counter . '" aria-controls="tab-' . $tab_id . '-' . $counter . '" role="tab" data-toggle="tab" aria-expanded="true">' . $item['title'] . '</a></li>';
			$tab_content .= '<div role="tabpanel" class="tab-pane active" id="tab-' . $tab_id . '-' . $counter . '">' . $item['text'] . '</div>';
		} else {
			$tab_nav .= '<li role="presentation"><a href="#tab-' . $tab_id . '-' . $counter . '" aria-controls="tab-' . $tab_id . '-' . $counter . '" role="tab" data-toggle="tab" aria-expanded="false">' . $item['title'] . '</a></li>';
			$tab_content .= '<div role="tabpanel" class="tab-pane" id="tab-' . $tab_id . '-' . $counter . '">' . $item['text'] . '</div>';
		}

		$counter++;
	}

	return '<div role="tabpanel"><ul class="nav nav-tabs" role="tablist">' . $tab_nav . '</ul><div class="tab-content">' . $tab_content  . '</div></div>';	
}
add_shortcode( 'tab', 'gfxbucket_tab_func' );

function gfxbucket_tab_item_func( $atts, $content ) {
	extract(shortcode_atts( array(
		'title' => '',
        'text'  => ''
	), $atts ));

	global $tab_items;

	if( !$content ) {
		$content = $text;
	}
	
	array_push($tab_items, array('title' => $title, 'text' => $content ));

	return true;
}
add_shortcode( 'tab_item', 'gfxbucket_tab_item_func' );