﻿var carouselExternalTeaser = function(id, o) {
    this.init(id, o);
}
jQuery.extend(carouselExternalTeaser.prototype, {
    options: null,
    carouselList: null,

    init: function(id, o) {
        // Default configuration properties
        var defaults = { pageSize: 4, pageCountTextTemplate: null };

        // Cache references to key DOM elements
        this.carouselList = jQuery('#' + id);
        this.options = jQuery.extend({}, defaults, o || {});

        // Append associated teaser panel pointer to body. Added to body because of absolute positioning rules
        this.carouselList.parents('.nova-carousel-container').append(String.format('<div id={0}-teaser-pointer class=nova-externalteaser-teaser-pointer></div>', this.carouselList.attr('id')));

        jQuery('li a.repeat', this.carouselList).each(function(i) {
            jQuery(this).next('div.teaser').prepend(jQuery(this).clone());
            jQuery('div.teaser a', this.carourselList).addClass('hideForPrint');
        });

        var _self = this;

        // Initialise jcarousel
        var jc = this.carouselList.jcarousel({
            vertical: false,
            scroll: this.options.pageSize,
            visible: this.options.pageSize,
            itemFirstInCallback: { onBeforeAnimation: function() { },
                onAfterAnimation: function(carousel, item, index, state) {
                    _self._updatePageCountInfo(carousel)
                    _self._setItemAsCurrent(item, false);
                }
            }
        });

        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.after(panelMarkup);

        //TODO Ned a more elegany way of switching heights on teaser panel if we ar repeating images
        if (jQuery('li a.repeat', this.carouselList).length > 0) {
            jQuery('#' + teaserPanelId).addClass('withImage');
        }

        // Fade out all items by default
        jQuery('.jcarousel-item', this.carouselList).css('opacity', 0.6);

        // 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
        jQuery('#' + id + ' .jcarousel-item').hover(
                        function() {
                            // Set current item as 'the' selected item
                            _self._setItemAsCurrent(this, true);
                        },
                        function() {

                        }
                                                        );

    },

    _setItemAsCurrent: function(item, animate) {
        // Remove the 'current' state from the item that WAS 'current'
        jQuery('#' + this.carouselList.attr('id') + ' .jcarousel-item.current')
                                .animate({ opacity: 0.6 }, 'fast')
                                .removeClass('current');

        jQuery(item).addClass('current');

        // Raise the opacity
        jQuery(item).animate({ opacity: 1.0 });

        this._alignTeaserPointer(this.carouselList, animate);

        // Get the current items teaser data and copy to the teaser panel
        jQuery('#' + this.carouselList.attr('id') + '-teaser').html(jQuery('.teaser', item).html());
    },

    _alignTeaserPointer: function(carouselList, animate) {
        // Align the teaser type 1 pointer to the selected item
        if (jQuery(' li.current', carouselList).length > 0) {
            var teaserPointer = jQuery('#' + carouselList.attr('id') + '-teaser-pointer');
            var teaserPanel = jQuery('#' + carouselList.attr('id') + '-teaser');

            if (teaserPanel.length > 0) {
                // Position the pointer ontop of the teaserPanel
                teaserPointer.css('top', teaserPanel.position().top);

                // We need to horizontally position the pointer about the middle of the item's content
                var currentItem = jQuery('li.current', carouselList).children()[0];

                // This is the left position of the current item offset from the . jcarousel-skin-nova-default
                var leftPosOfCurrentItem = jQuery(currentItem).position().left + this.carouselList.parents('.jcarousel-container').position().left

                leftPosOfCurrentItem = leftPosOfCurrentItem + carouselList.position().left;

                var teaserPointerWidth = teaserPointer.width();

                // Stop any animations as we are about to move it
                teaserPointer.stop();
                var leftPos = (leftPosOfCurrentItem + (jQuery(currentItem).width() / 2)) - (teaserPointerWidth / 2);

                if (animate) {
                    teaserPointer.animate({ left: leftPos });
                } else {
                    teaserPointer.css({ left: leftPos });
                }
            }
        }
    },

    _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']['ExternalTeaser'] = carouselExternalTeaser;
