$(window).load(function() {
    $("ul.image-bank").each(function() {
        var list = $(this);

        var items = list.find("li");

        function markCellsWithNotLastRow() {
            var length = items.length;

            var numberOfElementsInLastRow = length % 3;

            if (numberOfElementsInLastRow == 0) {
                numberOfElementsInLastRow = 3;
            }

            for (var i = 0; i < length - numberOfElementsInLastRow; i++) {
                items.eq(i).addClass("not-last-row");
            }
        }

        function markCellsWithColumnIndex() {
            items.each(function() {
                var item = $(this);

                item.addClass("column-" + ((item.index() % 3) + 1));
            });
        }

        function equalizeElementHeights() {
            function makeMinHeight(height, element) {
                var differenceInHeight = height - element.height();

                element.find("a:first").css("padding-top", differenceInHeight + "px");
            }
			
			function equalizeHeights(elements){
				var tallestElementHeight = 0;
				
				elements.each(function(){
					var element = $(this);
					
					var elementHeight = element.height();
					
					if(elementHeight > tallestElementHeight){
						tallestElementHeight = elementHeight;
					}
				});
				
                elements.each(function(){
					var element = $(this);
					
					makeMinHeight(tallestElementHeight, element);
				});
			}
			
            items.each(function() {
				var item = $(this);
				if(item.is(".column-1")){
                    var firstCell = item;
                    var secondCell = item.next();
                    var thirdCell = item.next().next();
					
					equalizeHeights(firstCell.add(secondCell).add(thirdCell));
				}
            });
        }
		
        function wrapImagesWithLinks() {
            items.each(function() {
                var item = $(this);

                var image = item.find("img");
                var link = item.find("a");

                image.wrap("<a href=\"" + link.attr("href") + "\"></a>");
            });
        }

        markCellsWithNotLastRow();
        markCellsWithColumnIndex();
        wrapImagesWithLinks();
        equalizeElementHeights();
    });
});
