(function($) {
    $.fn.scaleToContainer = function(container, images) {
        var ch = $(container).height();
        var cw = $(container).width();
        var ratio = cw / ch;

        $(images).each(function() {
            var iw = $(this).width();
	    var ih = $(this).height();

            if ((iw > cw) || (ih > ch)) {
                var ir = parseFloat(iw) / parseFloat(ih);
                var dh = ch / ih;
                var dw = cw / iw;

                if (dh > dw) {
                    $(this).width(cw);
                    $(this).height(parseInt(cw / ir));
                } else {
                    $(this).height(ch);
                    $(this).width(parseInt(ch * ir));
                }
            }
            
            $(this).css('left', (cw - $(this).width())/2);
	    $(this).css('top', (ch - $(this).height())/2);
        });
    }
})(jQuery);

// These all deal with the loading of images.  It is not sufficient
// for the document to be ready.  The images must be loaded to be
// analyzed.

$(window).load(function() {
    if ($('#festival-bigimage').length != 0) {
        $.fn.scaleToContainer('#festival-bigimage', '#festival-bigimage img');
    }

    if ($('.cycler').length != 0) {
        $.fn.scaleToContainer('.cycler', '.cycler img');
        
        $('.cycler').cycle({
            fx: 'fade',
            delay: 4000,
            speed: 400
        });
    }

    // TODO: This construction indicates a pain point.
    // scaleToContainer is not abstracted enough.

    if ($('#festival-film-list').length != 0) {
        $('a.festcard-image').each(function() {
            $.fn.scaleToContainer($(this), $('img', $(this)));
        });
    }

    if ($('#minifilms').length != 0) {
        $('a.festcard-image').each(function() {
            $.fn.scaleToContainer($(this), $('img', $(this)));
        });
    }
}); 

