$(function () {
    var current_image;
    var current_opacity = 100;
    var current_timeout_spec;
    var featured_images = $('.rotate');
    var featured_image_links = featured_images.find('a');
    var hovering = false;
    var i = 0;
    var next_image;
    var timeout;

    var start_next_cross_fade = function () {
        get_next_image_pair();
        cross_fade();
    };

    var cross_fade = function () {
        if (current_opacity < 0) {
            current_opacity = 100;
            i += 1;
	    current_timeout_spec = {what: start_next_cross_fade, when:2500};
            if (!hovering) {
                timeout = window.setTimeout(current_timeout_spec.what,
					    current_timeout_spec.when);
	    }
            return;
        }
        current_image.fadeTo(0, current_opacity / 100);
        next_image.fadeTo(0, 1 - current_opacity / 100);
        current_opacity -= 2;
        current_timeout_spec = {what: cross_fade, when: 50};
        if (!hovering) {
            timeout = window.setTimeout(current_timeout_spec.what, 
					current_timeout_spec.when);
        }
    };

    var get_next_image_pair = function () {
        current_image = featured_images.eq(i % featured_images.length);
        next_image = featured_images.eq((i + 1) % featured_images.length);
        // bring the next image to be faded in to the front so its link 
        // can be clicked on
        featured_images.css('z-index', '10');
        next_image.css('z-index', '11');
    };

    featured_image_links.hover(function () {
        hovering = true;
        window.clearTimeout(timeout);
    }, function () {
        hovering = false;
        timeout = window.setTimeout(current_timeout_spec.what,
				    current_timeout_spec.when);
    });        

    get_next_image_pair();
    cross_fade();

});

