//test2
var executeImmediately = (function($) {
    $(document).ready(function() {
        var cmData = BN.Page.CoremetricsData;
        // Coremetrics
        if (typeof cmCreatePageviewTag !== "undefined") {
            try {
                cmCreatePageviewTag(cmData.pageId, cmData.productMetrics.uber.category);

                $('#printBuyForm .btn-add-to-cart').click(function() {
                    var printBuyMetrics = cmData.productMetrics.PrintBuy;
                    cmCreateProductviewTag(printBuyMetrics.ean, cmData.title, printBuyMetrics.category);
                    cmCreatePageElementTag('TEXTBOOK ADD TO CART', 'TEXTBOOK PRODUCT PAGE', 'SHOP_ACTION-_-TEXTBOOK_ADD_TO_CART');
                });

                $('#printRentalForm .btn-add-to-cart').click(function() {
                    var printRentMetrics = cmData.productMetrics.PrintRent;
                    cmCreateProductviewTag(printRentMetrics.ean, cmData.title, printRentMetrics.category);
                    cmCreatePageElementTag('TEXTBOOK ADD TO CART', 'TEXTBOOK PRODUCT PAGE', 'SHOP_ACTION-_-TEXTBOOK_ADD_TO_CART');
                });

                $('#btn-buy-now-DigitalBuy').click(function() {
                    var digitalBuyMetrics = cmData.productMetrics.DigitalBuy;
                    cmCreateProductviewTag(digitalBuyMetrics.ean, cmData.title, digitalBuyMetrics.category);
                    cmCreatePageElementTag('TEXTBOOK BUY NOW', 'TEXTBOOK PRODUCT PAGE', 'SHOP_ACTION-_-TEXTBOOK_BUY_NOW');
                });

                $('#btn-buy-now-DigitalRent').click(function() {
                    var digitalRentMetrics = cmData.productMetrics.DigitalRent;
                    cmCreateProductviewTag(digitalRentMetrics.ean, cmData.title, digitalRentMetrics.category);
                    cmCreatePageElementTag('TEXTBOOK RENT NOW', 'TEXTBOOK PRODUCT PAGE', 'SHOP_ACTION-_-TEXTBOOK_RENT_NOW');
                });
            }
            catch (e) { }
        }


        var drmOverlay = new jQuery.Overlay({
            useHeading: 1,
            heading: 'Digital Rights',
            block: 1
        });
        drmOverlay['set'].content($('#drm_overlay_content').html());
        drmOverlay['set'].id('drm_overlay');
        drmOverlay['set'].width(400);

        $('.drmOverlayFunc').click(function() {
            drmOverlay.open();
            $('#drm_overlay .overlayClose').click(function(e) { e.preventDefault(e); drmOverlay.close(); });
        });

        /* eTextbook Rentals is no longer an overlay...gonna be a popup */
        /*
        var eTextbookRentalsOverlay = new $.Overlay({
        useHeading: 1,
        heading: 'How eTextbook Rentals Work',
        block: 1
        });
        eTextbookRentalsOverlay['set'].content($('#eTextbooks_overlay_content').html());
        eTextbookRentalsOverlay['set'].id('eTextbookRentalsOverlay');
        $('.how-etextbook-rentals-work').click(function() {
        eTextbookRentalsOverlay.open();
        $('#eTextbookRentalsOverlay .overlayClose').click(function(e) { e.preventDefault(e); eTextbookRentalsOverlay.close(); });
        });
        */

        $('#print-rental-term-select').change(function() {
            var selectedRentalTermObj, selectedRentalTermDays = $(this).val(), rentalTerms = BN.Page.TextbookRentals.printRentalTerms;
            $('#rentalTermFormInput').val(selectedRentalTermDays);
            for (var i = 0; i < rentalTerms.length; i++) {
                if (rentalTerms[i].rentalTerm == selectedRentalTermDays) {
                    selectedRentalTermObj = rentalTerms[i];
                    break;
                }
            }
            var printRentalRow = $('#printRentalRow');
            $('.price', printRentalRow).text(selectedRentalTermObj.priceDisplay);
            if (selectedRentalTermObj.youSave > 0) {
                $('.you-save', printRentalRow).text('(You Save ' + selectedRentalTermObj.youSaveDisplay + ')');
            }
        });

        // Wire up the used inlay
        var $marketplaceRow = $('#marketplace-row');
        var $marketplaceRowInlayWidget = $marketplaceRow.find('.wgt-marketplace-inlay');
        var $marketplaceTabInlayWidget = $('#tab-marketplace').find('.wgt-marketplace-inlay');
        $marketplaceRow.find('.marketplace-link-container.used-container .marketplace-link').click(function(e) {
            e.preventDefault();
            BN.Page.TextbooksProductPage.getMarketplaceInlay(null, '6', $marketplaceRowInlayWidget);
        });
        $marketplaceRow.find('.marketplace-link-container.new-container .marketplace-link').click(function(e) {
            e.preventDefault();
            BN.Page.TextbooksProductPage.getMarketplaceInlay(null, '5', $marketplaceRowInlayWidget);
        });
        $marketplaceRow.find('.see-all-prices-button').click(function(e) {
            e.preventDefault();
            BN.Page.TextbooksProductPage.getMarketplaceInlay(null, '7', $marketplaceRowInlayWidget);
        });

        $('a[name=marketplaceTab]').click(function() {
            BN.Page.TextbooksProductPage.getMarketplaceInlay(null, '7', $marketplaceTabInlayWidget);
        });
        $('.marketplace-inlay-container').delegate(
            '.condition-tabs-container a, .sort-row a, .pagination-container a',
            'click',
            function(e) {
                var $this = $(this), // 'this' is the clicked element that matches a selector.  not '#marketplace-inlay-container', and not necessarily the event target
                    $marketplaceRowInlayWidget = $this.closest('.wgt-marketplace-inlay');
                if (!$this.hasClass('close-link')) {
                    e.preventDefault();
                    BN.Page.TextbooksProductPage.getMarketplaceInlay(this.href, null, $marketplaceRowInlayWidget);
                }
            }
        );

        $('.marketplace-inlay-container').delegate(
            '.close-link',
            'click',
            function(e) {
                var $this = $(this), // 'this' is the clicked element that matches a selector.  not '#marketplace-inlay-container', and not necessarily the event target
                    $marketplaceRowInlayWidget = $this.closest('.wgt-marketplace-inlay'),
                    $inlayContainer = $marketplaceRowInlayWidget.find('.marketplace-inlay-container');

                e.preventDefault();
                $inlayContainer.find('.fade-container').animate({ opacity: 0 }, { duration: 300, queue: false });
                $inlayContainer.animate(
                    { height: '0px' },
                    {
                        duration: 300,
                        queue: 'false',
                        complete: function() { $inlayContainer.empty().hide(); }
                    }
                );
            }
        );
    });
})(jQuery142);




BN('Page.TextbooksProductPage', function() {
    return {
        'showAjaxError': function($marketplaceInlayLoadingContainer) {
            $marketplaceInlayLoadingContainer.find('.fade-container').animate(
                { opacity: 0 },
                'fast',
                null,
                function() {
                    $marketplaceInlayLoadingContainer.find('.loading-spinner').hide();
                    $marketplaceInlayLoadingContainer.find('.error-message').show()
                    $(this).animate(
                        { opacity: 1 },
                        'fast'
                    );
                }
            );
        },
        'getMarketplaceInlay': function(pUrl, condition, $marketplaceInlayWidget) {
            var usedPrintData, pEan, onlinePrice, $marketplaceInlayContainer, $marketplaceInlayLoading, url, cond, params;
            usedPrintData = $('#usedPrintData');
            pEan = $('#ean', usedPrintData).text();
            onlinePrice = $('#listPrice', usedPrintData).text();
            $marketplaceInlayContainer = $marketplaceInlayWidget.find('.marketplace-inlay-container');
            $marketplaceInlayLoading = $marketplaceInlayWidget.find('.marketplace-inlay-loading-container').contents().clone();

            onlinePrice = onlinePrice || 1; // hack in the case that there is no online price on the page.  provide 1, and the service call will succeed, 
            if (onlinePrice && pEan) { // if online price(oprc) and ean is available, make service call.
                url = pUrl || 'http://' + BN.Environment.Host.getMappedDomain("SEARCH") + '/used/results.aspx'
                cond = condition || '7'; // 7 for All
                // temporary until Julia fixes : don't include oprc if you want a full listing of results
                // pass the template, uiaction, and view params, in order to ajaxify the default paging/sorting/etc links in the inlay
                // have to use uppercase param names for certain params, because that's how the XML provides the URL we're modifying here.
                // If lowercase, it would create a duplicate param & blow up the service call
                params = {
                    'pean': pEan,
                    'sze': 10,
                    'cnd': cond,
                    'view': 'isbnservice',
                    'template': 'textbooksinlay',
                    'bnOutput': '1',
                    'usedpagetype': 'usedisbn',
                    'uiAction': 'isbnservice'//,
                    //'oprc': onlinePrice
                };

                if (url.indexOf('PEAN') > -1) { delete params.pean; }
                if (url.indexOf('VIEW') > -1) { delete params.view; }
                if (url.indexOf('USEDPAGETYPE') > -1) { delete params.usedpagetype; }
                if (url.indexOf('SZE') > -1) { delete params.sze; }
                if (url.indexOf('CND') > -1) { delete params.cnd; }


                $marketplaceInlayLoading.find('.fade-container').css('opacity', 0);
                // height of container with loading block is 168px
                $marketplaceInlayContainer
                    .empty()
                    .append($marketplaceInlayLoading)
                    .show();
                $marketplaceInlayLoading.find('.fade-container').animate({ opacity: 1 }, { duration: 'fast', queue: false });
                $marketplaceInlayContainer
                    .animate(
                        { height: '168px' },
                        {
                            duration: 'fast',
                            queue: false,
                            complete: function() {
                                $.ajax({
                                    url: url,
                                    data: params,
                                    dataType: 'jsonp',
                                    success: function(response) {
                                        if (response.output !== '' && response.output.indexOf('condition-tabs-container') > -1) {
                                            $marketplaceInlayContainer
                                            .html(response.output);
                                            var targetHeight = $marketplaceInlayContainer[0].scrollHeight;
                                            //var targetHeight = $marketplaceInlayContainer.find('.condition-tabs-container')[0].scrollHeight + $marketplaceInlayContainer.find('.fade-container')[0].scrollHeight;
                                            //console.log("$marketplaceInlayContainer.find('.condition-tabs-container')[0].scrollHeight " + $marketplaceInlayContainer.find('.condition-tabs-container')[0].scrollHeight); 
                                            //console.log("$marketplaceInlayContainer.find('.fade-container')[0].scrollHeight " + $marketplaceInlayContainer.find('.fade-container')[0].scrollHeight);
                                            //console.log('targetHeight ' + targetHeight);
                                            $marketplaceInlayContainer.animate({ 'height': targetHeight + 'px' }, { duration: 'slow', queue: false });
                                            $marketplaceInlayContainer.find('.fade-container').animate({ opacity: 1 }, { duration: 500, queue: false });
                                        }
                                        else {
                                            BN.Page.TextbooksProductPage.showAjaxError($marketplaceInlayLoading);
                                        }
                                    },
                                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                                        BN.Page.TextbooksProductPage.showAjaxError($marketplaceInlayLoading);
                                    },
                                    complete: function(XMLHttpRequest, textStatus) {
                                        if (XMLHttpRequest.responseText == '' || XMLHttpRequest.responseText.indexOf('condition-tabs-container') < 0) {
                                            BN.Page.TextbooksProductPage.showAjaxError($marketplaceInlayLoading);
                                        }
                                    },
                                    timeout: 5000
                                });
                            }

                        }
                    );

            }

        }
    };
});


// TODO : Move this into a global Torque file at some point
BN('Util.Widget', function() {
    return {
        'applyTheme': function(selector, themeName) {
            // selector must be the at the top-level node of the widget; ex '.wgt-product-listing-textbooks'
            var currentThemeName, $wgt = $(selector), classNames = $wgt[0].className.split(' ');

            for (var i = 0; i < classNames.length; i++) {
                if (classNames[i].substr(0, 3) === 'th-') { currentThemeName = classNames[i].substr(3); }
            }

            $wgt.each(function() {
                $this = $(this);
                if (currentThemeName) {
                    $this.removeClass('th-' + currentThemeName);
                    $this.find('.w-head').removeClass('w-head-' + currentThemeName);
                    $this.find('.w-head-c').removeClass('w-head-' + currentThemeName + '-c');
                    $this.find('.w-body').removeClass('w-body-' + currentThemeName);
                    $this.find('.w-body-c').removeClass('w-body-' + currentThemeName + '-c');
                    $this.find('.w-foot').removeClass('w-foot-' + currentThemeName);
                    $this.find('.w-foot-c').removeClass('w-foot-' + currentThemeName + '-c');
                }

                $this.addClass('th-' + themeName);
                $this.find('.w-head').addClass('w-head-' + themeName);
                $this.find('.w-head-c').addClass('w-head-' + themeName + '-c');
                $this.find('.w-body').addClass('w-body-' + themeName);
                $this.find('.w-body-c').addClass('w-body-' + themeName + '-c');
                $this.find('.w-foot').addClass('w-foot-' + themeName);
                $this.find('.w-foot-c').addClass('w-foot-' + themeName + '-c');
            });
        }
    }
});

