/* Yes, this is a big file. Lots of it is tracking, though. */

/* config */

CN.page.config = CN.page.config || {};
        // These should mirror the ones in pluckRatings.jspf for the site
        // They are required for pluckHelper functionality - note that the spaces are intentional to match line breaks in the jsp
CN.page.config.pluckRatingMarkup = '<div class="rating"> <h3>Ratings</h3> <div id="rating_' + CN.site.name + '_0000" class="rate"> <span>Rate it:</span> <div id="ratingGroup_' + CN.site.name + '_0000"> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_1" class="inactive">1 star</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_2" class="inactive">2 stars</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_3" class="inactive">3 stars</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_4" class="inactive">4 stars</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_5" class="inactive">5 stars</a> </div> <h4><span class="ratingtxt" id="ratingAverageTxtshort_' + CN.site.name + '_0000"> </span><span id="ratingAverage_' + CN.site.name + '_0000"></span></h4></div></div>';
CN.page.config.pluckCommentMarkup = '<div class="comments"> <h3>Comments</h3> <h5 class="totalComments" id="totalComments_' + CN.site.name + '_0000"></h5> <div class="commentAnchor" id="commentAnchor_' + CN.site.name + '_0000"></div> <div class="publicCommentsBox"> <h4>Post a Comment</h4> <form id="frmSubmitComment_' + CN.site.name + '_0000" action="" method="get" name="frmSubmitComment_' + CN.site.name + '_0000"> <input type="hidden" value="list" name="type" id="commentPageType_' + CN.site.name + '_0000"/> <input type="hidden" value="" name="title" id="commentPageTitle_' + CN.site.name + '_0000"/> <textarea id="commentText_' + CN.site.name + '_0000" class="commentText" name="text" rows="10" cols="58"/> <input type="image" id="frmPostBtn_' + CN.site.name + '_0000" class="post_btn" value="submit" name="submit" src="/css/i/pluck/submit_btn.gif"/> </form> </div> </div>';
CN.page.config.contributorUrl = '/w/bios/search/search?contributorName=';
CN.page.config.isJumpOnLoad = jQuery('html').hasClass('slideshow-showinitial-false'); // TODO: should the slideshow provide this property?

/* slideshow callbacks */

CN.page.config.slideshowIntroShowCallback = function(slideshow) {
    CN.dart.refresh();
    CN.stats.omniture.setPaginationValue('intro_show');
    CN.stats.omniture.trackAjaxPage();
};

CN.page.config.slideshowIntroHideCallback = function(slideshow) {
    CN.dart.refresh();
    CN.stats.omniture.setPaginationValue('intro_hide');
    CN.stats.omniture.trackAjaxPage();
};

CN.page.config.slideshowViewLargerCallback = function(larger, commands) {
    var configureSlide;

    configureSlide = function() {
                // This slideshow has horizontal and vertical slides; get the item page type and append a class
                // Note - using slides[index] because slide is perplexingly undefined if we visit VL from a DomSlide
        if (larger.slides[larger.currentSlideIndex].getLabel() === 'slide') {
            larger.$el.find('.item').each(function() {
                if (!this.className.match(/item(A|B)/)) {
                    jQuery(this).addClass('item' + CN.schemaParser.getInstance().parse(larger.data[larger.currentSlideIndex].item).pageType());
                }
            });
        }

        CN.page.buildAnnotations('.slideshow-view-larger-container', '.slideshow-view-larger-container .items');

        try {
            larger.$el.find('.item-inner').jScrollPane({ scrollbarWidth: 14, showArrows: true });
        } catch(e) {}
    };

    larger.onInterstitialShow.subscribe(function() {
        if (larger.slide.getLabel() === 'dartinterstitial') {
            try {
                CN.dart.call(CN.page.config.slideshowDartConfig.name,CN.page.config.slideshowDartConfig);
                CN.stats.omniture.setPaginationValue('slideshow_ad');
                CN.stats.omniture.trackAjaxPage();
            } catch(e) {
                CN.debug.log('Tried to perform dart request but failed. Perhaps no interstitial exists');
            }
        }
    });

            // Calls on complete and also when VL initially loads to hit the first slide
    larger.onSlideChangeComplete.subscribe(function() {
        configureSlide();
        if (larger.slide.getLabel() === 'slide') {
                    // Tracking
            CN.stats.omniture.setPaginationValue('slide' + (larger.currentSlideIndex + 1));
            CN.stats.omniture.trackAjaxPage();
        } else if (larger.slide.getLabel() === 'domslide') {
            CN.stats.omniture.setPaginationValue('slideshow_offer');
            CN.stats.omniture.trackAjaxPage();
        }
    });
    configureSlide();

            // We have to massage the replay button
    jQuery('<div id="slideshow-cm-replay-larger" class="slideshow-replay"><a href="#">Replay</a></div>').insertAfter('#slideshow-cm-replay').click(function() {
        commands.jumpToSlideCommand.execute(1);
        return false;
    });
};

CN.page.config.slideshowViewLargerCloseCallback = function(larger) {
    jQuery('#slideshow-cm-replay-larger').remove();
};

/* Slideshow dart configuration object */

CN.page.config.slideshowDartConfig = {
    name    : "slideshowInterstitial",
    sz      : "300x250",
    kws     : ["interstitial","top"],
    store   : false,
    ssready   : false
};

/************************
   INITIALIZE SLIDESHOW
************************/

        // If we are on a slideshow page
if (jQuery('body').hasClass('listC') && !CN.url.params().showall) {

            // Load plugins - remove pluck call if we aren't supporting pluck for a site
    jQuery('head').append('<script type="text/javascript" src="/js/cn-fe-content/pluck3/cn.pluckhelper.js"></script>');
    jQuery('head').append('<script type="text/javascript" src="/js/cn-fe-slideshow/pluck3/cn.slideshow.pluckhelper.js"></script>');
    if (CN.page.config.viewLarger) {
        jQuery('head').append('<script type="text/javascript" src="/js/cn-fe-slideshow/cn.slideshow.viewlarger.js"></script>');
    }

    jQuery(function() {
        var commands,
            pluckHelper,
            slideshow,
            slideChangeFns,
            toggleItemCommentBox;

                // Builds the slideshow
        CN.page.slideshow = new CN.slideshow.Slides('#items-container', {
            transition            : CN.page.config.transition            || 'photoflash',
            showInterstitialTimer : CN.page.config.showInterstitialTimer || 5,
            playTimer             : CN.page.config.playTimer             || 5,
            useHistory            : true,
            useIntro              : true
        });
        slideshow = CN.page.slideshow;

                // Pluck helper
        if (CN.slideshow.plugin.PluckHelper) {
            pluckHelper = new CN.slideshow.plugin.PluckHelper(slideshow, '#content');
        }

                // Removes the loading elements when slideshow is ready
        slideshow.onSlideshowReady.subscribe(function() {
            jQuery('.slideshow-loading').fadeOut('slow');
            jQuery('.slideshow-loading-message').fadeOut('slow', function() { jQuery(this).remove(); });
        });

                // Gets the slideshow data
        jQuery.ajax({
            type     : 'GET',
            url      : '/services/ajax' + location.pathname + '?mainContent=false&relatedContent=true&documentId=' + CN.page.config.contentId,
            dataType : 'json',
            success  : function(json) {
                var items = json.relatedContent || {},
                    i,
                    il,
                    newSlide,
                    initParams;

                            // Defines the features that this slideshow will implement
                initParams = {
                    goForward     : { trigger: '#items-container .next a' },
                    goBackward    : { trigger: '#items-container .previous a' },
                    playSlideshow : { trigger: '#items-container .start a', sliderEl: '.stop' },
                    stopSlideshow : { trigger: '#items-container .stop a' }
                };

                if (CN.page.config.viewLarger === true) {
                    initParams.viewLarger = { trigger: '#items-container .viewlarger a', transition: 'fade' };
                    jQuery('#items-container .viewlarger a').bind('click', function() {
                        CN.stats.omniture.setPaginationValue('slideshow_enlarge');
                        CN.stats.omniture.trackAjaxPage();
                    });
                }

                if (CN.page.config.carousel === true) {
                    initParams.carouselNavigation = { container: '#item-navigation-container' };
                }

                if (CN.page.config.viewAll === true) {
                    initParams.viewAllNavigation = { trigger: '#items-container .viewall a' };
                }

                        // Initializes the slideshow if data is successful, and binds the data to the model
                commands = CN.slideshow.controller.init(CN.page.slideshow, initParams);
                slideshow.setData(items);

                        // Adds the slides into the slideshow
                for (i = 0, il = items.length; i < il; i++) {
                     newSlide = new CN.slideshow.Slide(items[i]);
                     slideshow.append(newSlide);
                }

                        // Scroll pane - these need to be set up before dataReady is called
                        // onSlideshowReady only if we have a JSP-delivered first slide
                if (jQuery('html').hasClass('slideshow-showinitial-true')) {
                    slideshow.onSlideshowReady.subscribe(function() {
                        try { slideshow.$el.find('.item-inner').jScrollPane({ scrollbarWidth: 14, showArrows: true }); } catch(e) {}
                    });
                }
                slideshow.onSlideChangeComplete.subscribe(function() {
                    try { slideshow.$el.find('.item-inner').jScrollPane({ scrollbarWidth: 14, showArrows: true }); } catch(e) {}
                });

                CN.slideshow.util.dataReady(slideshow);

                        // Consumer marketing slide replay function
                jQuery('#slideshow-cm-replay').click(function() {
                    commands.jumpToSlideCommand.execute(1);
                    return false;
                });

                jQuery('#items-container .start a').bind('click', function() {
                });

                jQuery('#items-container .stop a').bind('click', function() {
                });
            },
            error : function(xhr, textStatus) {
                        // Makes sure we remove the loading stuff if data fails, so the basic HTML version is still usable
                jQuery('.slideshow-loading').fadeOut('slow'); // we don't remove, because the div is used later to overlay the controls
                jQuery('.slideshow-loading-message').fadeOut('slow');
                CN.debug.error('Data load failed for slideshow, probably 404 or malformed data: ' + textStatus);
            }
        });

                // Repository for any functions that need to be run onForwardComplete, onBackwardComplete and onJumpToSlideComplete
        slideChangeFns = function() {
                    // This slideshow has horizontal and vertical slides; get the item page type and append a class
            if (slideshow.slide.getLabel() === 'slide') {
                slideshow.$el.find('.item').each(function() {
                    if (!this.className.match(/item(A|B)/)) {
                        jQuery(this).addClass('item' + CN.schemaParser.getInstance().parse(slideshow.data[slideshow.currentSlideIndex].item).pageType());
                    }
                });
                CN.page.buildAnnotations('#items-container', '#items-container .items');
                        // Tracking for actual DCT slides
                CN.stats.omniture.setPaginationValue('slide' + (slideshow.currentSlideIndex + 1)).trackAjaxPage();
            }
                    // Tracking for dom slides, assumed to be CM offers for our purposes...This only works if there never are other types of dom slides
            if (slideshow.slide.getLabel() === 'domslide') {
                CN.stats.omniture.setPaginationValue('slideshow_offer').trackAjaxPage();
            }
        };

                // Refreshes iframe ads
        slideshow.onForwardComplete.subscribe(function() {
            slideChangeFns();

            if (slideshow.slide.getLabel() === 'domslide') {
            } else {
                try {
                } catch(e) {}
            }
        });

                // Refreshes iframe ads
        slideshow.onBackwardComplete.subscribe(function() {
            slideChangeFns();

            if (slideshow.slide.getLabel() === 'domslide') {
            } else {
                try {
                } catch(e) {}
            }
        });

                // Refreshes iframe ads
        slideshow.onJumpToSlideComplete.subscribe(function() {
            slideChangeFns();

            if (slideshow.slide.getLabel() === 'domslide') {
            } else {
                try {
                } catch(e) {}
            }
        });

        slideshow.onSlideChangeComplete.subscribe(function() {
                    // Refresh ads
            CN.dart.refresh();
            slideshow.getSocialMediaButtons((slideshow.currentSlideIndex + 1));
        });

        // Generates social media buttons
        slideshow.getSocialMediaButtons = function(slide) {
            CN.page.config.url = jQuery('link[rel=canonical]').attr('href') + "?slide=" + slide;
            CN.socialmedia.getFacebookLike().getTweet();
            FB.XFBML.parse();
        };

                // Populates iframe when interstitial ad is shown
        slideshow.onInterstitialShow.subscribe(function() {
            if (slideshow.slide.getLabel() === 'dartinterstitial') {
                try {
                    CN.dart.call(CN.page.config.slideshowDartConfig.name,CN.page.config.slideshowDartConfig);
                    CN.stats.omniture.setPaginationValue('slideshow_ad');
                    CN.stats.omniture.trackAjaxPage();
                } catch(e) {
                    CN.debug.log('Tried to perform dart request but failed. Perhaps no interstitial exists');
                }
            }
            CN.dart.refresh();

        });

                // Adds the Consumer Marketing and interstitial ad slides
        slideshow.onSlideshowReady.subscribe(function() {
            var adshtml=(CN.dart.get ? '<div id="' + CN.page.config.slideshowDartConfig.name+CN.page.config.slideshowDartConfig.sz+CN.dart.get('container') + '"></div>' : '');
            CN.slideshow.api.addSlide('slideshow-cm-container', { slideType: 'DomSlide' } );
            CN.slideshow.api.addInterstitial(adshtml, { slideType: 'DartInterstitial' } );

            if (slideshow.navigationItems.navigationViewAll) {
                slideshow.navigationItems.navigationViewAll.onShow.subscribe(function() {
                    CN.stats.omniture.setPaginationValue('slideshow_viewthumb').trackAjaxPage();
                });
            }

                    // if we have JSP slide, we need to fire this for tracking
            if (jQuery('html').hasClass('slideshow-showinitial-true')) {
                CN.stats.omniture.setPaginationValue('slide' + (slideshow.currentSlideIndex + 1)).trackAjaxPage();
            }

        });

        toggleItemCommentBox = function() {
                    // Handles the animation of the comments box for slide-level r/c
            if (slideshow.slide.hasComments && slideshow.slide.hasComments() === true) {
                if (jQuery('.cr-item .comments-toggle').length < 1) {
                    jQuery('.cr-item .comments').hide();
                    jQuery('<div class="comments-toggle">Comments</div>').appendTo('.cr-item .rating').click(function() {
                        jQuery(this).toggleClass('active');
                        jQuery('.cr-item .comments').slideToggle(500);
                    });
                }
            } else {
                jQuery('.cr-item .comments-toggle').remove();
            }
        }

        if (CN.slideshow.plugin.PluckHelper) {
                    // Pluck updates when slide changes
            slideshow.onSlideChangeComplete.subscribe(function() {
                pluckHelper.initNewSlide();
                toggleItemCommentBox();
            });

            slideshow.onSlideshowReady.subscribe(function() {
                pluckHelper.initNewSlide(); // technically a duplicate on the first slide // TODO: smelly // also causes pluck to have to check for slide, because on ready the additional slides aren't in yet
                if (!CN.page.config.isJumpOnLoad) {
                    toggleItemCommentBox();
                }
            });
        }

        jQuery('#slideshow-cm-subsoffer a').click(function() {
            window.open(this.href);
            return false;
        });
    });
}

/***********************
 SCHEMA PARSER TEMPLATE
***********************/

/**
 * Overall HTML layouts, override if you need something else by overwriting the property before parsing the dct.
 * @property templates
 * @static
 */
CN.schemaParser = CN.schemaParser || {};
CN.schemaParser.templates = {

    baseItem : function(item, imageType) {
                // Don't like this much, but works for now
        try {
            item.photo[imageType]();
        } catch(e) {
            imageType = 'main';
        }

        // would this work too?
        // imageType = item.photo[imageType]() || 'main';

        var html = '';
        html += '<div class="item">';

            if (item.photo) {
                html += '<div class="captioned-photo"><div class="w">';
                if (item.photo.url()) { // check method return value, false if empty string
                    html += '<a href="' + item.photo.url() + '">';
                }
                html += '<img src="' + item.photo[imageType]() + '" alt="' + (item.photo.alt() || '') + '" />';
                if (item.photo.url()) {
                    html += '</a>';
                }
                html += '</div>';

                if (item.photo.caption()) {
                    html += '<p class="caption">' + item.photo.caption() + '</p>';
                }

                if (item.photo[imageType].annotations) {
                    html += item.photo[imageType].annotations();
                }

                html += '</div>';
            }

            html += '<div class="item-inner">';
                if (item.rubric || item.header || item.subHeaders) {
                    html += '<div class="headers-container">';
                        html += '<div class="headers">';
                            html += item.rubric ? '<h5 class="rubric">' + item.rubric() + '</h5>' : '';
                            html += item.header ? '<h3 class="content-headline">' + item.header() + '</h3>' : '';
                            if(item.subHeaders) {
                                jQuery.each(item.subHeaders(), function (index, thisItem) {
                                    html += '<h2 class="sub-header">' + thisItem + '</h2>';
                                });
                            }
                        html += '</div>';
                    html += '</div>';
                }
                html += '<div class="item-text">';
                    html += item.body && item.body().length > 0 ? '<div class="body">' + item.body() + '</div>' : '';
                    html += item.embeddedList ? item.embeddedList() : '';
                    html += item.contributors ? '<div class="byline">' + item.contributors() + '</div>' : '';
                    html += item.photoCredits ? '<cite class="photo-credits">' + item.photoCredits() + '</cite>' : '';
                    html += item.footerText || item.footerLegalCopy ? '<div class="footer">' : '';
                        html += item.footerText ? '<div class="text">' + item.footerText() + '</div>' : '';
                        html += item.footerLegalCopy ? '<div class="legal">' + item.footerLegalCopy() + '</div>' : '';
                    html += item.footerText || item.footerLegalCopy ? '</div>' : '';
                    html += item.displayDate ? '<div class="display-date">' + item.displayDate() + '</div>' : '';
                html += '</div>';
                html += item.filePath ? item.filePath() : '';
            html += '</div>';
        html += '</div>';
        return html;
    },

    item : function(item) {
        var html = this.baseItem(item, 'main');
        return html;
    },

    enlargedItem : function(item) {
        var html = this.baseItem(item, 'enlargedImage');
        return html;
    },

            // Override default schema parser template for contributor,
            // because we need <br /> tags instead of paragraphs for W Magazine
    contributors : function(dct) {
        var i,
            il,
            html = '',
            getContributorUrl;

                // Gets the URL for this contributor i
        getContributorUrl = function(dct) {
            var contributorUrl = false;
            if (dct.URL && dct.URL !== '[nolink]') {
                contributorUrl = dct.URL;
            } else if (CN.page.config.contributorUrl) {
                contributorUrl = CN.page.config.contributorUrl + dct.name;
            }
            return contributorUrl;
        }

        html += '<div class="contributors">';

        if (Object.prototype.toString.call(dct) === '[object Array]') {
            for (i = 0, il = dct.length; i < il; i++) {
                (function() { // scope for i
                    var contributor = dct[i];
                    html += '<span class="contributor">';
                        html += contributor.label ? '<span class="label">' + contributor.label + '</span> ' : '';
                        html += getContributorUrl(contributor) ? '<a href="' + getContributorUrl(contributor) + '">' : '';
                            html += contributor.name ? '<span class="name">' + contributor.name + '</span>' : '';
                        html += getContributorUrl(contributor) ? '</a>' : '';
                    html += '</span>';
                    if (i < il - 1) {
                        html += '<br />';
                    }
                })();
            }
        } else {
            html += '<span class="contributor">';
                html += dct.label ? '<span class="label">' + dct.label + '</span> ' : '';
                html += getContributorUrl(dct) ? '<a href="' + getContributorUrl(dct) + '">' : '';
                    html += dct.name ? '<span class="name">' + dct.name + '</span>' : '';
                html += getContributorUrl(dct) ? '</a>' : '';
            html += '</span>';
        }

        html += '</div>';

        return html;
    }
};

/* SET UP ANNOTATIONS */

CN.page.buildAnnotations = function(el, viewport) {

    jQuery(el).find('.annotations').annotation({
        position : 'top right',
        opacity  : 1,
        relative : true,
        effect   : 'slide',
        offset   : [12, -1], // vertical, horizontal
        dynamic  : {
            viewport : viewport || null,
            bottom   : {
                offset    : 10, // vertical offset only
                direction : 'down'
            },
            left     : {
                offset    : 1 // horizontal offset only
            }
        }
    });

    // Freaking refactor this
    setTimeout(function() {
        jQuery(el).find('.annotation-trigger').fadeTo('slow', .5, function() {
            jQuery(this).fadeTo('slow', 1, function() {
                jQuery(this).fadeTo('slow', .5, function() {
                    jQuery(this).fadeTo('slow', 1);
                });
            });
        });
    }, 1000);
}

CN.page.buildAnnotations('.captioned-photo', '.captioned-photo .w');

jQuery(function() {
   if (location.protocol !== 'https:') {
       CN.socialmedia.getTweet().getFacebookLike();
    }
});

