// original code from:                    
// http://ynzi.com/blog/dynamicslideshow/ 
jQuery.fn.dynamicSlideshow = function(attr) {

    // constants to identify slide rotation behavior
    var forward = 1;
    var backward = -1;

    // check for custom settings
    attr = attr || {};
    var duration = attr.duration || 3000;
    var step = attr.step || forward;
    var firstToggleString = attr.toggleString || "Go";
    var secondToggleString = $('#stopStart').val() || "Stop";

    // sanity check for rotation increment
    if ( ( step > forward ) || ( step == 0 ) ) step = forward;
    if ( step < backward ) step = backward;

    // hide the forward and back step buttons while slideshow is automatically
    // rotating
    $('#stepForward').hide();
    $('#stepBackward').hide();

    function initSlider(container, img) {
        
        // current slide identifier
        var curr = 0;

        function rotateSlide() {
            next = curr + step;
            if (next >= img.length) {
                next = 0;
            } else if (next < 0) {
                next = img.length - 1;
            }

            var i = new Image();
            $(i).load(function(){
                $(container).append(this);
                $(container).find('img:first').css({'z-index': 1});
                $(this).css({opacity: 0.0, 'z-index': 2}).animate({opacity: 1.0}, 1000, function() {
                    $(container).find('img:first').remove();
                })
            }).attr('src', img[next]).css({'z-index':8});
            curr = next;
        }; 

        slideInterval = setInterval(function () {rotateSlide()},  duration);

        $('#stopStart').toggle(
            function() {
                clearInterval(slideInterval);
                $('#stopStart').val(firstToggleString);
                $('#stepForward').show();
                $('#stepBackward').show();
            }, 
            function() {
                step = forward;
                slideInterval = setInterval(function () {rotateSlide()},  duration);
                $('#stopStart').val(secondToggleString);
                $('#stepForward').hide();
                $('#stepBackward').hide();
            }
        );

        $('#stepForward').click(
            function() {
                step = forward;
                rotateSlide();
            }
        );

        $('#stepBackward').click(
            function() {
                step = backward;
                rotateSlide();
            }
        );
    };

    $(this).each(function(){
        var img = [];
        $(this).find("a").each(function(){
            img.push($(this).attr("href"));     
        });
        var j = new Image();
        var container = this;
        $(this).empty();
        $(j).attr('src', img[0]).css({'z-index':0}).load(function(){
            $(container).append(this);
            initSlider(container, img);
        });
    });
};
