﻿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);
        
            $.data(container[0], 'click', img.title); 
            
            overlay.css('cursor', 'pointer');
            container.css('cursor', '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(container) {
    var slideshowCurrentUrl = $.data(container[0], 'click');
    if (slideshowCurrentUrl)
        location.href = slideshowCurrentUrl;
        /*
    else {
        var placeholder = container.closest('.slideshow-placeholder');
        var imgs = placeholder.prev('.slideshow-images').find('img');
        
        slideshowCycleInterval(imgs, placeholder.attr('id'));
    }
        */
}

function slideshowCycleInterval(images, placeholder) {
    var container = $('#'+placeholder+' img:first');

    var cycleId = jQuery.data(container[0], 'cycleId');

    cycleId++;

    if (cycleId >= images.length)
        cycleId = 0;

    setSlideshow(cycleId, images, placeholder);
}

function startSlideshow(imgcontainer, placeholder, timeout) {
    var images = $('#'+imgcontainer+' img');

    var overlay = $('#'+placeholder+' img:eq(1)');
    var container = $('#'+placeholder+' img:first');
    
    overlay.click(function() { slideshowImageClick(container); });
    container.click(function() { slideshowImageClick(container); });
    jQuery.data(container[0], 'timeout', timeout);

    setSlideshow(0, images, placeholder, true);
}