/*
 * jQuery dm_gallery plugin
 * Author: Dmytro Danylov
 */
(function($) {
	$.fn.dm_gallery = function(options) {
		var options = $.extend({
		}, options);
		
		return this.each(function() {
			
			var ulContainer = $(this);
			var pCtrlView = ulContainer.prevAll('.view:first');
			var pCtrlCategory = ulContainer.prevAll('.category:first');
			var currentView = 'grid';
			
			function changeCategory(a) {
				var category = a.attr('rel');
				ulContainer.children('div').each(function() {
					var div = $(this);
					if (category == 'view_all')
						div.fadeIn('fast');
					else if (!div.hasClass(category))
						div.fadeOut('fast');
					else
						div.fadeIn('fast');
				});
			}
			
			function changeView(type) {
				if (type == 'grid' && currentView != 'grid')
				{
					ulContainer.removeClass('list');
					currentView = 'grid';
				}
				else if (type == 'list' && currentView != 'list')
				{
					ulContainer.addClass('list');
					currentView = 'list';
				}
				return;
			}
			
			// Set grid view to active by default
			pCtrlCategory.children().eq(0).addClass('active');
			
			pCtrlCategory.children('a').each(function() {
				$(this).bind('click', function(event) {
					event.preventDefault();
					pCtrlCategory.children().each(function() { $(this).removeClass('active'); });
					$(this).addClass('active');
					changeCategory($(this));
				});
			});
			
			
			// Set grid view to active by default
			pCtrlView.children().eq(0).addClass('active');
			
			pCtrlView.children().eq(0).bind('click', function(event) {
				event.preventDefault();
				pCtrlView.children().eq(1).removeClass('active');
				pCtrlView.children().eq(0).addClass('active');
				changeView('grid');
			});
			
			pCtrlView.children().eq(1).bind('click', function(event) {
				event.preventDefault();
				pCtrlView.children().eq(0).removeClass('active');
				pCtrlView.children().eq(1).addClass('active');
				changeView('list');
			});
		});
	};
})(jQuery);
