window.anterior = window.onload;

window.onload = function() {
	$('.pestanas').each(function() {
		var div = $(this);

		var ul = $('<ul />');
		div.find('h2').each(function(i) {
			var li = $('<li>' + $(this).html() + '</li>');

			li.attr('div', $(this).parent().attr('id') ).click(function() {
				div.find('> div').hide();
				$('#' + $(this).attr('div')).show();

				div.find('ul li').removeClass('activo');
				$(this).addClass('activo');
			});

			if(i == 0) {
				li.addClass('primero').addClass('activo');
			} else {
				$(this).parent().hide();
			}

			ul.append(li);
		});

		if(ul.children().length != 0) {
			var titulo = $('<h2 />');

			titulo.prepend(ul);

			div.prepend(titulo).find('h2:gt(0)').remove().end().addClass('cambiado');

			var tam = 1;
			while(!todosColocados(titulo.find('li')) && tam > 0.5) {
				tam -= 0.01;
				titulo.find('ul').css('font-size', tam + 'em');
			}
		} else {
			div.remove();
		}
	});

	if(window.anterior) {
		window.anterior();
	}
}

function todosColocados(lis) {
	var posicion = 0, altura = 0;
	var correcto = true;
	lis.each(function(i) {
		if(i == 0) {
			posicion = $(this).position().top;
			altura = $(this).height();
		} else {
			correcto = correcto && ($(this).position().top == posicion) && ($(this).height() == altura);
		}
	});

	return correcto;
}