Simple image resize...

Simple image resize...

Using Galleria, I have a gallery with various sized images:

<div class="gallery-container">
<div id="gallery-image"></div>
    <ul class="gallery-unstyled">
          <li class="active"><img src="images/50x50.jpg" title="tine pic" alt="tiny pic" /></li>
          <li><img src="images/500x200.jpg" title="Big picture" alt="big picture" /></li>
          <li><img src="images/200x500.jpg" title="Another big picture" alt="another big picture" /></li>
          <li><img src="images/200x200.jpg" title="Medium pic" alt="medium pic" /></li>
      </ul>
</div>

The gallery works fine, but I'm trying to dynamically change the size of the containing div's to the dimensions of the largest picture, but no more than 'x' pixels wide (a maximum allowed size).

I can get a few simple lines to set the div's, but I also want to set the size on any image bigger than the maximum size allowed so that any images larger than 'x' will also be scaled down.  Here's my code:

        var _maxWidth = 400;
        var _width = 0;
        var _height = 0;
        $('ul.gallery li img').each(
                                        function()
                                        {
                                                if ($(this).width() > _width)
                                                {
                                                    _width = $(this).width();
                                                    _height = $(this).height();
                                                }
                                                if ($(this).width() > _maxWidth)
                                                {
                                                    _width = _maxWidth;
                                                    _height = _height - (_height * (($(this).width() - _width)/$(this).width()));
                                                    $(this).css("width", _width + "px");
                                                }
                                               
                                            });
        $('div.gallery-container').width(_width + "px") .height(_height + "px");
        $('#gallery-image').width(_width + "px") .height(_height + "px");

I'm not too strong in js, but I've made a bazillion changes to this and still cannot get it to act consistently.  Can anyone spot anything obvious?