/**
 * modified image transition logic.  params:
 * { delay: 3000, duration: 1000, images: ['path/image1.jpg','path/image2.jpg'] }
 */
$.fn.imgswitch = function(options) {
    var settings = $.extend({delay:3000, duration:1000}, options || {});
    var index = 0;
    var us = $(this);
    var img1 = null;
    var img2 = null;

    
    function getNextImage(advance) {
        var nextIndex = index + 1;
        if (nextIndex >= settings.images.length) {
            //wrap
            nextIndex = 0;
        }
        if (advance) {
            index = nextIndex;
        }
        return settings.images[nextIndex];
    }

    function init() {
        var curImage = settings.images[index];
        var newImage = getNextImage(false);

        if (us.children('img').size() == 0) {
            //no images
            us.append($('<img style="position:absolute" src=' + curImage + '></img>'));
        }
        img1 = us.children('img:nth-child(1)');

        if (us.children('img').size() == 1) {
            //need a second
            img1.clone().css({position:'static'}).appendTo(us);
        }
        img2 = us.children('img:nth-child(2)');

        img1.css({position:'absolute'}).attr('src', curImage);
        img2.css({position:'static'}).attr('src', newImage);
    }

    init();

    setInterval(function() {
        var curImage = settings.images[index];
        var newImage = getNextImage(true);

        //wrap into div if no div is present.
        us.each(function() {
            img1.attr('src', curImage).show();
            img2.fadeOut(1).attr('src', newImage).fadeIn(settings.duration,
                function() {
                    img1.hide();
                    img1.attr('src', getNextImage(false)); //preload next image using the invisible component
                }
            );
        });

    }, settings.delay);

};	



