﻿var myTimer;
var image;
var cIndex = -1;
var interval;

function nextimage() {
    var cnt = $('#gallery a img').length;
    var nIndex = cIndex < (cnt - 1) ? cIndex + 1 : 0;
    showimage(nIndex);
}

function showimage(nextIndex) {
    if (nextIndex < $('#gallery a img').length) {
        var nextImage = $($('#gallery a')[nextIndex])
        var caption = nextImage.find('img').attr('rel');

        if (image) {

            if (cIndex != nextIndex) {

                clearTimeout(myTimer);

                //Set the fade in effect for the next image, show class has higher z-index
                $(nextImage).css({ opacity: 0.0 })
                .addClass('show')
                .stop().animate({ opacity: 1 }, 1000); //$(nextImage).fadeIn(1000);
                
                //Hide the current image
                $(image).stop().animate({ opacity: 0.0 }, 1000)
                .removeClass('show') //$(image).fadeOut(1000);

                $('#gallery .caption .selector #slct' + nextIndex + '').attr('src', 'Images/HomepageRotation/Controls/selected.png');
                $('#gallery .caption .selector #slct' + image.index() + '').attr('src', 'Images/HomepageRotation/Controls/selector.png');

                $('#gallery .caption .caption-text').stop().fadeOut(100, function () {
                    $($('#gallery .caption .selector img')[cIndex]).attr('src', 'Images/HomepageRotation/Controls/selector.png');
                    $($('#gallery .caption .selector img')[nextIndex]).attr('src', 'Images/HomepageRotation/Controls/selected.png');
                    $('#gallery .caption .caption-text').html(caption);
                    $('#gallery .caption .caption-text').fadeIn(1000);
                });

                myTimer = setTimeout("nextimage()", 8000);
            }
        } else {
            $('#gallery .caption .caption-text').html(caption);
            $('#gallery .caption .caption-text').fadeIn(100);
            $(nextImage).css({ opacity: 1.0 });
            $(nextImage).addClass('show');
            $($('#gallery .caption .selector img')[nextIndex]).attr('src', 'Images/HomepageRotation/Controls/selected.png');
        }

        image = nextImage;
        cIndex = nextIndex;
        
    }
}

