//Prerequisites: jquery-1.2.6.min.js, jquery.cycle.all.min.js

var CurrentFilmStripIndex = 0;
var SlideCount = 0;
var FilmStripItems = 6;
var FilmStripItemWidth = 99;
var FilmStripLeft = -1;
$.fn.cycle.defaults.timeout = 4000;

$(function() {

    //Setup HiddenFields: used to pass content to javascript without worry of character usage.
    //Hidden fields must not contain original html content if postback occurs or validation error will be thrown.
    //Move all html content from hidden label to alt attribute of image
    $("#divPics span[id$='hfContent']").each(function() {
        $(this).siblings('img')[0].alt = this.innerHTML;
    });
    //Move html title from hidden label to title attribute of image
    $("#divPics span[id$='hfTitle']").each(function() {
        $(this).parent().attr("title", this.innerHTML);
    });

    //Configure the gallery
    $('#divPics').cycle({
        fx: 'fade',
        speed: '800',
        pager: '#nav',
        pause: 1,
        pauseOnPagerHover: 1,
        before: onBefore,
        after: onAfter,
        next: '#next2',
        prev: '#prev2',
        // callback fn that creates a thumbnail to use as pager anchor
        pagerAnchorBuilder: function(idx, slide) {
            //determine sizeLimit: will force the thumbs into square shape (cropping may occur)
            var sizeLimit = '';
            var jSlide = $(slide);
            if (jSlide.attr("limitthumbwidth") == 'True') {
                sizeLimit = "width=77px;";
            }
            else {
                sizeLimit = "height=77px;";
            }
            return '<li><a href="#"><div class="divCrop"><img src="' + jSlide.attr("src") + '&thumb=1" class="thumb" ' + sizeLimit + '/></div></a>' + jSlide.attr("title") + '</li>';
        }
    });

    $('#nav a').each(
    function() {
        SlideCount++;
    });

    //Pause on start
    $('#divPics').cycle('pause');

    SetPagerState(1, SlideCount);
    SetThumbPagerState(0, SlideCount);

    //Set ThumbPager Click events
    $('#tPagerPrev').click(function() { SetThumbPagerState_Direct(FilmStripLeft); });
    $('#tPagerNext').click(function() { SetThumbPagerState_Direct(CurrentFilmStripIndex + 1); });

    //Set StartStop link events
    $('#divStartStop').click(function() {
        var startText = 'Start Slideshow';
        var stopText = 'Stop Slideshow';
        var currentText = $(this).html();
        if (currentText == startText) {
            $('#divPics').cycle('resume');
            $(this).html(stopText);
        }
        else {
            $('#divPics').cycle('pause');
            $(this).html(startText);
        };
    });
});

function onBefore(slideIn, slideOut, options) {
    //$('#output').html("Scrolling image:<br>" + this.src);
    //window.console.log(  $(this).parent().children().index(this) );
}
function onAfter(slideIn, slideOut, options) {
    var content = $(this).children('img')[0].alt//read content from image alt
    $('#output').html(content);
    var index = options.currSlide;

    SetPagerState(index + 1, options.slideCount);
    SetThumbPagerState(index, options.slideCount);
}
function SetPagerState(currentItem, totalItems) {
    $('#sPagerState').html(currentItem + '/' + totalItems);
}
//Automatic control for the current thumb pager set.
//called with each transition
function SetThumbPagerState(index, slideCount) {
    //check index ranges and wrap if needed
    if (index > slideCount) {
        index = 0;
    }
    if (index < 0) {
        index = slideCount - 1;
    }
    //current thumb page
    var currentTShiftIndex = index;

    SetThumbPagerState_Direct(currentTShiftIndex);
}

function SetThumbPagerState_Direct(tShiftIndex) {
    //set current thumb index

    //collect some status information first
    var indexOfFirstItemWhenAtEndOfFilmStrip = SlideCount - FilmStripItems; //can never shift farther than this
    var indexOfLastItemWhenAtStartOfFilmStrip = Math.min(SlideCount - 1, FilmStripItems - 1);
    //if left arrow was clicked then the index to shift to is not necessarily CurrentFilmStripIndex - 1 so we must determine what it really is
    //this kind of results in a missuse of the CurrentFilmStripIndex since the currenrtly highlighted and displayed image no longer corresponds to this index. It autocorrects when the user clicks a thumb though. If time find a better way.
    if (tShiftIndex == FilmStripLeft) {
        if (CurrentFilmStripIndex > indexOfFirstItemWhenAtEndOfFilmStrip) {
            tShiftIndex = indexOfFirstItemWhenAtEndOfFilmStrip - 1;
        }
        else {
            tShiftIndex = CurrentFilmStripIndex - 1;
        }
    }
    //
    var currentlyAtEndofFilmStrip = CurrentFilmStripIndex >= indexOfFirstItemWhenAtEndOfFilmStrip;
    var movingToEndOfFilmStrip = tShiftIndex >= indexOfFirstItemWhenAtEndOfFilmStrip;
    var movingWithinEndOfFilmStrip = currentlyAtEndofFilmStrip && movingToEndOfFilmStrip;
    //
    var currentlyAtStartOfFilmStrip = CurrentFilmStripIndex <= indexOfLastItemWhenAtStartOfFilmStrip;
    var movingToStartOfFilmStrip = tShiftIndex <= indexOfLastItemWhenAtStartOfFilmStrip;
    var movingWithinStartOfFilmStrip = currentlyAtStartOfFilmStrip && movingToStartOfFilmStrip;
    //
    var showPrevTButton = tShiftIndex > 0 && SlideCount > FilmStripItems;
    var showNextTButton = tShiftIndex < indexOfFirstItemWhenAtEndOfFilmStrip;
    //
    //    //var movingForward = CurrentFilmStripIndex < tShiftIndex;
    var animateIndex = tShiftIndex;
    var filmStripChangeNeeded = true;
    //do not animate if moving within the end or star
    if (movingWithinEndOfFilmStrip) {
        filmStripChangeNeeded = false;
    }

    //update global var
    CurrentFilmStripIndex = tShiftIndex;
    if (tShiftIndex > indexOfFirstItemWhenAtEndOfFilmStrip) {
        animateIndex = indexOfFirstItemWhenAtEndOfFilmStrip;
    }

    //show/hide next/prev
    $('#tPagerPrev')[showPrevTButton ? 'show' : 'hide']();
    $('#tPagerNext')[showNextTButton ? 'show' : 'hide']();

    if (filmStripChangeNeeded) {
        //animate thumb slide
        //FilmStripItemWidth
        var slideOffset = FilmStripItemWidth * animateIndex;
        $("#nav").animate({
            left: "-" + slideOffset + "px"
        }, { queue: false, duration: 1000 });
    }
}
