﻿
var currentProductIndex = 0;
var totalProducts = 0;
var currentlyAnimatingProduct = -1;
var productCopySelector = ".jRotatorPanel .Image_{0}";
var intervalId = 0;

// ----------- Product rotation code ----------- //

function displayProduct(productIndex, isShow) {
    var productElement = $(String.format(".jRotatorPanel .Image_{0}", productIndex)).stop();
    if (isShow) {
        productElement.show();
        productElement.fadeTo(0, 1.0);
    }
    else
        productElement.hide();
}

function rotateProduct() {
    scrollProduct((currentProductIndex + 1) % totalProducts);
}

function startRotator() {
    stopRotator();
    intervalId = setInterval("rotateProduct()", 4000);
}

function stopRotator() {
    if (intervalId != 0)
        clearInterval(intervalId);
    intervalId = 0;
}

function fadeProduct(productIndex, isFadeIn, callback) {
    var productElement = $(String.format(".jRotatorPanel .Image_{0}", productIndex)).stop();

    if (isFadeIn)
        productElement.fadeTo(200, 1.0, callback);
    else
        productElement.fadeOut(200, callback);
}

// hide current product, fade in product at targetProduct
function scrollProduct(targetProduct) {
    // don't interfere with animation unless changed mind
    if (targetProduct == currentlyAnimatingProduct)
        return;
    if (targetProduct == currentProductIndex)
        return; // cannot go 'back' to a product while animating away from it


    if (currentlyAnimatingProduct >= 0) {
        // if already mid-animation, jump ahead to the end of the last animation to begin this
        displayProduct(currentProductIndex, false);
        displayProduct(currentlyAnimatingProduct, true);
        currentProductIndex = currentlyAnimatingProduct;
    }

    currentlyAnimatingProduct = targetProduct;
    var target = String.format(".jRotatorPanel .Image_{0}", targetProduct);
    var current = String.format(".jRotatorPanel .Image_{0}", currentProductIndex);

    // let's do this animation
    fadeProduct(currentProductIndex, false, function() {
        fadeProduct(targetProduct, true, function() {
            displayProduct(currentProductIndex, false);
            currentProductIndex = currentlyAnimatingProduct;
            currentlyAnimatingProduct = -1;
        });
    });
}


$(function() {
    // setup the product rotator, or do nothing if not given
    $(".jRotatorPanel .Image:first").each(function() {
        $(this).show();
        totalProducts = $(".jRotatorPanel .Image").size();
        currentProductIndex = 0;
        startRotator();
    });

    // setup the right hand menu
    $(".jRotatorTriggers .ItemLink").each(function(index) {
        $(this).hover(function() {
            stopRotator();
            scrollProduct(index);
        }, function() {
            startRotator();
        });
    });
});