﻿var delays = new Array();
var timers = new Array();

function startSlideshow(id) {
    var container = document.getElementById(id);
    if ($(container).css('display') == 'none')
        $(container).show();
        
    delays[id] = 5000;
    timers[id] = setInterval('slideSwitch("' + id + '")', delays[id]);
    $(container).find('.switcher div').click(function() {
        // Display the image and select this div
        var this$ = $(this);
        var index = parseInt(this$.attr('id').substr(this$.attr('id').lastIndexOf('_') + 1));
        $(container).find('.images>div').removeClass('active');
        var activeImg = $($(container).find('.images>div')[index]);
        activeImg.addClass('active');
        this$.siblings().removeClass('active last-active');
        this$.addClass('active');

        // If an image is displayed by clicking on the div then display the image for twice as long
        clearInterval(timers[id]);
        delays[id] = 10000;
        timers[id] = setInterval('slideSwitch("' + id + '")', delays[id]);
    });
}

function slideSwitch(id) {
    var container = document.getElementById(id);
    // Reset the delay if it was set on click
    delays[id] = 5000;
    
    if ($(container).css('display') == 'none')
        $(container).show();
    // Change the image and the switch
    var container = document.getElementById(id);
    var $activeImg = $(container).find('.images .active');
    if ($activeImg.length == 0) $activeImg = $(container).find('.images>div:last');
    var $nextImg = $activeImg.next().length ? $activeImg.next()
        : $(container).find('.images>div:first');

    var $activeSwitch = $(container).find('.switcher .active');
    if ($activeSwitch.length == 0) $activeSwitch = $(container).find('.switcher div:last');
    var $nextSwitch = $activeSwitch.next().length ? $activeSwitch.next()
        : $(container).find('.switcher div:first');

    $nextImg.css({ opacity: 0.0 })
        .addClass('active')
        .animate({ opacity: 1.0 }, 1000, function() {
            if ($(container).css('display') == 'none')
                $(container).show();
            
            $activeImg.removeClass('active last-active');
            // If the delay is different for this image then clear the old timer and set a new one
            var _delay = parseInt($nextImg.attr('delay'));
            if (delays[id] != _delay) {
                clearInterval(timers[id]);
                delays[id] = _delay;
                timers[id] = setInterval('slideSwitch("' + id + '")', delays[id]);
            }
        });

    $nextSwitch.addClass('active');
    $activeSwitch.removeClass('active');

}

function LinkClicked(url) {
    window.open(url);
}
