$(document).ready(function() {
    
    if ($('body').eq(0).hasClass('pageWin')) {
        var store = null;

        // Boolean, set to true when the 'read more link' selected, 
        // used to check id the carosuel animation is triggered 
        // by the link;
        var readMore = false;     
        
        var items = [];  
        var slider = null;
        var isCompetition = $('body').hasClass('pageWin');
        var teasers = $(isCompetition ? '#winTeasers' : '#teasers');
        var template = "<li id='sn_@i1@' class='group_@i2@'>\n\
                        <a href='#'>\n\
                            <img alt='item @i1@' src='@base@Images/secondary-nav.png'/>\n\
                        </a>\n\
                    </li>\n";


        /**
         *  returns the unique id digit assigned to each carousel element;
         *  @param elem, HTMLElement selected (generally clicked) carousel element;   
         *  @return Number;
         */
        function getElementIndex(elem) {
            // uses jCarousel's custom attribute;
            return parseInt($(elem).closest('li').attr('jcarouselindex'));

        };


        /**
         *  builds the spotlight dots below the carousel;
         *  @param count, Number number of carousel items;   
         *  @return jQuery spotlight nav;
         */
        function createSpotlight(count) {
            var links = [];

            for (var i = 1; i<=count; i++) {
                var indx = i;
                links.push(template.slice(0)
                    .replace(/@(i\d+|\w+)@/g, function(match, p1) {
                        return p1 === 'i1' ? indx : p1 === 'i2' ?  
                            Math.ceil(indx/3) : base;
                }));
            };

            links.unshift("<div id='secondaryNav' class='nav'>\n<ul>\n");
            links.push("</ul>\n</div>\n")
            return teasers.after(links.join("\n")).next();
        };


        /**
         *  Fired before carousel animates;
         */
        function beforeAnimation() {
            if (slider) {
                slider.reset.call(slider.scope);
            };
        };


        /**
         *  Fired after carousel animates;
         */
        function afterAnimation() {
            if (readMore && slider) {
                readMore = false;
                showSlider(store.getCurrent());
            };
        };


        
        /**
         *  Define slider callbacks to enable trigger in of panel;
         *  @param o, Object collection of callbacks and scope ref;
         */
        function registerSlider(o) {
            slider = o;

            var start = store.getStart();
            // display panel if deep link set;
            if (start && cPos !== undefined) {
                showSlider(start);
            }
        };


        function showSlider(indx) {
            slider.update.call(slider.scope, store.get(indx, 'detail'), indx);
        };


        /**
         *  Called after the scroll animation, when an item isn't longer in the visible range of the carousel;
         *  @param carousel, jQuery requesting instance;
         *  @param item, HTMLElement carousel item;
         *  @param i, Number item index;
         *  @param state, String carousel action (prev, next or init);
         *  @param evt, String custom event;
         */
        function itemVisibleOut(carousel, item, i, state, evt) {
            carousel.remove(i);
        };


        /**
         *  Called after the scroll animation, when an item is in the visible range of the carousel;
         *  @param carousel, jQuery requesting instance;
         *  @param item, HTMLElement carousel item;
         *  @param i, Number item index;
         *  @param state, String carousel action (prev, next or init);
         *  @param evt, String custom event;
         */
        function itemVisibleIn(carousel, item, i, state, evt) {
            var indx = carousel.index(i, store.getItemsLength());
            var item = carousel.add(i, store.get(indx, 'panel'));
            if (! isCompetition) {
                item.attach(Flipper, {store: store});
            };
        };


        /**
         *  Called after initialisation of the carousel;
         *  @param carousel, jQuery newly created instance;
         */
        function carouselComplete(carousel) {

            if (isCompetition) {
                teasers.find('.more').live('click', function () {
                    if (! readMore) {
                        readMore = true;
                        var i = carousel.index(getElementIndex(this), store.getItemsLength());
                        //console.log(getElementIndex(this), store.getItemsLength(), carousel.index(getElementIndex(this), store.getItemsLength()));
                        // move selected item selected to start position...;
                        carousel.scroll(i);
                        // ...set selected item in store;
                        store.setCurrent(i);
                    };
                    return false;
                });
            } else {
                VideoPlayer.init(store);
            };

            $(document).bind('secondarynavchange', function (e, o) {
                carousel.scroll($.jcarousel.intval(o.id));
            });

        };


        /**
         *  Called when an item becomes the first one in the visible range of the carousel;
         *  @param carousel, jQuery requesting instance;
         *  @param item, HTMLElement carousel item;
         *  @param i, Number item index;
         *  @param state, String carousel action (prev, next or init);
         *  @param evt, String custom event;
         */
        function itemFirstIn(carousel, item, i, state, evt) {
            $(document).trigger('scrollcomplete', {id: i, group: Math.ceil(i/3)});
        };


        /**
         *  Attach the carousel and spotlight to page;
         *  @param count, Number carousel items count;
         */
        function createCarousel(count) {
             
            var start = store.getStart();

            // attach carousel;
            teasers.jcarousel({

                //scroll: 1,
                wrap: 'circular',

                itemVisibleInCallback:  { onBeforeAnimation: itemVisibleIn },
                itemVisibleOutCallback: { onAfterAnimation: itemVisibleOut },
                itemLoadCallback: {
                    onBeforeAnimation: beforeAnimation,
                    onAfterAnimation: afterAnimation
                },

                buttonNextHTML: '<div><img src="'+base+'Images/prev.png" alt="Next" /></div>',
                buttonPrevHTML: '<div><img src="'+base+'Images/next.png" alt="Prev" /></div>',

                itemFirstInCallback: itemFirstIn,
                initCallback: carouselComplete,
                start: start !== null ? start : 1
            });


            $('.jcarousel-prev').click(function() {
                $(document).trigger('carouselscroll');
            });

            $('.jcarousel-next').click(function() {
                $(document).trigger('carouselscroll');
            });

            //createSpotlight(count);
            //$('#secondaryNav').attach(Spotlight, {store: store});
        };


        function getVideoId(el) {
            var ret = null;
            var href = $(el).find('a').attr('href');
            if (href.indexOf('youtube') != -1) {
                ret = href.split('watch?v=').pop();
            };
            return ret;
        };


        function getSecondaryContent(el) {
            return $('<div />').append(el).html();
        };


        function getPrimaryContent(el) {
            var temp = [];
            var elems = $(el).find('.related');
            var href = $(el).find('a').attr('href');
            var target = $(el).find('a').attr('target');
            
            // collect required elements;
            elems.each(function() {
                temp.push($('<div>').append(this).html());
            });

            temp.unshift('<a href="'+href+'" '+(target === '_blank' ? 'target='+target : '')+'>');
            temp.push('</a>');

            // remove original;
            elems.remove();
           
            // add to items;
            return temp.join('\n');
        };


        if (isCompetition) {

            // create sliding panel for competitions...;
            $("<div id='sldr'>\
                <div class='gutter'></div>\
                <div class='ft'></div>\
                <span class='close'>close</span>\
             </div>").appendTo('body');

            // ...and attach behaviour;
            $('#sldr').attach(Slider, {connect: registerSlider});

            // attach sliding panel tab behaviour;
            $('.panel').attach(Panel);

            teasers.find('li').each(function (i) {

                var el = $(this).find('.gutter').contents().unwrap();
                
                items.push({
                    identifer: 'ci_' + (i+1),
                    group: Math.ceil((i+1)/3),
                    video: getVideoId(this),
                    detail: getSecondaryContent(el), 
                    panel: $(this).html()
                });

            });

            $('#share2').remove();

        } else {

            teasers.find('li').each(function (i) {

                var id = 'ci_' + (i+1);
                var el = $(this).find('.gutter');

                $(this).find('div').attr('id', id);
                
                items.push({
                    identifer: id,
                    group: Math.ceil((i+1)/3),
                    video: getVideoId(this),
                    detail: getPrimaryContent(this), 
                    panel: getSecondaryContent(el)
                });

            });

            //$('#share2').attach(Share);
        };

        store = new Store();
        store.initalise(items, {callback: createCarousel, scope: this});

    };

});
