(function($) {
    var both_columns = '#column-left, #column-right';
    /* justify_heights() is used to match the heights of both layout columns,
     * similar to a table based layout.
     */
    var justify_heights = function() { $(both_columns).vjustify(); };

    /* rejustify_heights() is called after page content, including images,
     * are loaded. If the 'column-right' height has changed since the first
     * justify_heights() call, the heights for both columns are reset and
     * then re-justified 
     */
    var height_changed_for = function(element) {
        var el = $(element);
        if(!el.length)
            return false;
        return (el.children().get(0).offsetHeight > el.get(0).offsetHeight);
    };
    var rejustify_heights = function() {
        var left = $('#column-left'),
            right = $('#column-right');
        /* This compares the first inner child of the right column to see if
         * the dynamic height of that child is greater than the justified 
         * height of the right column.
         */
        if(height_changed_for(left) || height_changed_for(right)) {
             $(both_columns)
                .height('auto')
                .vjustify();
        }
    };

    /* This sets up code to run when the DOM is ready, which can be before all
     * external content is loaded. Doing this early should cause these small
     * fixes to be applied fast enough that a user won't notice.
     */
    $(document).ready(function(){
        justify_heights();
    });

    /* This code runs when the 'load' event is signaled, which occurs after
     * external content has loaded. `rejustify_heights()` is called so that
     * the column justification code can adjust to loaded images whose heights
     * weren't specified in code. These images can cause the computed height
     * of a column to change.
     */
     $(window).load(function() {
         rejustify_heights();
     });
})(jQuery);

