var tcc = tcc || {};
var SPLASH = SPLASH || {};
SPLASH.isCarouselAdAvailable = function () {
    return typeof (CAROUSELAD) != "undefined" && $.isPlainObject(CAROUSELAD);
};
tcc.carousel1 = function ($elements, config) {
    function init($wrapper) {
        var options = {
            adOutOfCarouselClickSources: null, // clicking on the element(s) specified by this selector advances the carousel to the ad and expands it
            adHoverExpandTime: 500, // ms to wait after mouse over before expanding the ad
            adHoverContractTime: 500, // ms to wait after mouse out before contracting the ad
            adInsertionIndex: 2,
            autoplay: true,
            autoplayCancelAfterInteraction: false,
            autoplayInterval: 1000,
            autoplayPauseOnHover: true,
            carouselHeight: 374,
            expandedAssetWidth: 1002,
            infiniteScroll: false,
            standardImageWidth: 500,
            standardItemWidth: 0,
            offsetItemsConfig: {
                offsetDistance: 0,
                offsetItemsWithIndexGreaterThan: 0
            },
            pagingAnimationTime: 500
        };
        $.extend(options, config);

        // variable to hold references to various elements
        var $pagingControls, $pages, $carousel, $viewport, $ad, $adImage, $adCloseButton, $expansionTrackingIFrame, $nextButton, $previousButton;
        var adExpanded = false;
        var currentPageIndex = 0;
        var originalXOffset = 0;
        var pageWidths = new Array();
        var adHoverStartTime;
        var adHoverEndTime;
        var adClosing = false; // set to true whilst animating ad closure due to user clicking the close button
        var carouselSwfPlaceholderElementId = "carouselSwf";
        var isCurrentlyAnimating = false;
        var currentPageCssClass = "current";

        function moveToNextPage() {
            moveToPage(currentPageIndex + 1 == pageCount ? 0 : currentPageIndex + 1, true);
        };

        function moveToPreviousPage() {
            moveToPage(currentPageIndex - 1 < 0 ? pageCount - 1 : currentPageIndex - 1, true);
        };

        // change the page in the carousel
        function moveToPage(index, animate, callback, firstLoad) {
            $pages.stop(true, true);
            currentPageIndex = index;

            // update paging controls
            $pagingControls.filter("." + currentPageCssClass).removeClass(currentPageCssClass);
            $($pagingControls.get(index)).addClass(currentPageCssClass);

            // helper functions
            function moveToOtherEnd($carouselItem, leftPos, callback) {
                $carouselItem.fadeOut(0, function () {
                    $carouselItem.css("left", leftPos);
                    $carouselItem.fadeIn(options.pagingAnimationTime, callback);
                });
            };

            var $currentPage = $($pages.get(index));
            if (!firstLoad) {
                var currentPageOffset = parseInt($currentPage.css("left"));
                $pages.filter("." + currentPageCssClass).removeClass(currentPageCssClass);
                $currentPage.addClass(currentPageCssClass);
                //$currentPage.animate({ left: 0 }, options.pagingAnimationTime, function () { $currentPage.addClass(currentPageCssClass); });
                // move current page to primary position
                var lastPageIndex = $pages.length - 1;
                if (currentPageOffset != 0) {
                    var directionToMove = currentPageOffset < 0 ? "R" : "L";
                    var positionsToMove = Math.round(currentPageOffset % options.standardItemWidth == 0 ? currentPageOffset / options.standardItemWidth : (currentPageOffset - options.offsetItemsConfig.offsetDistance) / options.standardItemWidth);
                    positionsToMove = positionsToMove < 0 ? positionsToMove * -1 : positionsToMove;
                    $pages.each(function (index) {
                        var $carouselItem = $(this);
                        var carouselItemOffset = parseInt($carouselItem.css("left"));
                        var newCarouselItemOffset = positionsToMove * options.standardItemWidth * (directionToMove == "L" ? -1 : 1) + carouselItemOffset + (carouselItemOffset <= 0 && carouselItemOffset + (positionsToMove * options.standardItemWidth) >= options.standardItemWidth * (options.offsetItemsConfig.offsetItemsWithIndexGreaterThan + 1) && directionToMove == "R" ? options.offsetItemsConfig.offsetDistance : 0) - (directionToMove == "L" && carouselItemOffset > 0 && (carouselItemOffset - options.offsetItemsConfig.offsetDistance) / options.standardItemWidth <= positionsToMove ? options.offsetItemsConfig.offsetDistance : 0);
                        $carouselItem.stop(true, true);
//                        $carouselItem.css("left", newCarouselItemOffset);
//                        if (index == lastPageIndex) {
//                            ensurePrimaryItemIsCentred();
//                        }
                        $carouselItem.animate({ left: newCarouselItemOffset }, options.pagingAnimationTime, index == lastPageIndex ? ensurePrimaryItemIsCentred : null);
                    });
                }
            } else {
                ensurePrimaryItemIsCentred();
            }

            function ensurePrimaryItemIsCentred() {
                // reposition all pages so primary position is in the centre of the carousel
                var rightCount = Math.ceil((pageCount - 1) / 2);
                var rightItems = new Array();
                $currentPage.nextAll().each(function (index) {
                    if (index < rightCount) {
                        rightItems.push($(this));
                    } else {
                        return false;
                    }
                });
                if (rightItems.length < rightCount) {
                    var requiredItemCount = rightCount - rightItems.length;
                    $currentPage.prevAll().reverse().each(function (index) {
                        if (index < requiredItemCount) {
                            rightItems.push($(this));
                        } else {
                            return false;
                        }
                    });
                }
                var leftCount = Math.floor((pageCount - 1) / 2);
                var leftItems = new Array();
                $currentPage.prevAll().each(function (index) {
                    if (index < leftCount) {
                        leftItems.push($(this));
                    } else {
                        return false;
                    }
                });
                if (leftItems.length < leftCount) {
                    var requiredItemCount = leftCount - leftItems.length;
                    $currentPage.nextAll().reverse().each(function (index) {
                        if (index < requiredItemCount) {
                            leftItems.push($(this));
                        } else {
                            return false;
                        }
                    });
                }
                $.each(leftItems, function (indexInArray, valueOfElement) {
                    var $carouselItem = $(valueOfElement);
                    var currentLeftPos = parseInt($carouselItem.css("left"));
                    var newLeftPos = (indexInArray + 1) * options.standardItemWidth * -1;
                    var posDelta = currentLeftPos > newLeftPos ? currentLeftPos - newLeftPos : newLeftPos - currentLeftPos;
                    var longMove = posDelta > options.standardItemWidth + options.offsetItemsConfig.offsetDistance;
                    if (longMove) {
                        moveToOtherEnd($carouselItem, newLeftPos, rightItems.length == 0 && callback && indexInArray == leftItems.length - 1 && $.isFunction(callback) ? callback : null);
                    } else if (firstLoad == true) {
                        $carouselItem.stop(true, true);
                        $carouselItem.animate({ left: newLeftPos }, options.pagingAnimationTime, rightItems.length == 0 && callback && indexInArray == leftItems.length - 1 && $.isFunction(callback) ? callback : null);
                    }
                });
                $.each(rightItems, function (indexInArray, valueOfElement) {
                    var $carouselItem = $(valueOfElement);
                    var currentLeftPos = parseInt($carouselItem.css("left"));
                    var newLeftPos = ((indexInArray + 1) * options.standardItemWidth) + options.offsetItemsConfig.offsetDistance;
                    var posDelta = currentLeftPos > newLeftPos ? currentLeftPos - newLeftPos : newLeftPos - currentLeftPos;
                    var longMove = posDelta > options.standardItemWidth + options.offsetItemsConfig.offsetDistance;
                    if (longMove) {
                        moveToOtherEnd($carouselItem, newLeftPos, callback && indexInArray == rightItems.length - 1 && $.isFunction(callback) ? callback : null);
                    } else if (firstLoad == true) {
                        $carouselItem.stop(true, true);
                        $carouselItem.animate({ left: newLeftPos }, options.pagingAnimationTime, callback && indexInArray == rightItems.length - 1 && $.isFunction(callback) ? callback : null);
                    }
                });
            };

            // check if there is an expanded ad to be shown
            if (SPLASH.isCarouselAdAvailable() && CAROUSELAD.expandedAssetImageUrl && $($pages.get(index)).filter(".ad").length > 0) {
                // ad expansion/contraction code
                function contractAd(event, callback) {
                    $ad.stop();
                    if (event) {
                        event.stopPropagation();
                        event.preventDefault();
                    }
                    $ad.animate({ width: options.standardImageWidth }, 500, "swing", function () {
                        var $swfAd = $("#" + carouselSwfPlaceholderElementId);
                        if ($swfAd.length > 0) {
                            $swfAd.remove();
                        }
                        $adImage.load(
                            function () {
                                adExpanded = false;
                                $adImage.attr("width", options.standardImageWidth);
                                $adImage.unbind("load");
                                $ad.removeClass("expanded");
                                if (CAROUSELAD.expandedAssetFlashUrl && CAROUSELAD.expandedAssetFlashUrl.length > 0) {
                                    $ad.removeClass("expandedSwf");
                                }
                                unlinkAd();
                                if ($.isFunction(callback)) {
                                    callback();
                                }
                            }
                        );
                        if ($adImage.attr("src") == CAROUSELAD.inPlaceImageUrl) {
                            $adImage.load();
                        } else {
                            $adImage.attr("src", CAROUSELAD.inPlaceImageUrl);
                        }
                    });
                };
                function expandAd() {
                    if (adExpanded) {
                        return;
                    }
                    $ad.stop();
                    adExpanded = true;
                    // handle expansion tracking if necessary
                    if (CAROUSELAD.expansionTrackingUrl && $expansionTrackingIFrame.length > 0) {
                        var url = CAROUSELAD.expansionTrackingUrl + (CAROUSELAD.expansionTrackingUrl.indexOf("?") == -1 ? "?" : "&") + Math.random();
                        $expansionTrackingIFrame.attr("src", url);
                    }
                    function performExpansion() {
                        $ad.addClass("expanded");
                        if (CAROUSELAD.expandedAssetFlashUrl && CAROUSELAD.expandedAssetFlashUrl.length > 0) {
                            $ad.addClass("expandedSwf");
                        }
                        $ad.animate({ width: options.expandedAssetWidth }, 500, "swing");
                    };
                    // insert the expanded asset
                    if (CAROUSELAD.expandedAssetFlashUrl && CAROUSELAD.expandedAssetFlashUrl.length > 0) {
                        $ad.prepend("<div id=\"" + carouselSwfPlaceholderElementId + "\">" + (CAROUSELAD.expandedAssetImageUrl && CAROUSELAD.expandedAssetImageUrl.length > 0 ? "<img alt=\"\" height=\"" + options.carouselHeight + "\" src=\"" + UTILITIES.htmlEncode(CAROUSELAD.expandedAssetImageUrl) + "\" width=\"" + options.expandedAssetWidth + "\" />" : "") + "</div>");
                        var flashvars = {};
                        if (CAROUSELAD.linkUrl && CAROUSELAD.linkUrl.length > 0) {
                            flashvars.clickTag = CAROUSELAD.linkUrl;
                        }
                        var params = { wmode: "transparent" };
                        var attributes = {};
                        swfobject.embedSWF(CAROUSELAD.expandedAssetFlashUrl, carouselSwfPlaceholderElementId, options.expandedAssetWidth, options.carouselHeight, "9.0.0", "expressInstall.swf", flashvars, params, attributes);
                        performExpansion();
                    } else {
                        $adImage.load(
                            function () {
                                $adImage.attr("width", options.expandedAssetWidth);
                                $adImage.unbind("load");
                                linkAd();
                                performExpansion();
                            }
                        );
                        $adImage.attr("src", CAROUSELAD.expandedAssetImageUrl);
                    }
                };
                $adCloseButton.click(
                    function (e) {
                        adClosing = true;
                        contractAd(e, function () { adClosing = false; });
                    }
                );
                $ad.click(
                    function () {
                        expandAd();
                    }
                ).mouseout(function () {
                    adHoverStartTime = null;
                    adHoverEndTime = new Date().getTime();
                    setTimeout(function () {
                        if (adHoverEndTime && new Date().getTime() - adHoverEndTime >= options.adHoverContractTime * .9) {
                            contractAd();
                        }
                    }, options.adHoverContractTime);
                }).mouseover(function () {
                    adHoverStartTime = new Date().getTime();
                    adHoverEndTime = null;
                    setTimeout(function () {
                        if (!adClosing && !isCurrentlyAnimating && adHoverStartTime && new Date().getTime() - adHoverStartTime >= options.adHoverExpandTime * .9) {
                            if (options.autoplayCancelAfterInteraction) {
                                autoplayCancelledDueToUserInteraction = true;
                            }
                            expandAd();
                        }
                    }, options.adHoverExpandTime);
                });
                if (adExpanded && !$currentPage.hasClass("ad")) {
                    contractAd();
                }
            } else if ($ad && $ad.length > 0) {
                $ad.unbind("click").unbind("mouseout").unbind("mouseover");
                $adCloseButton.unbind("click");
            }
        };

        // add a link around the ad image
        function linkAd() {
            if (CAROUSELAD.linkUrl) {
                $adImage.wrap("<a href=\"" + UTILITIES.htmlEncode(CAROUSELAD.linkUrl) + "\" target=\"_blank\" />");
            }
        };

        // remove a link around the ad image
        function unlinkAd() {
            if (CAROUSELAD.linkUrl) {
                $ad.find("a img").unwrap();
            }
        };

        // set the carousel's viewport at 100% width
        function setViewportCss(animate) {
            // reset values to defaults before measuring
            $viewport.css("margin-left", 0).css("margin-right", 0);

            // measure and adjust the viewport to take up the full width of the display
            var leftPos = originalXOffset = parseInt($viewport.offset().left);
            $viewport.css("margin-left", leftPos > 0 ? leftPos * -1 : 0);
            var rightPos = ($(window).width() - leftPos - $viewport.offsetParent().width());
            var rightMargin = rightPos > 0 ? rightPos * -1 : 0;
            if (animate) {
                $viewport.animate({ marginRight: rightMargin }, 500, "swing");
            } else {
                $viewport.css("margin-right", rightMargin);
            }
            $carousel.css("left", leftPos);

            if (options.infiniteScroll === true) {
                $nextButton.css("right", rightPos * -1);
                $previousButton.css("left", leftPos * -1);
            }

            // reposition list items etc
            if (!animate) {
                moveToPage(currentPageIndex, false);
            }
        }

        // set the variables
        $carousel = $wrapper.children(".images");
        $pages = $carousel.children();

        // check if there is an advertisement to insert
        if (SPLASH.isCarouselAdAvailable() && CAROUSELAD.inPlaceImageUrl && UTILITIES.isInt(options.adInsertionIndex) && options.adInsertionIndex >= 0) {
            // make sure the insertion index is valid
            if (options.adInsertionIndex >= $pages.length) {
                options.adInsertionIndex = $pages.length - 1;
            }
            // insert the advertisement
            var adHtml = "<li class=\"ad carouselItem\"><img alt=\"\" class=\"carouselImage\" height=\"" + options.carouselHeight + "\" src=\"" + UTILITIES.htmlEncode(CAROUSELAD.inPlaceImageUrl) + "\" width=\"" + options.standardImageWidth + "\" /><span class=\"closeAd sir\">Close</span></li>";
            // insert the ad
            if (options.adInsertionIndex > 0) {
                $($pages.get(options.adInsertionIndex - 1)).after(adHtml);
            } else {
                $wrapper.prepend(adHtml);
            }
            // re-set the value of $pages as we have just added an extra page
            $pages = $carousel.children();

            // check if there are any external controls that should display the ad in the carousel
            if (options.adOutOfCarouselClickSources) {
                var $adOutOfCarouselClickElements = $(options.adOutOfCarouselClickSources);
                if ($adOutOfCarouselClickElements.length > 0) {
                    $adOutOfCarouselClickElements.click(function () {
                        if (options.autoplayCancelAfterInteraction) {
                            autoplayCancelledDueToUserInteraction = true;
                        }
                        moveToPage($ad.index(), true, function () {
                            $ad.click();
                        });
                    });
                }
            }

            // save reference to ad elements in local variables
            $ad = $pages.filter(".ad");
            $adCloseButton = $ad.children(".closeAd");
            $adImage = $ad.children("img");

            // check if we have a tracking URL and ad an iframe for it if we do
            if (CAROUSELAD.expansionTrackingUrl) {
                var trackingIFrameId = "CarouselAdExpansionTrackingIFrame";
                $("body").append("<iframe class=\"visuallyhidden\" id=\"" + trackingIFrameId + "\" style=\"height:1px;width:1px\" />");
                $expansionTrackingIFrame = $("#" + trackingIFrameId);
            }
        }

        // cache page widths
        $pages.each(
            function (index, element) {
                var $element = $(element);
                $element.addClass("item" + index);
                pageWidths.push($element.outerWidth(true));
            }
        );

        // add paging controls
        var pageCount = $pages.length;
        if (pageCount > 0) {
            // create the paging HTML
            var pagingHtml = "<ol class=\"paging\">";
            for (var i = 0; i < pageCount; i++) {
                pagingHtml += "<li></li>";
            }
            pagingHtml += "</ol>";
            // add the paging HTML to the DOM
            $wrapper.append(pagingHtml);
            // save the controls in a variable
            $pagingControls = $wrapper.find(".paging li");
            // wire up click events on the controls
            $pagingControls.click(
                function () {
                    if (options.autoplayCancelAfterInteraction === true) {
                        autoplayCancelledDueToUserInteraction = true;
                    }
                    moveToPage($pagingControls.index($(this)), true);
                }
            );
            // indicate the first page is currently displayed
            $($pagingControls.get(0)).addClass("current");

            // next/previous buttons
            if (options.infiniteScroll === true) {
                $wrapper.append("<ul class=\"pagingNextPrev\"><li class=\"previous\"></li><li class=\"next\"></li></ul>");
                $nextButton = $(".pagingNextPrev .next");
                $nextButton.click(function () { if (options.autoplayCancelAfterInteraction === true) { autoplayCancelledDueToUserInteraction = true; } moveToNextPage(); });
                $previousButton = $(".pagingNextPrev .previous");
                $previousButton.click(function () { if (options.autoplayCancelAfterInteraction === true) { autoplayCancelledDueToUserInteraction = true; } moveToPreviousPage(); });
            }
        }

        // set the height of the wrapper element
        $wrapper.height($wrapper.height());
        // create a viewport, this is the element that'll allow full width display of the carousel
        $carousel.wrap("<div class=\"carouselViewport\" />");
        $viewport = $wrapper.children(".carouselViewport");
        // position the viewport
        setViewportCss(true);
        // position listitems
        moveToPage(0, true, function () { $pages.filter(":first-child").css("z-index", "auto"); }, true);
        // resize the viewport when the window is resized
        $(window).resize(function () { setViewportCss(false); });

        // autoplay
        var autoplayCancelledDueToUserInteraction = false;
        if (options.autoplay && options.autoplayInterval > 0) {
            var autoplayEnabled = options.autoplay;
            var lastHoverTime = new Date().getTime();
            function autoplay() {
                if (autoplayCancelledDueToUserInteraction) {
                    return;
                }
                var nextRunDelay;
                if (!options.autoplayPauseOnHover || (autoplayEnabled && !adExpanded && lastHoverTime + options.autoplayInterval < new Date().getTime())) {
                    moveToPage(currentPageIndex == pageCount - 1 ? 0 : currentPageIndex + 1, true);
                    nextRunDelay = options.autoplayInterval;
                } else {
                    nextRunDelay = 100;
                }
                setTimeout(autoplay, nextRunDelay);
            }
            $wrapper.hover(
                function () {
                    autoplayEnabled = false;
                },
                function () {
                    autoplayEnabled = true;
                    lastHoverTime = new Date().getTime();
                }
            );
            setTimeout(autoplay, options.autoplayInterval);
        }
    }
    $elements.each(function (index, element) { init($(element)); });
};
tcc.carousel2 = function ($elements, config) {
    var options = {
        pagingAnimationTime: 500,
        adOutOfCarouselClickSources: null, // clicking on the element(s) specified by this selector advances the carousel to the ad and pauses autoplay
        adHoverExpandTime: 500, // ms to wait after mouse over before expanding the ad
        adHoverContractTime: 500, // ms to wait after mouse out before contracting the ad
        adInsertionIndex: null,
        autoplay: true,
        carouselHeight: null,
        standardImageWidth: null,
        expandedAssetWidth: null
    };
    $.extend(options, config);
    function init($wrapper) {
        // variable to hold references to various elements
        var $pagingControls, $pages, $carousel, $ad, $adImage, $adCloseButton;
        var currentPageIndex = 0;
        var pageWidths = new Array();
        var autoplayEnabled = options.autoplay;
        var isCurrentlyAnimating = false;

        // flags
        var adExpanded = false;
        // add a link around the ad image
        function linkAd() {
            if (CAROUSELAD.linkUrl) {
                $adImage.wrap("<a href=\"" + UTILITIES.htmlEncode(CAROUSELAD.linkUrl) + "\" target=\"_blank\" />");
            }
        };
        // remove a link around the ad image
        function unlinkAd() {
            if (CAROUSELAD.linkUrl) {
                $ad.find("a img").unwrap();
            }
        };
        // function for moving between pages
        function moveToPage(index) {
            isCurrentlyAnimating = true;
            $carousel.stop();
            if ($ad && $ad.length) {
                $ad.stop();
                // TODO: Move the binding of these events back into here
                $ad.unbind("mouseenter").unbind("mouseleave");
            }
            currentPageIndex = index;
            $pagingControls.filter(".current").removeClass("current");
            $($pagingControls.get(index)).addClass("current");
            var offset = 0;
            for (var i = 0; i < index; i++) {
                offset += pageWidths[i];
            }
            $carousel.animate({ left: offset * -1 }, options.pagingAnimationTime, "swing", function () { isCurrentlyAnimating = false; });
        };
        // set the width of the carousel
        function setCarouselWidth() {
            var totalWidth = 0;
            $pages.each(
                function (index, element) {
                    totalWidth += $(element).outerWidth(true);
                }
            );
            $carousel.width(totalWidth);
        };

        // save the carousel to a variable
        $carousel = $wrapper.children(".images");
        // save the pages to a variable
        $pages = $carousel.children();
        // if there are one or no pages don't bother doing anything else
        if ($pages.length < 1) {
            return;
        }

        // check if there is an advertisement to insert
        if (SPLASH.isCarouselAdAvailable() && CAROUSELAD.inPlaceImageUrl && UTILITIES.isInt(options.adInsertionIndex) && options.adInsertionIndex >= 0) {
            // make sure the insertion index is valid
            if (options.adInsertionIndex >= $pages.length) {
                options.adInsertionIndex = $pages.length - 1;
            }
            // insert the advertisement
            var adHtml = "<li class=\"ad carouselItem\"><img alt=\"\" class=\"carouselAdImage\" src=\"" + UTILITIES.htmlEncode(CAROUSELAD.inPlaceImageUrl) + "\" /><span class=\"closeAd sir\">Close</span></li>";
            // insert the ad
            if (options.adInsertionIndex > 0) {
                $($pages.get(options.adInsertionIndex - 1)).after(adHtml);
            } else {
                $wrapper.prepend(adHtml);
            }
            // re-set the value of $pages as we have just added an extra page
            $pages = $wrapper.children(".images").children();

            // check if there are any external controls that should display the ad in the carousel
            if (options.adOutOfCarouselClickSources) {
                var $adOutOfCarouselClickElements = $(options.adOutOfCarouselClickSources);
                if ($adOutOfCarouselClickElements.length > 0) {
                    $adOutOfCarouselClickElements.click(function () {
                        autoplayEnabled = false;
                        moveToPage($ad.index(), true, function () {
                            $ad.click();
                        });
                    });
                }
            }

            // save reference to ad elements in local variables
            $ad = $pages.filter(".ad");
            $adCloseButton = $ad.children(".closeAd");
            $adImage = $ad.children("img");

            // check if there is an expanded ad to be shown
            if (CAROUSELAD.expandedAssetImageUrl && CAROUSELAD.expandedAssetImageUrl.length > 0) {
                // flags
                var adHoverStartTime;
                var adHoverEndTime;
                var adClosing = false; // set to true whilst animating ad closure due to user clicking the close button
                var carouselSwfPlaceholderElementId = "carouselSwf";
                var $expansionTrackingIFrame = null;
                // ad expansion/contraction code
                function contractAd(event, callback) {
                    $wrapper.stop();
                    if (event) {
                        event.stopPropagation();
                        event.preventDefault();
                    }
                    $wrapper.animate({ width: options.standardImageWidth }, 500, "swing", function () {
                        setCarouselWidth();
                        var $swfAd = $("#" + carouselSwfPlaceholderElementId);
                        if ($swfAd.length > 0) {
                            $swfAd.remove();
                        }
                        $adImage.load(
                            function () {
                                adExpanded = false;
                                $adImage.unbind("load");
                                $ad.removeClass("expanded");
                                if (CAROUSELAD.expandedAssetFlashUrl && CAROUSELAD.expandedAssetFlashUrl.length > 0) {
                                    $ad.removeClass("expandedSwf");
                                }
                                unlinkAd();
                                if ($.isFunction(callback)) {
                                    callback();
                                }
                            }
                        );
                        if ($adImage.attr("src") == CAROUSELAD.inPlaceImageUrl) {
                            $adImage.load();
                        } else {
                            $adImage.attr("src", CAROUSELAD.inPlaceImageUrl);
                        }
                    });
                };
                function expandAd() {
                    if (adExpanded) {
                        return;
                    }
                    $wrapper.stop();
                    adExpanded = true;
                    // handle expansion tracking if necessary
                    if (CAROUSELAD.expansionTrackingUrl && $expansionTrackingIFrame.length > 0) {
                        var url = CAROUSELAD.expansionTrackingUrl + (CAROUSELAD.expansionTrackingUrl.indexOf("?") == -1 ? "?" : "&") + Math.random();
                        $expansionTrackingIFrame.attr("src", url);
                    }
                    function performExpansion() {
                        $ad.addClass("expanded");
                        if (CAROUSELAD.expandedAssetFlashUrl && CAROUSELAD.expandedAssetFlashUrl.length > 0) {
                            $ad.addClass("expandedSwf");
                        }
                        $wrapper.animate({ width: options.expandedAssetWidth }, 500, "swing", setCarouselWidth);
                    };
                    // insert the expanded asset
                    if (CAROUSELAD.expandedAssetFlashUrl && CAROUSELAD.expandedAssetFlashUrl.length > 0) {
                        $ad.prepend("<div id=\"" + carouselSwfPlaceholderElementId + "\">" + (CAROUSELAD.expandedAssetImageUrl && CAROUSELAD.expandedAssetImageUrl.length > 0 ? "<img alt=\"\" height=\"" + options.carouselHeight + "\" src=\"" + UTILITIES.htmlEncode(CAROUSELAD.expandedAssetImageUrl) + "\" width=\"" + options.expandedAssetWidth + "\" />" : "") + "</div>");
                        var flashvars = {};
                        if (CAROUSELAD.linkUrl && CAROUSELAD.linkUrl.length > 0) {
                            flashvars.clickTag = CAROUSELAD.linkUrl;
                        }
                        var params = { wmode: "transparent" };
                        var attributes = {};
                        swfobject.embedSWF(CAROUSELAD.expandedAssetFlashUrl, carouselSwfPlaceholderElementId, options.expandedAssetWidth, options.carouselHeight, "9.0.0", "expressInstall.swf", flashvars, params, attributes);
                        performExpansion();
                    } else {
                        $adImage.load(
                            function () {
                                $adImage.unbind("load");
                                linkAd();
                                performExpansion();
                            }
                        );
                        $adImage.attr("src", CAROUSELAD.expandedAssetImageUrl);
                    }
                };
                $adCloseButton.click(
                    function (e) {
                        adClosing = true;
                        contractAd(e, function () { adClosing = false; });
                    }
                );
                $ad.click(
                    function () {
                        expandAd();
                    }
                ).mouseout(function () {
                    adHoverStartTime = null;
                    adHoverEndTime = new Date().getTime();
                    setTimeout(function () {
                        if (adHoverEndTime && new Date().getTime() - adHoverEndTime >= options.adHoverContractTime * .9) {
                            contractAd();
                        }
                    }, options.adHoverContractTime);
                }).mouseover(function () {
                    adHoverStartTime = new Date().getTime();
                    adHoverEndTime = null;
                    setTimeout(function () {
                        if (!adClosing && !isCurrentlyAnimating && adHoverStartTime && new Date().getTime() - adHoverStartTime >= options.adHoverExpandTime * .9) {
                            expandAd();
                        }
                    }, options.adHoverExpandTime);
                });
                if (CAROUSELAD.expansionTrackingUrl) {
                    var trackingIFrameId = "CarouselAdExpansionTrackingIFrame";
                    $("body").append("<iframe class=\"visuallyhidden\" id=\"" + trackingIFrameId + "\" style=\"height:1px;width:1px\" />");
                    $expansionTrackingIFrame = $("#" + trackingIFrameId);
                }
            } else if (CAROUSELAD.linkUrl) { // no expanded URL, but there is a link
                linkAd();
            }
        }

        // set the width
        setCarouselWidth();
        // cache page widths
        $pages.each(
            function (index, element) {
                pageWidths.push($(element).outerWidth(true));
            }
        );
        // add paging controls
        var pageCount = $pages.length;
        if (pageCount > 0) {
            // create the paging HTML
            var pagingHtml = "<ol class=\"paging\">";
            for (var i = 0; i < pageCount; i++) {
                pagingHtml += "<li></li>";
            }
            pagingHtml += "</ol>";
            // add the paging HTML to the DOM
            $wrapper.append(pagingHtml);
            // save the controls in a variable
            $pagingControls = $wrapper.find(".paging li");
            // wire up click events on the controls
            $pagingControls.click(
                function () {
                    moveToPage($pagingControls.index($(this)));
                }
            );
            // indicate the first page is currently displayed
            $($pagingControls.get(0)).addClass("current");
        }
        // autoplay
        if (options.autoplay) {
            var lastHoverTime = new Date().getTime();
            function autoplay() {
                var nextRunDelay;
                if (autoplayEnabled && !adExpanded && lastHoverTime + 2000 < new Date().getTime()) {
                    moveToPage(currentPageIndex == pageCount - 1 ? 0 : currentPageIndex + 1);
                    nextRunDelay = 2000;
                } else {
                    nextRunDelay = 100;
                }
                setTimeout(autoplay, nextRunDelay);
            }
            $wrapper.hover(
                function () {
                    autoplayEnabled = false;
                },
                function () {
                    autoplayEnabled = true;
                    lastHoverTime = new Date().getTime();
                }
            );
            setTimeout(autoplay, 2000);
        }
    };
    $elements.each(function (index, element) { init($(element)); });
};
$(function () {
    tcc.carousel1($(".carouselInSeason"), { adInsertionIndex: 2, adOutOfCarouselClickSources: ".adRibbon img", autoplay: true, autoplayInterval: 5000, autoplayPauseOnHover: false, autoplayCancelAfterInteraction: true, carouselHeight: 374, expandedAssetWidth: 500, infiniteScroll: true, standardImageWidth: 500, standardItemWidth: 500, offsetItemsConfig: { offsetDistance: 0, offsetItemsWithIndexGreaterThan: 0 } });
    tcc.carousel2($(".carouselOutOfSeason"), { adInsertionIndex: 1, adOutOfCarouselClickSources: ".adRibbon img", carouselHeight: 374, expandedAssetWidth: 500, standardImageWidth: 500 });
});
