/**
 * @description Site behaviors for gourmet.com
 * @file        gourmet.js
 * @date        September 2010
*/

/**
 * CN page config object
*/

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"><div id="rating_' + CN.site.name + '_0000" class="rate"><h4>Rate it:</h4><div id="ratingGroup_' + CN.site.name + '_0000"><a href="#" id="ratingAnchor_' + CN.site.name + '_0000_1">1 Star</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_2">2 Stars</a><a href="#" id="ratingAnchor_' + CN.site.name + '_0000_3">3 Stars</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_4">4 Stars</a> <a href="#" id="ratingAnchor_' + CN.site.name + '_0000_5">5 Stars</a> </div><span class="ratingtxt" id="ratingAverageTxt_' + CN.site.name + '_0000"></span><span id="ratingAverage_' + CN.site.name + '_0000"></span></div></div>';
CN.page.config.pluckCommentMarkup = '<div class="comments"><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="/images/elements/user/registration/submit.gif"/></form></div><h3>Comments</h3><h5 class="totalComments" id="totalComments_' + CN.site.name + '_0000"></h5><div class="commentAnchor" id="commentAnchor_' + CN.site.name + '_0000"></div></div>';

/**
 * @section Slideshow dart config.
 */

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

/**
 * @section Callbacks for slideshow and most popular
 */

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

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

CN.page.config.slideshowViewLargerCallback = function(larger, commands) {
    var 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());
                }
            });
        }

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

    larger.onInterstitialShow.subscribe(function() {
        var dartConfig;
        if (larger.slide.getLabel() === 'dartinterstitial') {
            dartConfig=CN.config.get('slideshowDartConfig');
            try {
                CN.dart.call(dartConfig.name,dartConfig);
                CN.stats.omniture.setPaginationValue('slideshow_ad').trackAjaxPage();
            } catch(e) {
                CN.debug.warn('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)).trackAjaxPage();
        } else if (larger.slide.getLabel() === 'domslide') {
            CN.stats.omniture.setPaginationValue('slideshow_offer').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')
        .bind('click', function() {
            commands.jumpToSlideCommand.execute(1);
            return false;
    });
};

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


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

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

    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;

        // 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: 'crossfade' };
                    jQuery('#items-container .viewlarger a').bind('click', function() {
                        CN.stats.omniture.setPaginationValue('slideshow_enlarge').trackAjaxPage();
                    });
                }

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

                if (CN.page.config.imagelist === true) {
                    initParams.listNavigation = { 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 assigns 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() {
                    CN.stats.omniture.setPaginationValue('slideshow_play').trackAjaxPage();
                });

                jQuery('#items-container .stop a').bind('click', function() {
                    CN.stats.omniture.setPaginationValue('slideshow_pause').trackAjaxPage();
                });
            },
            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());
                    }
                });
                        // Tracking for actual DCT slides
                CN.stats.omniture.setPaginationValue('slide' + (slideshow.currentSlideIndex + 1));
                CN.stats.omniture.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');
                CN.stats.omniture.trackAjaxPage();
            }
        };

        slideshow.onForwardComplete.subscribe(function() {
            slideChangeFns();
        });

        slideshow.onBackwardComplete.subscribe(function() {
            slideChangeFns();
        });

        slideshow.onJumpToSlideComplete.subscribe(function() {
            slideChangeFns();
        });

        slideshow.onSlideChangeComplete.subscribe(function() {
            CN.dart.refresh();
        });

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

        // Adds the Consumer Marketing and interstitial ad slides
        slideshow.onSlideshowReady.subscribe(function() {
            var dartConfig=CN.config.get('slideshowDartConfig'),
            html=(CN.dart.get ? '<div id="' + dartConfig.name+dartConfig.sz+CN.dart.get('container') + '" class="displayAd"></div>' : '');

            CN.slideshow.api.addSlide('slideshow-cm-container', { slideType: 'DomSlide', slideshow: slideshow });
            CN.slideshow.api.addInterstitial(html, { slideType: 'DartInterstitial', slideshow: slideshow });

            if (slideshow.navigationItems.navigationViewAll) {
                slideshow.navigationItems.navigationViewAll.onShow.subscribe(function() {
                    CN.stats.omniture.setPaginationValue('slideshow_viewthumb').trackAjaxPage();
                });
            }
                    // Testing - if we have JSP slide, we need to fire this for tracking
            if (jQuery('html').hasClass('slideshow-showinitial-true')) {
                slideChangeFns();
            }
        });

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

            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
            });
        }

        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';
        }

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

            if (item.photo) {
                html += '<div class="captioned-photo"><div class="img-shadow">';
                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>';
                }

                html += '</div>';
            }

            html += '<div class="item-inner">';
                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>' : '';
                        html += item.subHeaders ? '<h4 class="sub-header">' + item.subHeaders() + '</h4>' : '';
                    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 += '</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;
    }
};

