(function($) {
	$.fn.flipgallery = function() {
			
		var choose = 10;		
		var duration = 500;
		var images = $(this).find('img');

		function flip() {
			// choose random numbers between 0 and numberofimages -1
			var numbers = new Array();
			while (numbers.length < choose) {
				var number = Math.round(Math.random() * images.length - 1);
				if (jQuery.inArray(number, numbers) === -1) {
					numbers.push(number);
				}
			}
		
			var urls = new Array();
		
			$(numbers).each(function(index, value) {
				var width = $(images[this]).width();
				var height = $(images[this]).height();
				var margin = $(images[this]).width() / 2;
				var reverse = numbers.length - 1 - index;

				// save urls so they don't get overwritten
				urls.push($(images[value]).attr('src'));

				$(images[value]).stop().animate({width: '0px', height: '' + height + 'px', marginLeft: '' + margin + 'px', opacity: '0.5'}, {duration: duration});
				window.setTimeout(function() {
					$(images[value]).attr('src', urls[reverse]);
					$(images[value]).stop().animate({width: width, height: '' + height + 'px', marginLeft: '0px', opacity: '1'}, {duration: duration});
				}, duration);
			});
			
		}
		
		setInterval(flip, 3000);
		
	};
	
})(jQuery);



$(document).ready(function() {

	if ($('#gallery').length > 0) {
		$('#gallery').flipgallery();
	}

});

