$j(document).ready(function() {
    /*
        This carousel code handles any number of carousels on the page with the appropriate html structure.
        The arrow elements have the carousel passed into their data cache in order to track which
        carousel their controls are related to.
    */
    $j('.dynamic-product-listing-carousel-wrapper').each(function() {
        var carousel = this;

        var number_of_items = $j('.dynamic-product-listing > li', carousel).length;
        var number_of_pages = Math.ceil(number_of_items / 2) - 1;

        $j('.dynamic-product-listing', carousel).css('width', (number_of_items * 346) + 'px');

        $j(this).data('number-of-pages', number_of_pages);
        $j(this).data('page', 0);   // initialise the 'current page'
    
        $j('.left-arrow', carousel).click(function() {
            var carousel = $j(this).data('carousel');

            var page_number = parseInt($j(carousel).data('page'));
            if (page_number > 0) {
                $j(carousel).data('page', page_number - 1).trigger('update-position');
            }
        }).data('carousel', carousel);

        $j('.right-arrow', carousel).click(function() {
            var carousel = $j(this).data('carousel');

            var page_number = parseInt($j(carousel).data('page'));
            var number_of_pages = $j(carousel).data('number-of-pages');

            if (page_number < number_of_pages) {
                $j(carousel).data('page', page_number + 1);
                $j(carousel).trigger('update-position');
            }
        }).data('carousel', carousel);

    }).bind('update-position', function() {

        /* Custom jQuery event for handling the transitions. */
        $j('.brand-list').stop();

        var left_offset = $j(this).data('page') * -690;

        $j('.dynamic-product-listing', this).animate({
            'left': left_offset + 'px'
        }, 600, 'swing');

/*
        $j('.dynamic-product-listing li', this).animate({
            'opacity': '0.5'
        }, 300, 'swing').animate({
            'opacity': '1'
        }, 300, 'swing');
*/

        var page_number = parseInt($j(this).data('page'));
        var number_of_pages = $j(this).data('number-of-pages');

        if (page_number > 0) {
            $j('.left-arrow', this).addClass('brandarrow_left_lit');
            $j('.left-arrow', this).removeClass('brandarrow_left');
        } else {
            $j('.left-arrow', this).addClass('brandarrow_left');
            $j('.left-arrow', this).removeClass('brandarrow_left_lit');
        }

        if (page_number < number_of_pages) {
            $j('.right-arrow', this).addClass('brandarrow_right_lit');
            $j('.right-arrow', this).removeClass('brandarrow_right');
        } else {
            $j('.right-arrow', this).addClass('brandarrow_right');
            $j('.right-arrow', this).removeClass('brandarrow_right_lit');
        }
    }).trigger('update-position');
});

