﻿// jquery.slideshow.js
// Written by http://www.vestras.net

/// <reference path="jquery-1.4.1.js" />
/// <reference path="jquery.center.js" />

// Constant value - determines the interval between automagic image changing.
var autoAnimateInterval = 5000;
var intervalId;
var selectedButton = undefined;

$.fn.slideshow = function ($centerSlideshow) {
    $slideshow = $(this);
    if ($centerSlideshow) {
        $slideshow.center({
            horizontal: true,
            vertical: false
        });
    }

    // Initialization of css values on related elements in the DOM.
    $buttons = $slideshow.find("ul li");
    $buttons.css({
        opacity: 0.5
    });
    $buttons.eq(0).css({
        opacity: 1.0
    });
    selectedButton = $buttons.eq(0);
    $buttons.parent().css("width", 25 * $buttons.length);
    $buttons.parent().center({
        horizontal: true,
        vertical: false
    });

    // Initialization of css values on the products in the slideshow.
    $items = $slideshow.find(".product");
    $items.css({
        display: "none"
    });
    $items.eq(0).css({
        display: "block"
    });

    // Displays the next product in the slideshow.
    function displayNext() {
        $nextButton = undefined;
        if (selectedButton.attr("id") == $buttons.last().attr("id")) {
            $nextButton = $buttons.eq(0);
        }
        else {
            $nextButton = selectedButton.next();
        }

        $nextButton.animate({
            opacity: 1
        }, 600);
        $idToLoad = $nextButton.find("a").attr("href");
        $slideshow.find("div:visible").fadeOut("slow", function () {
            $slideshow.find($idToLoad).fadeIn("slow");
        });
        $nextButton.siblings("li").animate({
            opacity: 0.5
        }, 600);
        selectedButton = $nextButton;
    }

    // Hook up the slideshow buttons' click event.
    $slideshow.find("li").click(function () {
        $clicked = $(this);
        selectedButton = $clicked;

        // Fade the item that the clicked button represents in, and fade out the currently visible div.
        if ($clicked.css("opacity") != "1" && $clicked.is(":not(animated)")) {
            $clicked.animate({
                opacity: 1
            }, 600);
            $idToLoad = $clicked.find("a").attr("href");
            $slideshow.find("div:visible").fadeOut("fast", function () {
                $slideshow.find($idToLoad).fadeIn();
            });
        }

        // Find all other slideshow buttons than the clicked and fade them out.
        $clicked.siblings("li").animate({
            opacity: 0.5
        }, 600);
        clearInterval(intervalId);
        intervalId = setInterval(displayNext, autoAnimateInterval);
    });
    clearInterval(intervalId);
    intervalId = setInterval(displayNext, autoAnimateInterval);
}
