﻿
// initialize the video sliders.
$(document).ready(function() {
    $('table.imageSlider').each(function() { $(this).updateImageSlider($('tr:first > td > div > div:visible', this)); })
});

// does the work of sliding from one to the next.
jQuery.fn.moveImageSlider = function(dir, effect, ms, pending) {

    // get the image divs
    var images = this.find('tr:first > td > div > div');

    // if there are pending clicks, queue this one up.
    if (images.get(0).pendingClicks > 0 && !pending) {
        ++images.get(0).pendingClicks;
        return;
    }

    // get the visible image and its index
    var visibleImage = this.find('tr:first > td > div > div:visible');
    var currentIdx = this.find('tr:first > td > div > div').index(visibleImage);

    // get the next index, if -1 change to last index, if last index + 1 change to 0
    var nextIdx = currentIdx + dir;
    if (nextIdx == -1)
        nextIdx = images.length - 1;
    else if (nextIdx == images.length)
        nextIdx = 0;
    var nextImg = $(images.get(nextIdx));

    // finalization routine
    var finalization = function() {
        // hide the visible image
        visibleImage.hide();
        // ensure inline z-index
        visibleImage.css({ 'z-index': 0, 'filter' : '' });
        nextImg.css({ 'z-index': 0 });

        // ensure pendingClicks does not go below zero
        images.get(0).pendingClicks
            = Math.max(images.get(0).pendingClicks - 1, 0);
        // if there are more pending clicks, keep going.
        if (images.get(0).pendingClicks > 0)
            $(this).closest('table.imageSlider').moveImageSlider(dir, effect, ms, true);
    };

    // increment pending clicks
    images.get(0).pendingClicks =
        (!images.get(0).pendingClicks) ? 1 : images.get(0).pendingClicks++;

    // ensure css and positioning
    visibleImage.css({ 'z-index': 100, 'position' : 'absolute' });
    nextImg.css({ 'z-index': 99, 'position': 'relative', 'zoom': 1 });
    nextImg.show();
    
    //update the text of the video slider
    this.updateImageSlider(nextImg);
    
    // do the slide!
    if (effect == 'fade')
        visibleImage.fadeOut(ms, finalization);
    else if (effect == 'slideup')
        visibleImage.slideUp(ms, finalization);
    else
        visibleImage.hide(effect, ms, finalization);
}

// updates the labels of the video slider
jQuery.fn.updateImageSlider = function(image, title) {

    try 
    {
        var title = image.children('input[type="hidden"]').val().split('|');
        var id = this.get(0).id;

        this.find('#' + id + '_Title').text(title[0]);
        this.find('#' + id + '_Duration').text('(' + title[1] + ')');
        this.find('#' + id + '_Catalog').text(
            (this.find('tr:first > td > div > div').index(image) + 1) + ' of ' +
             this.find('tr:first > td > div > div').length
        );
    }
    catch (ex) { }
}
       