$(document).ready(function() {
	instatabs();
});

function instatabs() {
	var tab, label, active;
	var header = 'h3';
	
	$('.instatabs').prepend('<ul class="tab-tabs"></ul>');
	$('.instatabs').each(function() {
		// set default as first if not set
		if ($(this).children('div.start').length == 0) {
			$(this).children('div:first').addClass('start');
		}
	
		$(this).children('div').each(function() {
			tab     = $(this).attr('id'); // get tabs
			label   = $(this).children(header).hide().html(); // get tab label, hide label
			active  = $(this).hasClass('start');
		
			// show or hide tab
			if (active) {
				$(this).show();
			} else {
				$(this).hide();
			}
		
			$(this).siblings('ul.tab-tabs').append('<li class="' + tab + '"><a href="#" rel="' + tab + '">' + label + '</a></li>');
		
			// bind event
			$('a[rel=' + tab + ']').click(function(e) {
				e.preventDefault();					
				var rel = $(this).attr('rel');
					
				// update tab active state to this
				$(this).parents('ul.tab-tabs').find('li a').each(function(i) {
					if (rel == $(this).attr('rel')) {
						$(this).addClass('active').parents('ul').addClass($(this).attr('rel'));
					} else {
						$(this).removeClass('active').parents('ul').removeClass($(this).attr('rel'));
					}
				});
			
				// update tab content display					
				$(this).parents('.instatabs').children('div').each(function(i) {
					$(this).hide();
					if ($(this).attr('id') == rel) {
						$(this).show();
					} else {
						$(this).hide();
					}
				});
			
				return false;
			});
		});

		// start tabs
		$('a[rel=' + $(this).find('div.start').attr('id') + ']').click();
	});
	
	// clearing floats
	$('.instatabs ul.tab-tabs').append('<span class="clear"></span>');
}
