﻿//Prerequisites: jquery-1.2.6.min.js, jquery.cycle.all.min.js

var CurrentFilmStripIndex = 0;
var SlideCount = 0;
var FilmStripItems = 4;
var FilmStripItemWidth = 95;
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 content attribute of the slide
    $("#divPics span[id$='hfContent']").each(function () {
        $(this).parent().attr("content", 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);
        $(this).siblings("img")[0].alt = 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 jSlide = $(slide);
            var fullWidth = jSlide.children("img").attr('fullWidth');
            var fullHeight = jSlide.children("img").attr('fullHeight');
            var sizeAttrib = "fullWidth = '" + fullWidth + "' fullHeight='" + fullHeight + "'";
            return '<li><a><div class="divThumbStatus"><img src="' + jSlide.attr("src") + '&thumb=1" class="thumb" ' + sizeAttrib + ' /></div><span class="title">' + jSlide.attr("title") + '</span></a></li>';
        }
    });

    //Resize main image as needed to fit the area.
    var tsMain = new ThumbScaler(400, 400); //This is valid only for the default theme. 
    tsMain.SetupThumbnails("mainImage"); //mainImageCropBox is generated

    //Scale and Crop ThumbImages
    var ts1 = new ThumbScaler(77, 77);
    ts1.SetupThumbnails("thumb"); //thumbCropBox is generated

    $('#nav a').each(
    function () {
        SlideCount++;
    });

    //Note: Cycle will not load a thumbnail area if there is only 1 image in this gallery resulting in SlideCount = 0.
    //In this scenario hide the slide controls
    if (SlideCount == 0) {
        $('.divGallery').css("display", "none");
        
        $('.divGalleryEmpty').show();
    }

    //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 = $.trim($(this).html());
        if (currentText == startText) {
            $('#divPics').cycle("resume");
            $(this).html(stopText);
        }
        else {
            $('#divPics').cycle('pause');
            $(this).html(startText);
        };
    });

    //Show the gallery now that everything is setup
    $(".divGallery").css("visibility", "visible");
});

function onBefore(slideIn, slideOut, options) {
    //$('#output').html("Scrolling image:<br>" + this.src);
    //window.console.log(  $(this).parent().children().index(this) );
    var nextSlide = options.elements[options.nextSlide];
    $('#mainImageTitle').html(nextSlide.getAttribute("title"));
    $('#output').html(nextSlide.getAttribute("Content"));
}
function onAfter(slideIn, slideOut, options) {
  
    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: 800 });
    }
}


/*----------- ThumbScaler Class ------------*/

function ThumbScaler(dW, dH) {
    this.DestinationWidth = dW;
    this.DestinationHeight = dH;
    this.SourceWidth = 0;
    this.SourceHeight = 0;
    this.ScaledWidth = 0;
    this.ScaledHeight = 0;

    //Searches for all thumbnail images by class and then wraps them with a crop container and scales and shifts them to fit and fill the crop container.
    this.SetupThumbnails = function (imageCssClass) {
        var thumbData = this; //the reference to this is moved to thumbData so it can be used within the jquery each loop without creating ambiguity.
        $('.' + imageCssClass).each(function () {
            var thisImage = $(this);

            //Put the image in a crop box (should be setup to use destination width and height.
            thisImage.wrap("<div class='" + imageCssClass + "CropBox" + "'/>");

            thumbData.SourceWidth = thisImage.attr('fullWidth');
            thumbData.SourceHeight = thisImage.attr('fullHeight');


            //To fill the destination box with the source image thumbnail the thumbnail image must be resized to either the height or width of the destination box.
            if (thumbData.ScaledThumbWillFillDestinationBox("W")) {
                thisImage.attr("width", thumbData.DestinationWidth);
                //Shift the image up to center it in the crop box.
                var heightDiff = parseInt((thumbData.ScaledHeight - thumbData.DestinationHeight) / 2);
                thisImage.css("position", "relative");
                thisImage.css("top", "-" + heightDiff + "px");
            }
            else {
                //This function is called again to calculate the Scaled dimensions. We already know the result will be true though if it was false for "W"
                thumbData.ScaledThumbWillFillDestinationBox("H");
                thisImage.attr("height", thumbData.DestinationHeight);
                //Shift the image left to center it in the crop box.
                var widthDiff = parseInt((thumbData.ScaledWidth - thumbData.DestinationWidth) / 2);
                thisImage.css("position", "relative");
                thisImage.css("left", "-" + widthDiff + "px");
            }
        });
    };

    //Used to determine which type of scaling will result in a thumb image that fills the destination box.
    //This will almost always result in an image that is too large for the box. The box should be setup to crop that part of the image that is desired.
    this.ScaledThumbWillFillDestinationBox = function (sideToScaleTo) {
        if (sideToScaleTo == "W") {
            this.ScaledWidth = this.DestinationWidth;
            this.ScaledHeight = (this.ScaledWidth * this.SourceHeight) / this.SourceWidth;
            return this.ScaledHeight >= this.DestinationHeight;
        }
        else {
            this.ScaledHeight = this.DestinationHeight;
            this.ScaledWidth = (this.ScaledHeight * this.SourceWidth) / this.SourceHeight;
            return this.ScaledWidth >= this.DestinationWidth;
        }
    };
}
