﻿(function ($) {
    $.fn.initRotatingPromo = function () {
        var currentPromoItem = 0;
        var tickerInterval;
        var promoItemCount = $('.rotatingAd').length;
        // this variable is written to a small script block by RotatingPromoContentBlockListing.ascx

        var tickerIntervalTimes;

        if (typeof rotatingPromoContentBlockListing_tickerIntervalTimes != 'undefined') {
            tickerIntervalTimes = rotatingPromoContentBlockListing_tickerIntervalTimes.split(',');
        }

        if (tickerIntervalTimes != null) {
            initRotatingPromo();
        }

        function initRotatingPromo() {

            $('.rotatingAd').first().show();

            // rollover, start 
            $('.rotatingAd').each(function (index) {
                $(this).mouseover(function () { stopTimer(); }).mouseout(function () { if (promoItemCount > 1) { startTimer(); } });
            });

            if (promoItemCount > 1) {
                startTimer();
            }
        }

        function startTimer() { tickerInterval = setInterval(nextPromoItem, tickerIntervalTimes[currentPromoItem]); }
        function stopTimer() { clearInterval(tickerInterval); }

        function resetTimer() {
            stopTimer();
            startTimer();
        }

        function nextPromoItem() {
            clearInterval(tickerInterval);
            var prevPromoItem = currentPromoItem;
            if (currentPromoItem < promoItemCount - 1) {
                currentPromoItem++;
            }
            else if (currentPromoItem == promoItemCount - 1) {
                currentPromoItem = 0;
            }

            $('.rotatingAd').eq(prevPromoItem).fadeOut(400);
            $('.rotatingAd').eq(currentPromoItem).delay(500).fadeIn(400);
            tickerInterval = setInterval(nextPromoItem, tickerIntervalTimes[currentPromoItem]);
            $('div[idx="' + prevPromoItem + '"]').removeClass("rotatingPromoIndicatorOn").addClass("rotatingPromoIndicatorOff");
            $('div[idx="' + currentPromoItem + '"]').removeClass("rotatingPromoIndicatorOff").addClass("rotatingPromoIndicatorOn");

        }
    };
})(jQuery);
