﻿var carouselAutomated = function(id, o) {
    this.init(id, o);
}
jQuery.extend(carouselAutomated.prototype, {
    autoScroll: true,       //configuration option
    _moveInterval: 10000,    //conguration option (interval in ms)
    options: null,
    carouselList: null,
    _scrollTimer: null,
    _carousel: null,
    _firstVisibleIndex: 0,   //zero based. The index returned from onAfterAnimation is one-based!

    init: function(id, o) {
        // Default configuration properties
        var defaults = { pageSize: 5, pageCountTextTemplate: null };
        var showPrevNext = false;

        // Cache references to key DOM elements
        this.carouselList = jQuery('#' + id);
        this.options = jQuery.extend({}, defaults, o || {});

        jQuery('li a.repeat', this.carouselList).each(function(i) {
            jQuery('div.teaser a', this.carourselList).addClass('hideForPrint');
            jQuery('div.teaser a', this.carourselList).removeClass('hide');     //hide exists so that if javascript is disabled, then hero image is not displayed.
        });

        var _self = this;

        // Initialise jcarousel
        var jc;

        var size = jQuery('#' + id).children('li').size();
        showPrevNext = size > this.options.pageSize + 1;
        var visible;

        jc = this.carouselList.jcarousel({
            vertical: false,
            scroll: this.options.pageSize,
            visible: showPrevNext ? this.options.pageSize : size,
            auto: 0,
            itemFirstInCallback: { onBeforeAnimation: function() { },
                onAfterAnimation: function(carousel, item, index, state) {
                    _self._firstVisibleIndex = index - 1;
                    _self._updatePageCountInfo(carousel);
                    if (!_self._isSelectionVisible(_self._firstVisibleIndex)) {
                        _self._setItemAsCurrent(item, true, true);
                    }
                }
            },
            buttonNextHTML: showPrevNext ? '<div></div>' : null,
            buttonPrevHTML: showPrevNext ? '<div></div>' : null,
            initCallback: this.autoScroll ? function(carousel) { _self._carousel = carousel; } : null
        });

        var outerCarouselWrapper = this.carouselList.parents('.jcarousel-container').parent();

        // Append default teaser panel
        var teaserPanelId = this.carouselList.attr('id') + '-teaser';

        var panelMarkup = String.format('<div id={0} class=nova-externalteaser-teaser></div>', teaserPanelId);

        outerCarouselWrapper.before(panelMarkup);

        // Set first item as current
        this._setItemAsCurrent(jQuery('.jcarousel-item:first', this.carouselList));

        // Set up hover state to select an item on hover. Note that an item is not "unselected" when hover is over
        // Pause minor autoscrolling if the user moves with the cursor over the clip.
        jQuery('#' + id + ' .jcarousel-item').hover(
                        function() {
                            // Set current item as 'the' selected item
                            _self._setItemAsCurrent(this, true);
                            _self.autoScroll ? window.clearInterval(_self._scrollTimer) : null;
                        },
                        function() {
                            if (_self.autoScroll) {
                                _self._scrollTimer = setInterval(function() {
                                    _self._moveSelection();
                                }, _self._moveInterval);
                            }
                        }
        );
        if (_self.autoScroll) {
            this._scrollTimer = setInterval(function() {
                _self._moveSelection();
            }, _self._moveInterval);
        }
    },

    //moves the selection along. performs scrolling if necessary.
    _moveSelection: function() {
        var nextItem = jQuery('#' + this.carouselList.attr('id') + ' .jcarousel-item.current').next();

        if (nextItem.length < 1) {
            this._setItemAsCurrent(jQuery('.jcarousel-item:first', this.carouselList), true);
        }
        else {
            this._setItemAsCurrent(nextItem, true);
        }

        if (!this._isSelectionVisible(this._firstVisibleIndex)) {
            var idx = this._getCurrentIndex();
            this._scroll(idx);
        }
    },

    //scrolls to the given index. index is zero-based
    _scroll: function(index) {
        if (this._carousel != null) {
            this._carousel.scroll(index + 1);   //jcarousel scroll index is 1-based
        }
    },

    // doesn't perform scroll. just highlights item
    _setItemAsCurrent: function(item, animate, afterScroll) {
        // Remove the 'current' state from the item that WAS 'current'
        jQuery('#' + this.carouselList.attr('id') + ' .jcarousel-item.current')
                                .removeClass('current');

        jQuery(item).addClass('current');

        // Get the current items teaser data and copy to the teaser panel
        jQuery('#' + this.carouselList.attr('id') + '-teaser').html(jQuery('.teaser', item).html());
    },

    //gets the (zero-based) index of the item.
    _getIndex: function(item) {
        return jQuery('.jcarousel-item').index(item);
    },

    //gets the (zero-based) index of the currently selected item.
    _getCurrentIndex: function() {
        var current = jQuery('.jcarousel-item.current');
        return this._getIndex(current);
    },

    // index is the index of the first visible list element - zero based.
    _isSelectionVisible: function(index) {
        var curIdx = this._getCurrentIndex();
        if (curIdx >= index && curIdx < index + this.options.pageSize) {
            return true;
        }
        else {
            return false;
        }
    },

    _updatePageCountInfo: function(carousel) {

        // Note the page count info is only displayed if a template has been supplied
        if (this.options.pageCountTextTemplate !== null) {
            var outerCarouselWrapper = carousel.list.parents('.jcarousel-container').parent();
            var pageCountElement = jQuery('.pageCount', outerCarouselWrapper);

            if (pageCountElement.length === 0) {
                // page count element not yet created, create it
                outerCarouselWrapper.prepend('<p class="pageCount"></p>');
                pageCountElement = jQuery('.pageCount', outerCarouselWrapper)
            }

            pageCountElement.html(String.format(this.options.pageCountTextTemplate,
                                            carousel.first,
                                            carousel.last,
                                            carousel.options.size));
        }
    }
});

if (!window.Nova) { window['Nova'] = {}; };
if (!window.Nova.Controls) { window['Nova']['Controls'] = {}; };
if (!window.Nova.Controls.Carousels) { window['Nova']['Controls']['Carousels'] = {}; };
window['Nova']['Controls']['Carousels']['Automated'] = carouselAutomated;