/**
 * Flowy 1.0
 * Copyright (C) by Invent Themes
 * All rights reserved
 * http://invent-themes.com
 */

;(function($) {
	$.fn.flowy = function(options){
		var options = $.extend({}, $.fn.flowy.defaults, options);

		return this.each(function() {
			var duringAnimation = false;
			var selectedSet = 'gallery-all';
			var parentObject = $(this);
			var itemsContainer = $(this).find('>div');
			var galleryItems = itemsContainer.find('>div'); // '.gallery-item',parentObject);
			var itemWidth = 10;
			var itemHeight = 10;

			for(var i=0; i<galleryItems.length; i++) {
				var j = galleryItems.eq(i).outerWidth()+options.margin;
				var k = galleryItems.eq(i).outerHeight();//+options.margin;
				if(j>itemWidth) itemWidth=j;
				if(k>itemHeight) itemHeight=k;
			}
			var columns = Math.floor((parseInt(itemsContainer.css('width'))+options.margin)/itemWidth);

			function changeGroup(newItemsClass, animateContener) {
				selectedSet = newItemsClass;
				duringAnimation = true;
				$('.gallery-splitter .selected').removeClass('selected');
				$('.'+newItemsClass).addClass('selected');
				if(newItemsClass=='gallery-all')
					var newItems = galleryItems;
				else {
					var newItems = $('.'+newItemsClass).not('.gallery-splitter .'+newItemsClass);
					itemsContainer.find('>div').not(newItems).stop().animate({'opacity':0},{ duration: options.animationSpeed, queue: false },options.easing, function(){ $(this).css({left:0, top:0})}).addClass('flowy-hidden').css('display', 'none');
				}
				var t=0;
				var l=0;
				for(var i=0; i<newItems.length; i++) {

					if(animateContener){
						var item =$(newItems).eq(i);
						if(item.hasClass('flowy-hidden'))
							item.css({'display': 'block',left: l, top: t}).stop().animate({'opacity':1},{ duration: options.animationSpeed, queue: false },options.easing).removeClass('flowy-hidden');
						else
							item.stop().animate({left: l, top: t},options.animationSpeed,options.easing);
					}
					else
						$(newItems).eq(i).css({left: l, top: t});
					
					l+=itemWidth;
					if((i+1)%columns==0){
						l = 0;
						t += itemHeight;
					}
				}

				if(animateContener)
					itemsContainer.stop().animate({height:itemHeight*Math.ceil(newItems.length/columns)}, { duration: options.animationSpeed, queue: false }, options.easing, function(){ duringAnimation = false; portfolioAnimations(); });
				else{
					itemsContainer.css({height:itemHeight*Math.ceil(newItems.length/columns)});
					portfolioAnimations();
				}
			}

			$('.gallery-splitter a', parentObject).click(function(){
				changeGroup(this.hash.slice(1), true);
			});

			changeGroup(window.location.hash.slice(1)=='' ? 'gallery-all' : window.location.hash.slice(1), false);
		});
	};

	$.fn.flowy.defaults = {
		animationSpeed: 500,
		easing: 'easeOutSine',
		margin: 0
	}
})(jQuery);
