﻿//var DivDebug = null;
var RefCarousel = null;
var RefNextButton = null;
var RefPreviousButton = null;
var BalancesCount = 0;
var BalancesEachPage = 4;
var NumberOfSlides = 0;
var CurrentSlide = 0;
var skipAutoScrolling = false;
var IndexFirstItemLastSlide = 0;
var DisplayTime = 4; //Time in Seconds each Slide is displayed. Set to 0 if now Autoscrolling is wanted.
var ListItem = '<li></li>'; //invisible because contains no Content
var NumberOfItemsOnLastSlide = 0;
//rei:
var familyImages = [];
var allLoaded = false;

//$(function() {
function initializeCarousel() {    
    //DivDebug = $('#Debug');
    //get References and Number of Slides
    RefCarousel = $('#Carousel');
    RefPreviousButton = $('#CarouselPrevious');
    RefNextButton = $('#CarouselNext');

    BalancesCount = $('#Carousel > li').length;
    NumberOfSlides = getNumberOfSlides(BalancesCount, BalancesEachPage);
    IndexFirstItemLastSlide = (NumberOfSlides - 1) * BalancesEachPage + 1;
    NumberOfItemsOnLastSlide = BalancesCount - ((NumberOfSlides - 1) * BalancesEachPage);

    //for some Reasion, Slider stops if only 1 Element is on last slide. Therefore we eventually have to add 1 additional (invisible) List-Item.
    if (NumberOfItemsOnLastSlide == 1)
        RefCarousel.append(ListItem);

    if (NumberOfSlides == 1) {
        RefPreviousButton.addClass('invisible');
        RefNextButton.addClass('invisible');
        DisplayTime = 0; //no Autoscroll
    }

    //initialize Carousel
    if (RefCarousel.css('display') != 'none')
        RefCarousel.jcarousel({
            auto: DisplayTime,
            scroll: BalancesEachPage,
            wrap: 'circular',
            animation: 'slow',
            initCallback: carousel_initCallback,
            itemFirstInCallback: carousel_itemFirstInCallback,
            itemLastInCallback: carousel_itemLastInCallback
        });
}
//});

//called when Carousel is initialized
function carousel_initCallback(carousel) {

    RefCarousel = carousel; //replaces jQuery-Reference with Reference to Carousel (otherwise Function "goFirstSlide()" doesn't work)

    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });

    RefNextButton.bind('click', function() {
        carousel.stopAuto();
        skipAutoScrolling = true;

        if (CurrentSlide == NumberOfSlides) {
            CurrentSlide = 0;
            RefCarousel.scroll(1, false);
        } else {
            carousel.next();
        }
        return false;
    });

    RefPreviousButton.bind('click', function() {        
        carousel.stopAuto();
        skipAutoScrolling = true;

        if (CurrentSlide == 1) {
            RefCarousel.scroll(IndexFirstItemLastSlide, false);
            CurrentSlide = NumberOfSlides;
        } else {
            carousel.prev();
        }
        backgrounds_LoadNextBatch(false);
        return false;
    });
};

//called before Slide is rendered
function carousel_itemFirstInCallback(carousel, SlideIndex, CurrentItemIndex, Action) {

    var CurrentSlideBefore = CurrentSlide;
    
    switch (Action) {
        case 'init':
            CurrentSlide = 1;
            break;
        case 'next':
            CurrentSlide += 1;
            backgrounds_LoadNextBatch(true);
            break;
        case 'prev':
            CurrentSlide -= 1;
            //backgrounds_LoadNextBatch(false); //buggy here
            break;
    }

    if (CurrentSlide > NumberOfSlides)
        CurrentSlide = NumberOfSlides;

    if (CurrentSlide <= 0)
        CurrentSlide = 1;
}

//called after Slide is completely rendered
function carousel_itemLastInCallback(carousel) {

    if (CurrentSlide >= NumberOfSlides) {

        if (DisplayTime != 0 && !skipAutoScrolling) { //only if Autoscrolling is active (DisplayTime > 0)
            CurrentSlide = 2;
            setTimeout(goFirstSlide, 4000); //little bit of a hack ;-)
        }
    }
}

//goes to first Slide
function goFirstSlide() {
    RefCarousel.scroll(1, false);
}

//returns Number of Slides
function getNumberOfSlides(NumberOfItems, NumberOfItemsEachPage) {
    return Math.ceil(NumberOfItems / NumberOfItemsEachPage);
}

//added rei:
function loadSlider(res, wrapperUlName, pathToProducts, directlink) {
    if (res != null && res.length > 0) {
        var compareURL = "../compare-products.aspx?id1=" + (typeof(productID) !== 'undefined' ? productID : "");
        var startid = 2;
        var toAppend = [];
        $.each(res, function(i, item) {
            var bgrdImg = "background-image:url(/_img/products/img_" + item.ID + "_slider.jpg);";
            familyImages.push(
            {
                id: item.ID,
                bgrd: bgrdImg,
                loaded: false
            });
            if (directlink)
                toAppend.push('<li id="' + item.ID + '" class="item"><a href="' + (typeof (pathToProducts) !== 'undefined' ? pathToProducts : "") + 'product-families/' + item.ID + '.aspx"><div id="sliderImg_' + item.ID + '" class="productFamDiv_slider loading"></div></a><br /><p>' + item.Name + '</p></li>');
            else
                toAppend.push('<li id="' + item.ID + '" class="item"><a href="' + (typeof (pathToProducts) !== 'undefined' ? pathToProducts : "") + '../products.aspx?directSearch=' + item.ID + '"><div id="sliderImg_' + item.ID + '" class="productFamDiv_slider loading"></div></a><br /><p>' + item.Name + '</p></li>');
            compareURL += "&id" + startid + "=" + item.ID;
            startid++;
        });
        $("ul#" + wrapperUlName + "").append(toAppend.join(""));
        initializeCarousel();
        backgrounds_LoadNextBatch(true);
        return compareURL;
    }
}

function backgrounds_LoadNextBatch(forward) {
    if (!allLoaded) {
        var goOn = true;
        var count = 0;
        var totalToLoad = BalancesEachPage;
        var i = forward ? 0 : familyImages.length - 1;
        while (goOn) {
            if (forward && i == familyImages.length) {
                allLoaded = true;
                goOn = false;
            }
            else if (!forward && i == -1) {
                allLoaded = true;
                goOn = false;
            }      
            else {
                var curr = familyImages[i];
                if (!curr.loaded) {
                    var vImgDivs = $("ul#Carousel div#sliderImg_" + curr.id);
                    vImgDivs.removeClass("loading");
                    vImgDivs.attr("style", curr.bgrd);
                    curr.loaded = true;
                    count++;
                    if (count == totalToLoad)
                        goOn = false;
                }
                i = forward ? (i+1) : (i-1);
            }
        }
    }
}
