(function($){

	$.fn.categoryman = function(opts)
	{
		
		var _settings =
		{
			starting_tab : 0
		}
		
		
		$.extend(_settings, opts);
		
		var context = $(this);
		
		var title = $(context).find('.categoryman-title').text();
		var menu_container = $(context).find('.categoryman-menu-placeholder');
		var categories = $(context).find('.categoryman-category');

		$(menu_container).html('<ul class="categoryman-menu"></ul>');
		$.each($(context).find('.categoryman-category'), function(categoryIndex, categoryElement)
		{
			var menu_list_item = $('<li class="categoryman-menu-item"></li>');
			var menu_list_trigger = $('<a href="javascript:void(0);">' + $(categoryElement).find('.categoryman-category-name').text() + '</a>')
			.click(function()
			{
				$(context).find('.categoryman-menu > li > a').not($(this)).removeClass('active');
				$(this).addClass('active');

				$(context).find('.categoryman-category').not($(categoryElement)).fadeOut();
				$(categoryElement).fadeIn();
			});

			$(menu_list_item).append($(menu_list_trigger));
			$(context).find('.categoryman-menu').append(menu_list_item);
			$(categoryElement).find('.categoryman-gallery > li:not(:eq(0))').hide();

			$.each($(categoryElement).find('.categoryman-gallery .categoryman-gallery-item'), function(galleryItemIndex, galleryItemElement)
			{
				var gallery_menu_item = $('<a></a>')
				.attr({
					'href':'javascript:void(0)',
					'class':'categoryman-gallery-menu-item'
				})
				.html('&bull;')
				.click(function()
				{
					$(categoryElement).find('.categoryman-gallery-menu-placeholder > a').not($(this)).removeClass('active');
					$(this).addClass('active');

					if($(galleryItemElement) !== $(categoryElement).find('.categoryman-gallery .categoryman-gallery-item:last'))
					{
						$(galleryItemElement).hide();
						$(galleryItemElement)
						.appendTo($(categoryElement).find('.categoryman-gallery'))
						.fadeIn('slow', function()
						{
							$(categoryElement)
							.find('.categoryman-gallery .categoryman-gallery-item').not($(galleryItemElement))
							.fadeOut('fast');
						});
					}
				});
				
				$(categoryElement).find('.categoryman-gallery-menu-placeholder').append($(gallery_menu_item));
			});

			$(categoryElement).hide();
		});

		$(context).find('.categoryman-category:eq('+_settings.starting_tab+')').fadeIn();
		$(context).find('.categoryman-menu li:eq('+_settings.starting_tab+') a').addClass('active');
	};

})(jQuery);
