// from http://stackoverflow.com/questions/5329201/jquery-move-elements-into-a-random-order
jQuery.fn.shuffle = function () {
    var j;
    for (var i = 0; i < this.length; i++) {
        j = Math.floor(Math.random() * this.length);
        $(this[i]).before($(this[j]));
    }
    return this;
};

var samsCmsMediaGalleryTeaserHandler = new function () {
    this.listSelector = '.samsCmsMediaGalleryTeaserComponent ul';
    this.initialized = false;

    this.init = function () {
        this.initialized = true;
        jQuery(this.listSelector).each(function (i, ul) {
            var $ul = jQuery(ul);
            var maxHeight = 0;
            var maxWidth = 0;
            $ul.children('li').each(function (j, li) {
                var $li = jQuery(li);
                var height = $li.height();
                if (height > maxHeight) {
                    maxHeight = height;

                }
                var width = $li.width();
                if (width > maxWidth) {
                    maxWidth = width;
                }
            });

            if ($ul.css('max-height').indexOf('px') > 0) {
                maxHeight = $ul.css('max-height').replace(/[^\d]/g, '') * 1;
            }
            if ($ul.css('max-width').indexOf('px') > 0) {
                maxWidth = $ul.css('max-width').replace(/[^\d]/g, '') * 1;
            }
            $ul.height(maxHeight);
            $ul.children('li').each(function (j, li) {
                var $li = jQuery(li);
                $li.css('margin-top', Math.round((maxHeight - $li.height()) / 2) + 'px');
            });
            $ul.width(maxWidth);
            $ul.children('li').each(function (j, li) {
                var $li = jQuery(li);
                $li.css('margin-left', Math.round((maxWidth - $li.width()) / 2) + 'px');
            });
        });
    };
};

jQuery(window).on('load', function () {
    if (!samsCmsMediaGalleryTeaserHandler.initialized) {
        samsCmsMediaGalleryTeaserHandler.init();
    }
});