var intervalId;
var intervalTime = 10000;
var $active;
var currentImg = 1;
var animating = false;

 $('#slideshow IMG:last').addClass('active');

function slideSwitch() {

    if(!animating){
        $active = $('#slideshow IMG.active');

        if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

        var $next =  $active.next().length ? $active.next()
            : $('#slideshow IMG:first');

        $active.addClass('last_active');
        currentImg++;
        animateImage($next);
    }   // end if !animating

}

$(function() {
    intervalId = setInterval( "slideSwitch()", intervalTime );
});

function chooseImage(imageNum, positive){
	if(!animating){
            imageNum--;
            $active = $('#slideshow IMG.active');
            $active.addClass('last_active');

            var $next = $('#slideshow IMG:eq(' + imageNum + ')');
            animateImage($next);

            clearInterval(intervalId);
            intervalId = setInterval( "slideSwitch()", intervalTime );
        } // end if !animating

} // end chooseImage

function animateImage($nextImage){
        if(!animating){
            animating = true;
            $nextImage.css({opacity: 0.0})
                    .addClass('active')
                    .animate({opacity: 1.0}, 1000, function() {
                    $active.removeClass('active last_active');
                    animating = false;
                    }
            );
            return true;
        } else {                // already animating do nothing
            return false;
        }

} // end animateImage

function nextImage(){
    if(!animating){
        currentImg++;
        if(currentImg > $('#slideshow IMG').size())
            currentImg = 1;
        chooseImage(currentImg);
    } // end if !animating
}

function prevImage(){
    if(!animating){
        currentImg--;
        if(currentImg < 1)
            currentImg = $('#slideshow IMG').size();
        chooseImage(currentImg);
    } // end if !animating
}