﻿
$(document).ready(function() { 
    // set up scrollable
    var scrollableOptions = {
        clickable: false,
        speed: 750,
        size: 1
    }
    
    var autoScrollOptions = {
        autoplay: true, // when enabled the scrolling starts automatically upon page load.
        interval: 5000, // the time (in milliseconds) between autoscrolls.
        autopause: true, // when carousel is mouseovered the autoscrolling will *pause*
        api: true // http://flowplayer.org/tools/using.html#api
    }

    // get actual no of items
    var carouselItems = $("#ADT-Carousel .scrollable li");

    // if there's more than one item turn it in to a carousel
    if (carouselItems.length > 1) {

        // create ref to <ul> under main promos
        var carouselNav = $("#ADT-Carousel-Nav ul");

        // create 'previous' btn
        carouselNav.append('<li><a class="prev" title="Previous" href="#">&lt;</a></li>');

        // for each carousel main promos
        carouselItems.each(function(index) {

            var liHtml = "";
            liHtml = "<li><a href=\"#\">" + (index + 1) + "</a></li>";

            // append each new <li> to nav ul
            $("#ADT-Carousel-Nav ul").append(liHtml);

        });

        // create 'next' btn
        carouselNav.append('<li><a class="next" title="Next" href="#">&gt;</a></li>');

        // create ref to the new nav <li>'s but exclude prev and next
        var carouselNavLis = carouselNav.find("li").not(":first").not(":last");

        // create ref to api and init carousel
        window.carouselApi = $("#ADT-Carousel").scrollable(scrollableOptions).circular().autoscroll(autoScrollOptions);     
        
        // add click function
        carouselNavLis.click(function(e) {
            e.preventDefault();
            var no = $(this).find("a").text()
            currentIndex = no;
            carouselApi.seekTo(no);
        });

        // set background when clicked
        window.carouselApi.onBeforeSeek(function(event, index) {
            // clear all backgrounds
            carouselNavLis.attr("class", "");
            // if we're at the end, update index;
            if (index > carouselNavLis.length) {
                index = 1;
            }
            carouselNavLis.eq(index - 1).attr("class", "ADT-Carousel-Nav-Selected");
        });

        // ensure that we highlight first one
        carouselNavLis.eq(0).attr("class", "ADT-Carousel-Nav-Selected");

        // center <ul>
        var liWidth = 40; // width:30px + margin-left:10px
        var ulWidth = $("#ADT-Carousel-Nav ul li").length * liWidth;
        var navWidth = $("#ADT-Carousel-Nav").width();
        var marginLeft = (navWidth / 2) - (ulWidth / 2);

        $("#ADT-Carousel-Nav ul").css({ "margin-left": parseInt(marginLeft) + "px" });

    }

});
