﻿var slideshowCurrentUrl;

function setSlideshow(ix, images, placeholder) {
    var overlay = $('#'+placeholder+' img:eq(1)');
    var container = $('#'+placeholder+' img:first');
    var noTransition = arguments[3] || false;
    
    // reset timeout until next slide
    var interval = $.data(container[0], 'interval');
    if(interval)
        window.clearTimeout(interval);

    var img = images[ix];
    if (img) {
        var src = img.src;
        overlay.animate({ opacity: 0 }, 0, 'linear', function() {
        
            overlay.attr('src', src);
        
            slideshowCurrentUrl = img.title; 
            
            overlay.css('cursor', slideshowCurrentUrl ? 'pointer' : '');
            container.css('cursor', slideshowCurrentUrl ? 'pointer' : '');
            
            var callback = $.data(container[0], 'callback');
            if(typeof callback == 'function')
                callback(ix);
                
            overlay.animate({ opacity: 1 }, noTransition ? 0 : 1500, 'linear', function() {
                $.data(container[0], 'cycleId', ix);
                container.attr('src', src);
                
                $.data(container[0], 'interval', window.setTimeout(function() {
                    slideshowCycleInterval(images, placeholder);
                }, $.data(container[0], 'timeout')));
                
            });
        });
    }
}

function setSlideCallback(placeholder, callback) {
    var container = $('#'+placeholder+' img:first');
    $.data(container[0], 'callback', callback);
}

function slideshowImageClick() {
    if(slideshowCurrentUrl)
        location.href = slideshowCurrentUrl;
}

function slideshowCycleInterval(images, placeholder) {
    var container = $('#'+placeholder+' img:first');
    var reverse = !!arguments[2];

    var cycleId = jQuery.data(container[0], 'cycleId');

    cycleId += (reverse ? -1 : 1);

    if (cycleId >= images.length)
        cycleId = 0;
        
    if (cycleId < 0)
        cycleId = images.length-1;

    setSlideshow(cycleId, images, placeholder);
}

function startSlideshow(imgcontainer, placeholder, timeout) {
    var images = $('#'+imgcontainer+' img');

    var overlay = $('#'+placeholder+' img:eq(1)');
    var container = $('#'+placeholder+' img:first');
    
    jQuery.data(container[0], 'timeout', timeout);

    setSlideshow(0, images, placeholder, true);

    overlay.click(slideshowImageClick);
    container.click(slideshowImageClick);
}
