var categoryContent;

jQuery(document).ready(function($) {
	categoryTitles = new Array();
	categoryContent = new Array();
	$('#widgetContent ul[title]').each(function(){
		categoryContent.push($(this));
	});
	
	if(categoryContent.length > 0)
		buildWidget();
});

function buildWidget()
{
	var widgetLists = jQuery('#widgetContent ul[title]');
	
	var title = '<ul id="titles">';
	for(var i = 0; i < categoryContent.length; i++)
	{
		//title += (i != 0)?'<li>':'<li class="first active"><img src="/wp-content/uploads/widget_arrow.png" alt="arrow"/>';
		title += '<li '
		
		if(i == 0)
			title += 'class="first active"><img src="/wp-content/uploads/widget_arrow.png" /';
		if(i == categoryContent.length-1)
			title += 'id="last-title"';
		
		title += '>';
		title += categoryContent[i].attr('title');
		title += '</li>';
	}
	title += '<li id="titleFiller" style="padding:0px; margin:0px"></li>';
	title += '</ul>';
	widgetLists.first().before(title);
	widgetLists.hide();
	widgetLists.first().show();
	
	widgetLists.each(function(){
		var lastBox = '<li class="last-item">';
			if(jQuery(this).attr('rel') != undefined) lastBox += '<a href="'+ jQuery(this).attr('rel') +'" class="button">See More</a>';
			lastBox += '</li>';
		jQuery(lastBox).appendTo(jQuery(this));
		jQuery(this).children().first().addClass('first-item');
	});
	
	var minHeight = jQuery('#titles').height();
	jQuery('#widgetContent').css('min-height',minHeight);
	
	jQuery('ul#titles li').click(function(){switchContent(this);});
	adjustFiller(categoryContent[0]);
}

function switchContent(eventObj)
{
	var arrow = jQuery('#widgetContent li.active img').remove();
	for(var i = 0; i < categoryContent.length; i++)
	{
		if(categoryContent[i].attr('title') == jQuery(eventObj).html())
		{
			jQuery('#widgetContent ul[title="' + jQuery('#widgetContent li.active').html() + '"]').hide();
			jQuery('#widgetContent li.active').removeClass('active');
			categoryContent[i].show();
			jQuery(eventObj).addClass('active');
			jQuery(eventObj).append('<img src="/wp-content/uploads/widget_arrow.png" />');
			adjustFiller(categoryContent[i]);
		}
	}
}

function adjustFiller(activeContent)
{
	var fillerHeight = jQuery('ul[title="' + activeContent.attr('title') +'"]').height() - (jQuery('#titles').height() - jQuery('#titleFiller').height());
	if(fillerHeight > 0)
	{
		jQuery('#titleFiller').css('height',fillerHeight);
		jQuery('#last-title').removeClass('last');
	}
	else
	{
		jQuery('#titleFiller').css('height',0);
		jQuery('#last-title').addClass('last');
	}
}
