$(document).ready(function(){

    function updatePositions() {
        var $columns = 3;
        var selectors = ['.product-item-resizer', '.product-item-price'];
        for (var key in selectors) {
            var selector = selectors[key];
            var sizes = {};
            var $count = 0;
            var $row = 0;
            $(selector).each(function() {
                if ($count % $columns == 0) {
                    $row++;
                }
                $count++;
                var height = $(this).height();
                if (sizes[$row] == undefined || sizes[$row] < height) {
                    sizes[$row] = height;
                }
            });

            var $count = 0;
            var $row = 0;
            $(selector).each(function() {
                if ($count % $columns == 0) {
                    $row++;
                }
                $count++;
                $(this).height(sizes[$row]);
            });
        }
    }

    $('#sorter select').live('change', function(event){
        event.preventDefault();
        
        if (window.showLoading) {
            showLoading();
        }

        $.ajax({
            type: 'get',
            url: $(this).val() + '&mode=ajax',
            dataType: 'html',
            success: function (html) {
                $('#product-contents').html(html);
                updatePositions();
            },

            complete: function () {
                if (window.hideLoading) {
                    hideLoading();
                }
            }
        });
    });

    $('#pager a').live('click', function(event){
        event.preventDefault();

        if (window.showLoading) {
            showLoading();
        }

        $.ajax({
            type: 'get',
            url: $(this).attr('href') + '&mode=ajax',
            dataType: 'html',
            success: function (html) {
                $('#product-contents').html(html);
                updatePositions();
            },

            complete: function () {
                if (window.hideLoading) {
                    hideLoading();
                }
            }
        });
    });

    updatePositions();
});
