Array.prototype.max = function() {
	var max = this[0];
	var len = this.length;
	for (var i = 1; i < len; i++) {
		if (this[i] > max) {
			max = this[i];
		}
	}
	return max;
};

var container, contWidth, heights, hMax, margin, imgPerRow, widthNeeded, imgPerRowMargin;
$(document).ready(function() {
	if (!images || !path) return;
	
	container = $("#fancygallery");
	heights   = [];
	contWidth = container.width();
	margin    = parseInt(container.append($("<a>").html("1").addClass("fancybox margin")).find(".margin").css("marginLeft"), 10);
	container.html("");
	
	if (typeof(thumbnailWidth) == "undefined") {
		thumbnailWidth = 125;
	}
	
	imgPerRow   = Math.max(1, Math.floor(contWidth/(thumbnailWidth+2)));	// 2*1px border
	widthNeeded = imgPerRow*(thumbnailWidth+2)+(imgPerRow-1)*margin;
	imgPerRowMargin = (widthNeeded > contWidth) ? Math.max(1, imgPerRow-1) : imgPerRow;
	
	jQuery.each(images, function(k, ele) {
		var a = $("<a>").addClass("fancybox").attr({
		 	"rel": "group1",
			"href": path+ele
		});
		var img = $("<img>").attr({
		 	"src": path+"thumbs/"+ele,
		 	"alt": "",
			"width": thumbnailWidth
		});
		
		if ((k+1)%imgPerRow == 1) {
			a.addClass("first");
		}
		
		container.append(a.append(img));
	});

	
	/* Apply fancybox to multiple items */
	$("a.fancybox").fancybox({
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'speedIn'		: 600, 
		'speedOut'		: 200, 
		'overlayShow'	: true,
		'opacity'       : false,
		'autoScale'     : (typeof(showFullSize) != "undefined") ? !showFullSize : true
	});
});

// Workaround for IE < 8
if (jQuery.browser.msie) {
	if ((Number(jQuery.browser.version) < 8)) {
		$(window).load(function() {
			if (!container || !images || !path) return;
			
			jQuery.each(container.find("img"), function(k, ele) {
				heights.push($(ele).height());
			});
			hMax = heights.max();
			
			jQuery.each(container.children(), function(k, ele) {
				$(ele).css("height", hMax+"px");
			});
		});
	}
}
