/** Snaps Unified JS v1 **/

/** Commented out variables are for reference purposes **/

/**
var defSearchMsg = "<xsl:value-of select="$txt_searchDefText" />";
var txt_grid = "<xsl:value-of select="txt_grid"/>";
var txt_list = "<xsl:value-of select="txt_list"/>";
var snap_ImagePath = '<xsl:value-of select="$txt_image_path" />';
var snap_PlaceId = "<xsl:value-of select="/contents/placeId"/>";
//Typeahead variables
var snap_locale = "<xsl:value-of select="/contents/contentLangauge"/>";
var snap_placementLabelSetId = "<xsl:value-of select="/contents/placementLabelSetId"/>";
var snap_placementId = "<xsl:value-of select="/contents/placementId"/>";
var snap_globalLabelSetId = "<xsl:value-of select="/contents/globalLabelSetId"/>";
// If there is no placement labelset then it should use the global labelset ID
if(snap_placementLabelSetId == "") snap_placementLabelSetId = snap_globalLabelSetId;
var baseSearchUrl = "?rt=<xsl:value-of select="$txt_typeAheadUrl"/>";
var fSearch = "<xsl:value-of select="//allProductsShown"/>";
var burl = "<xsl:value-of select="$baseurl"/>";
var taCategory = "<xsl:value-of select="$txt_category"/>";
var compRemove = "<xsl:value-of select="$txt_remove"/>";
var compMaxMsg = "<xsl:value-of select="$txt_compmaxmsg"/>";
var compMinMsg = "<xsl:value-of select="$txt_compminmsg"/>";
var txt_quickView = "<xsl:value-of select="$txt_quickView" />";
var txt_loading = "<xsl:value-of select="$txt_loading" />";
var typeAheadRestrictId = "<xsl:value-of select="$txt_restrictTypeAheadDimId" />";
var bvRatingsProdIdJsonObject = {};
var campaignID = "<xsl:value-of select="$campaignID"/>";            
var rurl = "<xsl:value-of select="$ratingsURL"/>";
var rxsl = "<xsl:value-of select="$cs_reviewsXSLT"/>";
var bcExp = null;
var modVP, modExp, modCon;
var bcVids = new Array();
var bcVidId = "";
var playSmallImg = "<xsl:value-of select="$cs_playSmallImg"/>";
var playImg = "<xsl:value-of select="$cs_playImg"/>";
var modelsTxt = "<xsl:value-of select='$txt_tabname_ProductResults' />";
var loadingImg = "<xsl:value-of select='$cs_loadingImg' />";
var snap_PlaceId = "<xsl:value-of select='/contents/placeId' />";
var snap_placementLabelSetId = "<xsl:value-of select='/contents/placementLabelSetId' />";
var snap_placementId = "<xsl:value-of select='/contents/placementId' />";
var snap_globalLabelSetId = "<xsl:value-of select='/contents/globalLabelSetId' />";
var snap_locale = "<xsl:value-of select='/contents/contentLangauge'/>";
var snap_ImagePath = "<xsl:value-of select='$txt_image_path' />";
var burl = "<xsl:value-of select='$baseurl' />";
var carouselClicked = false;       
var relProdNext = "<xsl:value-of select='$txt_next' />";  
var relProdPrev = "<xsl:value-of select='$txt_prev' />";  
var relProdProducts = "<xsl:value-of select='$txt_products' />";
var originalNavHTML, maxImgHeight;
var bvClientName = "<xsl:value-of select='$corpBV_clientName' />";
var bvDisplayZone = "<xsl:value-of select='$corpBV_displayZone' />",
var brightcoveMarkup = "";
var xslVars = new Array();
xslVars[0] = {name: "txt_displaying", value: "<xsl:value-of select="$txt_displaying"/>"};
xslVars[1] = {name: "txt_of", value: "<xsl:value-of select="$txt_of"/>"};
xslVars[2] = {name: "txt_reviews", value: "<xsl:value-of select="$txt_reviews"/>"};
xslVars[3] = {name: "txt_viewAllReviews", value: "<xsl:value-of select="$txt_viewAllReviews"/>"};
xslVars[4] = {name: "txt_outOf", value: "<xsl:value-of select="$txt_outOf"/>"};
xslVars[5] = {name: "txt_by", value: "<xsl:value-of select="$txt_by"/>"};
xslVars[6] = {name: "txt_stars", value: "<xsl:value-of select="$txt_stars"/>"};
xslVars[7] = {name: "txt_featuredReview", value: "<xsl:value-of select="$txt_featuredReview"/>"};
xslVars[8] = {name: "txt_basedOn", value: "<xsl:value-of select="$txt_basedOn"/>"};
xslVars[9] = {name: "txt_customerReviews", value: "<xsl:value-of select="$txt_customerReviews"/>"};
xslVars[10] = {name: "txt_topRatedReview", value: "<xsl:value-of select="$txt_topRatedReview"/>"};
xslVars[11] = {name: "txt_avgRating", value: "<xsl:value-of select="$txt_avgRating"/>"};
xslVars[12] = {name: "txt_rating", value: "<xsl:value-of select="$txt_rating"/>"};
xslVars[13] = {name: "txt_jan", value: "<xsl:value-of select="$txt_jan"/>"};
xslVars[14] = {name: "txt_feb", value: "<xsl:value-of select="$txt_feb"/>"};
xslVars[15] = {name: "txt_mar", value: "<xsl:value-of select="$txt_mar"/>"};
xslVars[16] = {name: "txt_apr", value: "<xsl:value-of select="$txt_apr"/>"};
xslVars[17] = {name: "txt_may", value: "<xsl:value-of select="$txt_may"/>"};
xslVars[18] = {name: "txt_jun", value: "<xsl:value-of select="$txt_jun"/>"};
xslVars[19] = {name: "txt_jul", value: "<xsl:value-of select="$txt_jul"/>"};
xslVars[20] = {name: "txt_aug", value: "<xsl:value-of select="$txt_aug"/>"};
xslVars[21] = {name: "txt_sep", value: "<xsl:value-of select="$txt_sep"/>"};
xslVars[22] = {name: "txt_oct", value: "<xsl:value-of select="$txt_oct"/>"};
xslVars[23] = {name: "txt_nov", value: "<xsl:value-of select="$txt_nov"/>"};
xslVars[24] = {name: "txt_dec", value: "<xsl:value-of select="$txt_dec"/>"};
WT.pn_sku="<xsl:value-of select="$productID"/>";
WT.tx_e="v"; 

**/

var defSearchMsg,
txt_grid,
txt_list,
snap_ImagePath,
snap_PlaceId,
snap_locale,
snap_placementLabelSetId,
snap_placementId,
snap_globalLabelSetId,
baseSearchUrl,
fSearch,
burl,
taCategory,
compRemove,
compMaxMsg,
compMinMsg,
txt_quickView,
txt_loading,
typeAheadRestrictId,
bvRatingsProdIdJsonObject,
campaignID,
rurl,
rxsl,
bcExp,
modVP,
modExp,
modCon,
bcVids,
bcVidId,
playSmallImg,
playImg,
modelsTxt,
loadingImg,
snap_PlaceId,
snap_placementLabelSetId,
snap_placementId,
snap_globalLabelSetId,
snap_locale,
snap_ImagePath,
burl,
carouselClicked,
relProdNext,
relProdPrev,
relProdProducts,
originalNavHTML,
maxImgHeight,
bvClientName,
bvDisplayZone,
brightcoveMarkup,
xslVars,
img360Count = 0;

if(snap_placementLabelSetId == ""){snap_placementLabelSetId;}




function hideColorSwatchHeaders() {
    var $colorSwatchHeaders = $('.js-colorSwatchBreadboxHeader','.breadbox');
    var colorSwatchHeadersLength = $colorSwatchHeaders.length;
    for(var h=0; h < colorSwatchHeadersLength; h++){
        var headerSelect = $('.js-colorSwatchBreadboxHeader')[h];
        if (h !== 0){
            headerSelect.style.display = 'none';
        }
    }
}

function calcMainImageHeight() {
    // Takes a look at all the images in the mainImageBlock and takes the tallest height and then sizes #mainImageBlock to that height
    var imgHeightArray = [];

	// Runs when the page is fully loaded including graphics
	$(window).load(function(){
		
		$('.mainImageBlockImg').each(function(){
            imgHeightArray.push(this.height);
        });
		
		imgHeightArray.sort(function (a, b) {
			return a > b ? 1 : a < b ? -1 : 0;
		});

		$('#mainImageBlock').height(imgHeightArray.pop());
		
    });
   
}

function calcVariantNavWidth() {

    // loops through the largest width item of each <a> in each .dimesion and then sizes .dimension to the width of the widest <a>(within the <li>) and also checks against the <h5> header incase that one is wider than any of tha <a>'s    $('.dimension').each(function(){
    $('.dimension').each(function(){
        var _lastWidth = 0;
        $(this).find('a').each(function(){
             var _nextWidth = $(this).outerWidth(true),
             _headerWidth = $(this).closest('.dimension').find('.dimensionName').outerWidth(true);

             if(_nextWidth > _lastWidth){
                if (_headerWidth >_nextWidth){
                    var _width = _headerWidth;
                    $(this).closest('.dimension').width(_width);
                 }else{
                    var _width = _nextWidth;
                    $(this).closest('.dimension').width(_width);
                 }                
             }
        });
    });
};

function loadCookie() {
    var cVal, cName, i, cookieArr = document.cookie.split(";");
    var curDate = new Date();
    var hasSnaps = false;
    var tmpCookie = '';
    for (i = 0; i < cookieArr.length; i++) {
        cName = cookieArr[i].split('=')[0].replace(/^\s+|\s+$/g, "");
        if (cName == 'SNAPS') hasSnaps = true;
        if (cName == 'WT_FPC') tmpCookie = cookieArr[i].split('=')[2] + curDate.valueOf();
    }
    if (hasSnaps == false) document.cookie = 'SNAPS=' + tmpCookie;
}

function adjustProdCells() {
    //If 'list' remove the heights, if grid calculate the heights
    if ($('#productRecords').hasClass('grid')) {
        $('.prodRow').each(function () {
            var maxHeight = 0;
            var addlProdInfoHeight = 0;
            var shortDescriptionHeight = 0;
            $(this).find('.prodInfo H6').each(function () {
                if ($(this).height() > maxHeight) maxHeight = $(this).height();
            });
            $(this).find('.prodInfo p').each(function () {
                if ($(this).height() > shortDescriptionHeight) shortDescriptionHeight = $(this).height() + 20;
            });
            $(this).find('.prodInfo .addlProdInfo').each(function () {
                if ($(this).height() > addlProdInfoHeight) addlProdInfoHeight = $(this).height();
            });
            maxHeight += 20 + addlProdInfoHeight + shortDescriptionHeight;
            $(this).find('.prodInfo').css('height', maxHeight / 12 + 'em');
        })
    } else {
        $('.prodInfo').css('height', '');
    }
}


function openQuickView(href, button, html) {
    var $qvframe = $('#quickViewFrame');
    if ($qvframe.length === 0) {
        $qvframe = $('<div id="quickViewFrame" class="quickView"><div class="quickViewClose"></div><div class="loadingFrame"></div><div class="quickViewContent displayNone"></div></div>');
        $('#productRecords').append($qvframe);

    } else {
        $('.loadingFrame').show();
        $('.quickViewContent').hide();
        $qvframe.show();

    };

    $qvframe.show().find('.quickViewContent').load(href + ' .quickViewContainer', function () {
        assembleQV(html);
    });
    $qvframe.position({
        my: "center",
        at: "center",
        of: window
    });


    $('.quickViewClose').click(function () {
        closeQuickView();
    });

}

function assembleQV(html) {
    $('.quickViewContent').show();
    $('.loadingFrame').hide();
    resizeContent();
    styleWtbCIButton();
    enableMediaBlockThumbnailHover();
    enableWtbCIButtonColorbox();
    enableQVCorpBVStarRatings(html);
	$('.quickViewContent').find('.primarybutton').button();
    // $('.quickViewContent').show();
    // $('.loadingFrame').hide();
}

function enableQVCorpBVStarRatings(html) {
    $('.quickViewContent .pageTitle').after(html);
}

function enableMediaBlockThumbnailHover() {
    //If we have more than one thumbnail we need to initialize the mediaBlock
    if ($('#mediaBlock div').length > 0) {
        //Size the media block (it needs to retain maximum height if no js)
        $('#mediaBlock').height(50);
        //Highlight the first media block since it should be selected by default
        $('#mediaBlock div:eq(0)').addClass('HOVER');
        //Unhide the media block
        $('#mediaBlock').css('display', 'block');
        //Mouseover for image blocks under the main image
        $('#mediaBlock div').mouseover(function () {
            $('#mediaBlock div').removeClass('HOVER');
            $(this).addClass('HOVER');
            //Only hide the main image and display a new one if they hover over an image, not a video
            if ($(this).attr('type') == 'image') {
                var imagename = $(this).attr('parentImage');
                $('#mainImageBlock div').css('display', 'none');
                $('#' + imagename).css('display', 'block');
            }
        });
    }
}

function enableWtbCIButtonColorbox() {

    var $wtbCIButton = $('.wtbCIButton');

    $wtbCIButton.colorbox({
        iframe: true,
        scrolling: false,
        width: 600,
        height: 500
    });

}

function styleWtbCIButton() {
    var $wtbCIButton = $('.wtbCIButton'),
        $wtbCIButtonText = $('.wtbCIButton').text();

    $wtbCIButton.text('');
    $wtbCIButton.addClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only');
    $wtbCIButton.append('<span class="ui-button-text"></span>').find('.ui-button-text').text($wtbCIButtonText);
}

function resizeContent() {
    var $qvFrame = $('#quickViewFrame').contents();
    var $descCell = $qvFrame.find('.prodDescOuter');
    $descCell.outerHeight(245 - $qvFrame.find('.quickViewContainer H3.pageTitle').outerHeight(true) - $qvFrame.find('.quickViewContainer #summaryInlineRating').outerHeight(true));
}

function closeQuickView() {
    $('#quickViewFrame').hide();
}

function loadRatings() {
    if (campaignID != '' && rurl != '' && rxsl != '') {
        $('#ratingsReviewsContainer').ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
            $('#ratingsReviewsContainer').text('AJAX ERROR: ' + thrownError);
        });
        $.get(rurl, function (xmlData) {
            var xml = xmlData;
            $.get(rxsl, function (xsltData) {
                //Now loop through all of the variables in the stylesheet and replace their values 
                for (var x = 0; x < xslVars.length; x++) {
                    $(xsltData).find('*[name="' + xslVars[x].name + '"]').text(xslVars[x].value);
                }
                var xslt = xsltData;
                var transformed;
                if (!window['XSLTProcessor']) {
                    //IE
                    transformed = xml.transformNode(xslt);
                } else {
                    //Non-IE
                    var processor = new XSLTProcessor();
                    processor.importStylesheet(xslt);
                    var xmldom = processor.transformToDocument(xml);
                    var serializer = new XMLSerializer();
                    var transformed = serializer.serializeToString(xmldom.documentElement);
                };
                $('#ratingsReviewsContainer').html(transformed);
                $('#summaryInlineRating').html($('#hideInlineRating').html());
            }, 'xml');
        }, 'xml');
    }
}

function initCBPlayer(videoId) {
    //We have to initiate the creation of the BrightCove player AFTER the colorbox has been opened
    //due to an IE6 bug.  Once the player is built we don;t have to rebuild it.
    if (bcExp == null) {
        var player = brightcove.createElement("object");
        player.id = "colorboxBC";
        var parameter;
        for (var i in bcpParams) {
            parameter = brightcove.createElement("param");
            parameter.name = i;
            parameter.value = bcpParams[i];
            player.appendChild(parameter);
        }
        parameter = brightcove.createElement("param");
        parameter.name = "@videoPlayer";
        parameter.value = videoId;

        player.appendChild(parameter);
        $("#cbBCPlayer").html("");
        var playerContainer = document.getElementById("cbBCPlayer");
        brightcove.createExperience(player, playerContainer, true);
    }
}

function selectPlayer(obj) {
    if (obj.attr('type') == "video") {
        var filetype = obj.attr('filetype').toLowerCase();
        $('#cbImagePlayer').css('display', 'none');
        $('#cbBCPlayer').css('display', 'none');
        $('#cb360Player').css('display', 'none');
        if ($f("cbFPPlayer").isHidden()) $f("cbFPPlayer").show();
        $('#cbFPPlayer').css('display', 'block');
        $f("cbFPPlayer").play({
            title: obj.attr('title'),
            url: obj.attr('url')
        });
        if (modVP != null) {
            if (modVP.isPlaying()) modVP.pause();
        }
    } else if (obj.attr('type') == "image") {
        $('#cbBCPlayer').css('display', 'none');
        if ($f("cbFPPlayer").isHidden() == false) $f("cbFPPlayer").hide();
        if ($f("cbFPPlayer").isPlaying()) $f("cbFPPlayer").stop();
        if (modVP != null) {
            if (modVP.isPlaying()) modVP.pause();
        }
        $('#cbFPPlayer').css('display', 'none');
        $('#cb360Player').css('display', 'none');
        $('#cbImagePlayer').css('display', 'block');
        $('#cbImagePlayer').html('<img src="' + obj.attr('url') + '&boundedSize=400" />');
    } else if (obj.attr('type') == "brightcove") {
        if ($f("cbFPPlayer").isHidden() == false) $f("cbFPPlayer").hide();
        if ($f("cbFPPlayer").isPlaying()) $f("cbFPPlayer").stop();
        $('#cbFPPlayer').css('display', 'none');
        $('#cbImagePlayer').css('display', 'none');
        $('#cb360Player').css('display', 'none');
        bcVidId = obj.attr('url');
        if (modVP != null) {
            //Player has already been built, just load a new video
            //This is when the user has the colorbox open and is switching between videos
            modVP.loadVideo(bcVidId);
        } else {
            //No player yet (colorbox was just opened) so build it and set the video id parameter so it will start it
            initCBPlayer(bcVidId);
            //bcpParams.videoId = bcVidId;
        }
        $('#cbBCPlayer').css('display', 'block');
    } else if (obj.attr('type') == "img360") {
        $('#cbFPPlayer').css('display', 'none');
        $('#cbImagePlayer').css('display', 'none');
        $('#cb360Player').css('display', 'block');
		// multiple 360 image starts
		$("div[id^='m360']").each(function(){
			$(this).css('display', 'none');
		});
		var celumID = obj[0].getAttribute('data-celum');
		$("div[id^='m360'] > a[data-celum='"+celumID+"']").parent().css('display', 'block');
		// multiple 360 image ends
		if ($f("cbFPPlayer").isPlaying()) $f("cbFPPlayer").stop();
        if (modVP != null) {
            if (modVP.isPlaying()) modVP.pause();
        }
        $('#cb360Player img').attr("src", obj.find("img").attr("src"));
    }
    //Now write the title to the colorbox
    $('#cboxTitle').html(obj.attr('title'));
    $('.mediaListItem').removeClass('mliSelected');

	if (obj.attr('url')) {
		$('.mediaListItem[url="' + obj.attr('url') + '"]').addClass('mliSelected');
	} else {
		$('.mediaListItem[parentimage="' + obj.attr('parentimage') + '"]').addClass('mliSelected');
	}
}


function initFP() {
    $f("cbFPPlayer", {
        src: "/3MContentRetrievalAPI/BlobServlet?assetId=1258561261386&assetType=MMM_Image&blobAttribute=ImageFile",
        cachebusting: $.browser.msie
    }, {
        clip: {
            autoPlay: true,
            metaData: false,
            scaling: 'fit'
        },
        play: {
            label: "Play",
            replayLabel: "Click to play again"
        },
        key: MMMDefault.key,
        plugins: {
            controls: {
                url: controlBar,
                playlist: false,
                stop: true
            }
        },
        canvas: MMMDefault.canvas
    });
    $f("cbFPPlayer").hide();
}

function loadBCVideo() {
    bcExp = brightcove.getExperience('colorboxBC');
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
    if (bcVidId != '') {
        modVP.loadVideo(bcVidId);
    }
}

function onTemplateError(event) {
    $debug("type: " + event.type, "brightcove");
    $debug("errorType: " + event.errorType, "brightcove");
    $debug("code: " + event.code, "brightcove");
    $debug("info: " + event.info, "brightcove");
}

function initBCPlayerColorbox() {
    if (bcVids.length > 0) {
        for (var i = 0; i < bcVids.length; i++) {
            var vThumb = (bcVids[i].thumbnailURL == null) ? playSmallImg : bcVids[i].thumbnailURL;
            var vStillImg = (bcVids[i].videoStillURL == null) ? playImg : bcVids[i].videoStillURL;
            var vLongDesc = (bcVids[i].longDescription == null) ? "" : bcVids[i].longDescription;
            var vShortDesc = (bcVids[i].shortDescription == null) ? "" : bcVids[i].shortDescription;

            //Create the thumbnails under the main image
                var htmlstr = "<div class=\"cboxElement\" filetype=\"brightcove\" title=\"" + bcVids[i].name + "\"  type=\"brightcove\" url=\"" + bcVids[i].id + "\">";
            htmlstr += "<a><img class=\"smallVideoThumbnail\" src=\"" + vThumb + "\"><img class=\"smallVideoOverlay\" src=\"/3MContentRetrievalAPI/BlobServlet?assetId=1273681609448&amp;assetType=MMM_Image&amp;blobAttribute=ThumbnailImage\"></a></div>";

            
            if ($('#mediaBlock div').length > 4) {
                //If there are 5 or more images/videos already in the thumbnail list then we want to add the 
                //Brightcove thumbnails after the fourth one
                $('#mediaBlock div:eq(3)').after(htmlstr);
            } else {
                //Otherwise just append it to the mediablock div
                $('#mediaBlock').append(htmlstr);
            }
            //Add to the media item list in the lightbox
            htmlstr = "<a class=\"mediaListItem\" filetype=\"brightcove\" title=\"" + bcVids[i].name + "\" type=\"brightcove\" url=\"" + bcVids[i].id + "\">";
            htmlstr += "<div class=\"mlItemImage mlItemVideo\"><img src=\"" + vStillImg + "\"><img class=\"mlItemImageOverlay\" src=\"/3MContentRetrievalAPI/BlobServlet?assetId=1273681609448&assetType=MMM_Image&blobAttribute=ThumbnailImage\"></div><div class=\"mlItemDesc\">" + bcVids[i].name;
            htmlstr += "</div></a>";
            if ($('#mediaListContainer .mediaListItem').length > 4) {
                $('#mediaListContainer .mediaListItem:eq(3)').after(htmlstr);
            } else {
                $('#mediaListContainer').append(htmlstr);
            }
        }
    }
}


function carouselCallback(carousel) {
    // Function for updating the pagination
    $("#relatedProdCarouselContainer .ui-button").on("click", function () {
        // Ensure the carousel isn't in mid-animation
        if ($("#relatedProdCarouselContainer .relatedProdCarousel:animated").length < 1 || !carouselClicked) {
            // Previous button
            if ($(this).hasClass("carouselleftbutton")) {
                // If it's not at page 1 currently, reduce page number by 1
                if ($("#curPage").text() > 1) $("#curPage").text($("#curPage").text() - 1);
                // If it is at page 1, go to the last page
                else $("#curPage").text($("#totalPage").text());
            }
            // Next button
            else {
                // If it's not on the last page, increase page number by 1
                if ($("#curPage").text() * 1 < $("#totalPage").text()) $("#curPage").text($("#curPage").text() * 1 + 1);
                // If it is on the last page, go to page one
                else $("#curPage").text(1);
            }
            carouselClicked = true;
        }
    });

    // Function for the "start over" link
    $("#resetCarousel").on("click", function (e) {
        carousel.scroll(1);
        // Update page number
        $("#curPage").text("1");
        return false;
    });
}

// Initialization function for the variant SKU table
function variantSkuInit() {
    // Click function for breadbox links
    $("#variantBreadbox a").on("click", function (e) {
        e.preventDefault();
        loadVariantPage($(this));
    });

    // Initialize the navigation when the tab is clicked (initilization only works when the navigation is visible)
    $("#mainTabInterface .ui-tabs-nav a:contains(" + modelsTxt + ")").on("click", variantNavInit);

    // Table sort function
    /* Removed
                    $("#variantTable th").on("click", function(){
                        var rows = new Array();
                        var colIndex = $(this).index();
                        var parentTable = $(this).parents("#variantTable");
                        var temp = "";
                        var additionalRow;
                        var currentSort = $(this).attr("class");
                        
                        $("#variantTable th").removeClass("sortedAscend sortedDescend");
                        if(currentSort === "sortedAscend") $(this).addClass("sortedDescend");
                        else $(this).addClass("sortedAscend");
                        // Store every non-header row in an array and remove them from the DOM
                        parentTable.find("tr").each(function(){
                            if($(this).find("th").length < 1 && $(this).find("td").length > 1){
                                rows.push($(this).clone(true, true));
                                $(this).remove();
                            }
                        });
                        // Sort the rows based on the column that was clicked
                        if(currentSort === "sortedAscend"){
                            for(i=0;i<rows.length/2;i++){
                                temp = rows[i];
                                rows[i] = rows[rows.length-i-1];
                                rows[rows.length-i-1] = temp;
                            }
                        }
                        else{
                            for(i=0;i<rows.length;i++){
                                for(j=i+1;j<rows.length;j++){
                                    if(rows[j].find("td:eq(" + colIndex + ")").text() < rows[i].find("td:eq(" + colIndex + ")").text()){
                                        temp = rows[j];
                                        rows[j] = rows[i];
                                        rows[i] = temp;
                                    }
                                }
                            }
                        }
                        // Put the rows back in their new order
                        for(i=0;i<rows.length;i++){
                            // Get the row's additional info row
                            additionalRow = parentTable.find("#" + rows[i].find("a").attr("rel")).clone(true, true);
                            parentTable.find("#" + rows[i].find("a").attr("rel")).remove();
                            if(i % 2 === 0){
                                rows[i].addClass("oddRow");
                                additionalRow.addClass("oddRow");
                            }
                            else{
                                rows[i].removeClass("oddRow");
                                additionalRow.removeClass("oddRow");
                            }
                            parentTable.append(rows[i]);
                            parentTable.append(additionalRow);
                        }
                        //variantSkuInit();
                    });
            */

    // Initialize BV ROI if BV is enabled
    if ( !! bvClientName && !! bvDisplayZone) initializeBVROI();
}

// Initialization function for the variant SKU navigation
function variantNavInit() {
    // Reset the HTML in case it's already been formatted
    $("#variantDimensions").html(originalNavHTML);
    // Width of the container
    var navWidth = $("#variantDimensions").width();
    // Variable for storing the width of the current row
    var rowWidth = 0;
    // Keep track of the first row
    var firstRow = true;
    // Loop through the dimensions
    $("#variantDimensions .dimension").each(function (i) {
        // Add the dimension's total with to the row width
        rowWidth += $(this).outerWidth();
        // If the row is now wider than the container
        if (rowWidth > navWidth) {
            // Insert a clearing element
            $(this).before("<br style='clear:both;' />");
            // This is the start of a new row so reset the row width to the current item's
            rowWidth = $(this).outerWidth();
            // No longer the first row
            firstRow = false;
        }
        // Close all dimensions not in the first row
        if (!firstRow) {
            $(this).find(".dimOpen").removeClass("dimOpen mmm-lsnOn").addClass("dimClosed mmm-lsnOff");
            $(this).find("ul").hide();
        }
    });

    // If the variant table is wider than 908px, then it should scroll the overflow
    if ($("#variantTable").width() > 908) $("#productResults").css({
        "overflow-x": "scroll"
    });

    // Function for navigation dimension names
    $("#variantDimensions .dimension h5").on("click", function () {
        if ($(this).hasClass("dimOpen")) {
            $(this).removeClass("dimOpen mmm-lsnOn").addClass("dimClosed mmm-lsnOff");
            $(this).siblings("ul").hide();
        } else {
            $(this).removeClass("dimClosed mmm-lsnOff").addClass("dimOpen mmm-lsnOn");
            $(this).siblings("ul").show();
        }
    });

    // Function for loading additional refinements
    $("#variantDimensions .moreLink").on("click", function (e) {
        e.preventDefault();
        var moreHref = $(this).attr("href");
        // Assemble the URL to retrieve the refinements
        var refinementParams = 'pid=' + snap_PlaceId + '&plmlblid=' + snap_placementLabelSetId + '&plmid=' + snap_placementId + '&gblid=' + snap_globalLabelSetId + '&loc=' + snap_locale + '&' + moreHref.substring(moreHref.indexOf("?") + 1, moreHref.length);
        var refinementsURL = snap_ImagePath + 'AjaxServlet?' + refinementParams;
        // Begin the HTML for the refinements
        var newItems = "<h5 class='dimensionName dimOpen mmm-lsnOn'>" + $(this).parents("ul").prev().text() + "</h5><ul class='moreRefinements'>";
        // Retrieve the refinements
        $.get(refinementsURL, function (jsonData) {
            // Loop through each refinement
            for (var i = 0, j = jsonData.refinements.length; i < j; i++) {
                var ref = jsonData.refinements[i];
                // Add the HTML for the refinement
                newItems += "<li><a class='refinementLink' rel='nofollow' href='" + decodeURIComponent(ref.addRefinementUrl.substring(ref.addRefinementUrl.indexOf("?"), ref.addRefinementUrl.length)) + "'>" + ref.refinement_name + " (" + ref.size + ")</a></li>";
            }
            // Close the HTML for the new refinements
            newItems += "</ul>";
            // Open a colorbox with the new refinements
            $.colorbox({
                html: newItems
            });
            // Initialize the navigation again
            variantSkuInit();
            // Function for clicking refinements
            $(".refinementLink").on("click", function (e) {
                e.preventDefault();
                loadVariantPage($(this));
            });
        });
    });

    // Function for clicking refinements
    $("#variantDimensions .refinementLink").on("click", function (e) {
        e.preventDefault();
        loadVariantPage($(this));
    });

    // Pagination
    $("#productResults .paginationBar a").on("click", function (e) {
        e.preventDefault();
        loadVariantPage($(this));
    });
}

function loadMoreVariantsDRWTB (data){
    var language = document.getElementsByName("DC_coverage")[0].getAttribute('content'),
        $newVariants = $(data).find('.moreInfo'),
        newVariantsLength = $newVariants.length,
        psArray = [];


    for (var i = 0; i < newVariantsLength; i++) {
        psArray.push(
            new Object({
                widgetConfigurationId : DigitalRiverWTBKey,
                container : $('#DigitalRiverWTB-' + $newVariants.eq(i).text())[0],
                sku : language + '_' + $newVariants.eq(i).text()
            })
        );
    };
        
    for (var i = 0; i < newVariantsLength; i++) {
        ps_Show(psArray[i]);
    }
}

function loadVariantPage(refinement) {
    var refinementURL = $(refinement).attr("href"),
        currentURL = window.location.href,
        currURLWithoutParam = currentURL.substring(0, currentURL.indexOf("?"));
    // If &app=rudv is already in the URL we don't need to add it again
    if (refinementURL.indexOf("&app=rudv") > -1) {
        addlParams = "";
    } else {
        addlParams = "&app=rudv";
    }
    // Assemble the URL where the new table will come from
    if (currentURL.indexOf('~') < 0) {
        loadURL = currURLWithoutParam + '~/' + refinementURL.replace("rt=r3", "rt=rud").replace("&Nu=base_product_pk", "") + addlParams;
    } else {
        loadURL = currURLWithoutParam + refinementURL.replace("rt=r3", "rt=rud").replace("&Nu=base_product_pk", "") + addlParams;
    }
    // Display the loading gif
    $("#variantView").html("<img src='" + loadingImg + "' alt='loading' />");
    // If a colorbox is open, close it
    $.colorbox.close();
    // Load the new table
    $("#variantView").load(loadURL + " #variantView", function (data) {
        // Call the initialization function again
        variantSkuInit();
        // Reset the HTML for the navigation
        originalNavHTML = $("#variantDimensions").html();
        // Call the navigation initialization function again
        variantNavInit();
        // Apply button JS to any new buttons
        $("#variantTable button, #variantTable .primarybutton, #variantTable secondarybutton, #variantTable tertiarybutton").button();
        //WTB CI
        try {
            $(".wtbCIButton").colorbox({
                width: "600px",
                height: "500px",
                iframe: true
            });
        } catch (err) {};
        //WTB CI for Consumer
        try {
            $("#wtbCIButton").colorbox({
                width: "600px",
                height: "500px",
                iframe: true
            });
        } catch (err) {};

        //WTB DR
        try {
            loadMoreVariantsDRWTB(data);
        } catch (err) {};

        $("body").animate({
            "scrollTop": $("#variantView").offset().top
        });
    });
}

var bcFeaturePlayerReady = function () {
    featurePlayer = brightcove.getExperience("featuredPlayer");
    featureModule = featurePlayer.getModule(APIModules.VIDEO_PLAYER);
    if (playerAlias != "Error") {
        $.ajax({
            type: "POST",
            url: "/apxy/proxy?urlAlias=" + playerAlias + "_P&playlist_id=" + playlistID,
            success: bcFeaturedThumbs
        });
    }
}

var bcFeaturedThumbs = function (data) {
    var videos = !! data.videos ? data.videos : ( !! data.items ? data.items : data);
    featureModule.cueVideo(videos[i].id);
    for (i = 0; i < videos.length; i++) {
        thumbHTML = buildFeatureThumb(videos[i]);
        $("#bcFeaturedThumbs").append(thumbHTML);
    }
    $("#bcFeaturedThumbs .bcFeatureThumb").on("click", function () {
        featureModule.loadVideo($(this).attr("rel"));
    });
}

    function buildFeatureThumb(video) {
        var htmlString = $("<div class='bcFeatureThumb' rel='" + video.id + "'></div>");
        var imageSrc = !! video.thumbnailURL ? video.thumbnailURL : ( !! video.videoStillURL ? video.videoStillURL : '');
        var duration = !! video.length ? Math.round((video.length * .001)) : 0;
        var durMin = Math.floor(duration / 60) < 10 ? "0" + Math.floor(duration / 60) : Math.floor(duration / 60);
        var durSec = (duration % 60) < 10 ? "0" + (duration % 60) : (duration % 60);
        var imageHTML = $("<img src='" + imageSrc + "' alt='" + video.name + "(" + durMin + ":" + durSec + ")' />");
        var imageOverlay = $("<img class='playOverlay' src='" + playImg + "' />");
        var titleHTML = $("<span><a href='#'>" + video.name + "</a> (" + durMin + ":" + durSec + ")</span>");
        imageHTML.appendTo(htmlString);
        imageOverlay.appendTo(htmlString);
        titleHTML.appendTo(htmlString);
        return htmlString;
    }
	
	function loadBVuiInlineRatings() {
		$BV.ui( 'rr', 'inline_ratings', {
			productIds : bvRatingsProdIdJsonObject
		});
	}

    function initializeBVROI() {
        $("#shopBlock .wtbCIButton").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Purchase",
                    "label": "CatBodyWTB",
                    "value": 10
            });
        });

        $("#shopBlock .shop3mButton").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Purchase",
                    "label": "CatBodyBuyOnline",
                    "value": 10
            });
        });

        $("#mediaBlock .cboxElement[filetype=brightcove], #mediaListContainer .mediaListItem[filetype=brightcove]").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Engagement",
                    "label": "VideoStart",
                    "value": 9
            });
        });

        $("#mainTabInterface .docBlock a").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Engagement",
                    "label": "DownloadDoc",
                    "value": 8
            });
        });

        $("#mediaButtons .rootVoice, #buttonContainer a").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Social",
                    "label": $(this).text(),
                    "value": 7
            });
        });

        $("#mainDescripContainer a").on("click", function () {
            if (!($(this).hasClass("wtbCIButton") || $(this).hasClass("shop3mButton"))) {
                $BV.SI.trackConversion({
                    "type": "Engagement",
                        "label": $(this).text(),
                        "value": 5
                });
            }
        });

        $("#mainTabInterface .ui-tabs-nav a").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Engagement",
                    "label": $(this).text(),
                    "value": 4
            });
        });

        $("#variantTable .addcart").on("click", function () {
            $BV.SI.trackConversion({
                "type": "Purchase",
                    "label": "ProdResultsPurchaseNow",
                    "value": 10
            });
        });
    }

	// 360 Image
	function init360(data){
	
			var fileUrl = data.firstfileurl,
			celumID = '';
			$(".img360").each(function(){
				var temp = this.getAttribute('data-celum');
				if(fileUrl.indexOf(temp)){
					celumID = temp;
				}
			})
			var $thumbnail = $(".img360[data-celum=" + celumID + "]");	
			$thumbnail.find("img").attr("src", fileUrl);
			$thumbnail.attr("parentimage", fileUrl).find("img").attr("src", fileUrl);
			$(".mediaListItem[data-celum="+ celumID +"]").show();

			img360Count--;
			
			var magic360Options = "columns: "+data.columns+"; "+
								  "rows: "+data.rows+"; "+								  
								  "large-filename: "+data["large-filename"]+";"+
								  "filename: "+data.filename+"; ";
			
			// multiple 360 image starts
			$(".Magic360.cbImg360[data-celum=" + celumID + "]").attr("data-magic360-options", magic360Options);
			$(".Magic360.cbImg360[data-celum=" + celumID + "]").attr("href", data.firstfileurl);
			$(".Magic360.cbImg360[data-celum=" + celumID + "]").find("img").attr("src", data.firstfileurl);		
			// multiple 360 image ends
			
		    if(img360Count === 0) {
				magic360Load();
			}
    }	
	
	function magic360LoadCallback(){
		// onready method will get fired after completion of every 360 images loaded.
		Magic360.options = {
			onready: function(spin) { 
				var selectedId = $('.img360.mediaListItem.mliSelected')[0].getAttribute('data-celum');
				var loadedId = spin.getAttribute('data-celum');
				if(selectedId == loadedId){
					spin.parentNode.style.display = 'block';
				}else{
					spin.parentNode.style.display = 'none';
				}
			}
		}
		
	}

	function magic360Load(){
		//We have to have the 360 image information before the JS is loaded
		$.getScript("/3MContentRetrievalAPI/BlobServlet?univid=1361842017891&locale=en_WW&assetType=MMM_Image&blobAttribute=ImageFile&fallback=true"
		,magic360LoadCallback);

		$(".js-360").each(function(){
			if(!$(this).find("img").attr("src")) $(this).hide();
		});
	}


	$(document).ajaxComplete(function(event, jqXHR, ajaxOptions){
		console.log(event);
		console.log(jqXHR);
		console.log(ajaxOptions);
	});

$(document).ready(function () {


    loadCookie();

    // hide extra color swatch checkboxes when using multi-select
    hideColorSwatchHeaders();

    // Sizes #mainImageBlock to the height of the tallest image
    if($('#mainImageBlock').length){
        calcMainImageHeight();
    }
    
    // Sizes each .dimension to the width of the widest .dimension
    if($('.dimension').length){
        calcVariantNavWidth();
    }
	
	// If bvRatingsProdIdJsonObject is a non empty object call Method
	if (JSON.stringify(bvRatingsProdIdJsonObject) != '{}' && bvRatingsProdIdJsonObject != undefined  ){
		loadBVuiInlineRatings();
	}

    if (navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
        $("#snap_compareItemsHolder").css("position", "static");
    }

    if ($('div#breadcrumbs A').length > 0) {
        if ($('#cShellBcrumb P A').length > 0) $('#cShellBcrumb P A').insertBefore($('div#breadcrumbs A:first')).after(' > ');
    } else {
        if ($('#cShellBcrumb P A').length > 0) $('#cShellBcrumb P A').prependTo($('div#breadcrumbs')).after(' > ');
    }
    $('#cShellBcrumb P').html($('div#breadcrumbs').html());
    $('div#breadcrumbs').css('display', 'none');


    //If this a search page then we want the default value of the search to be the searched term 
    //So don't write over the searched term or turn on the onblur event
    if ($('#snap_searchTerm').attr('value') === '') {
        $('#snap_searchTerm').attr('value', defSearchMsg);
        $('#snap_searchTerm').focus(

        function () {
            $(this).attr('value', '');
            $(this).removeClass('nofocus');
        });
    }


    //Also, if this is a full search highlight the appropriate link
    if (fSearch == "true") {
        $('#eallpr').addClass('selected');
    } else {
        $('#ectx').addClass('selected');
    }

    //Unhide the sort bar if javascript is active
    $('#sortBar').css('display', 'block');
    //Unhide compare checkboxes if javascript is active
    $('.prodCell .prodCompareWTB').css('display', 'block');


    //For L3 or SERP pages, modify the height of the product cells
    adjustProdCells();

    //Add mouseover for brands bar on L1 pages
    $('#byBrandsListContainer LI').click(function () {
        //Adding the onclick to the LI means they don;t just have to click on the text to open the brands page
        location.href = $(this).children('A').attr('HREF');
    });
    $('#byBrandsListContainer LI').hover(function () {
        var index = $('#byBrandsListContainer LI').index($(this));
        $(this).toggleClass('highlighted');
        //var obj = $(this).find('.brandsDialog');
        var obj = $('#byBrandsListContainer div.brandsDialog:eq(' + index + ')');

        obj.click(function () {
            location.href = $('#byBrandsListContainer LI:eq(' + index + ')').children('A').attr('HREF');
        });
        if ($(window).width() < 1150) {
            obj.addClass('flipped');
            obj.css('left', $(this).offset().left - 150);
        } else {
            obj.removeClass('flipped');
            obj.css('left', $(this).offset().left + 130);
        }
        obj.css('top', $(this).offset().top - 30);
        obj.css('display', 'block');
    },

    function () {
        var index = $('#byBrandsListContainer LI').index($(this));
        $(this).toggleClass('highlighted');
        //var obj = $(this).find('.brandsDialog');
        var obj = $('#byBrandsListContainer div.brandsDialog:eq(' + index + ')');
        obj.css('display', 'none');
    });
    //Also add hover to the brands dialogs themselves
    $('div.brandsDialog').hover(function () {
        var index = $('#byBrandsListContainer div.brandsDialog').index($(this));
        $('#byBrandsListContainer LI:eq(' + index + ')').addClass('highlighted');
        $(this).css('display', 'block');
    },

    function () {

        var index = $('#byBrandsListContainer div.brandsDialog').index($(this));
        $('#byBrandsListContainer LI:eq(' + index + ')').removeClass('highlighted');
        $(this).css('display', 'none');
    })


    //This block of code initializes the navigation bar on the left for L3 pages, but only if the outer wrap exists
    $('#mmmlsnouterwrap #mmmprodnavwrap').css('margin-right', '0px');
    $('#mmmprodnavwrap H5.dimension:lt(3)').addClass('dimOpen mmm-lsnOn');
    $('#mmmprodnavwrap H5.dimension:gt(2)').removeClass('dimOpen mmm-lsnOn');
    $('#mmmprodnavwrap H5.dimension:gt(2)').addClass('dimClosed mmm-lsnOff');
    $('#mmmprodnavwrap H5.dimension:gt(2)').each(function () {
        var id = $(this).attr('ID');
        $('#ul-' + id).css('display', 'none');
    });

    $('#mmmprodnavwrap H5.dimension').click(function () {
        $(this).toggleClass('dimOpen mmm-lsnOn');
        $(this).toggleClass('dimClosed mmm-lsnOff');
        var id = $(this).attr('ID');
        if ($(this).hasClass('dimClosed mmm-lsnOff')) {
            $('#ul-' + id).css('display', 'none');
        } else {
            $('#ul-' + id).css('display', 'block');
        }
    });

    $('#mmmprodnavwrap LI.moreAjax').click(function () {
        $(this).children('A').html(txt_loading);
        var refinementParams = 'pid=' + snap_PlaceId + '&plmlblid=' + snap_placementLabelSetId + '&plmid=' + snap_placementId + '&gblid=' + snap_globalLabelSetId + '&loc=' + snap_locale + '&' + $(this).find("a").attr("ajaxURL");
        var refinementsURL = snap_ImagePath + 'AjaxServlet?' + refinementParams;

        var newItems = '';
        
        var parId = $(this).parents("ul").attr('id');
        $.get(refinementsURL, function (jsonData) {
            for (var i = 0; i < jsonData.refinements.length; i++) {
                for (var j = i; j < jsonData.refinements.length; j++) {
                    if (jsonData.refinements[j].refinement_name.toLowerCase() < jsonData.refinements[i].refinement_name.toLowerCase()) {
                        var temp = jsonData.refinements[j];
                        jsonData.refinements[j] = jsonData.refinements[i];
                        jsonData.refinements[i] = temp;
                    }
                }

                // declare vars to parse out our color string into color names and hex values
                var ref = jsonData.refinements[i],
                refName = jsonData.refinements[i].refinement_name,
                ImgOrHex = refName.substring(0,refName.indexOf('|')),
                refSwatchStr = refName.substring(refName.indexOf('|')+1),
                refSwatchColor = refSwatchStr.substring(0,refSwatchStr.indexOf('~')),
                refSwatchHexOrImg = refSwatchStr.substr(refSwatchStr.indexOf('~')+1);

                var multiSelectCheckbox = '';

                if (ref.isSelected && ref.isSelected === 'true' && ref.multiselect && ref.multiselect === 'true') {
                    multiSelectCheckbox = '<div class="multiSelectCheckbox">X</div>';
                } else if(ref.isSelected && ref.isSelected === 'false' && ref.multiselect && ref.multiselect === 'true'){
                    multiSelectCheckbox = '<div class="multiSelectCheckbox">&#160;</div>';
                }

                // If we're using a color string build our links out this way
                if (ImgOrHex.indexOf('CSFC') > -1) {
                    newItems += "<li><div class='swatchBox'><a class='swatchBoxLink' rel='nofollow' href='" + burl + ref.addRefinementUrl + "' onclick='dcsMultiTrack(\"WT.cg_n\",\"PC - Add category filter from: \" + dcsTitle + \"; PC - Number of filters applied\",\"WT.cg_s\",\"" + ref.refinement_name + ";" + $(".breadbox li").length + 1 + "\",\"DCS.dcsuri\",window.location.pathname+\"AddCategoryFilters\",\"WT.ti\",\"Add Category Filters\",\"WT.z_catfilter\",\"1\")'><div class='swatchBoxColor' style='background-color:#"+refSwatchHexOrImg+"; '></div>"+ refSwatchColor + " (" + ref.size + ")</a></div>"+ multiSelectCheckbox +"</li>";
                }else if(ImgOrHex.indexOf('CSFI') > -1){
                    newItems += "<li><div class='swatchBox'><a class='swatchBoxLink' rel='nofollow' href='" + burl + ref.addRefinementUrl + "' onclick='dcsMultiTrack(\"WT.cg_n\",\"PC - Add category filter from: \" + dcsTitle + \"; PC - Number of filters applied\",\"WT.cg_s\",\"" + ref.refinement_name + ";" + $(".breadbox li").length + 1 + "\",\"DCS.dcsuri\",window.location.pathname+\"AddCategoryFilters\",\"WT.ti\",\"Add Category Filters\",\"WT.z_catfilter\",\"1\")'><img alt='"+refSwatchColor+"' class='swatchBoxColor' src="+refSwatchHexOrImg+" />"+ refSwatchColor + " (" + ref.size + ")</a></div>"+ multiSelectCheckbox +"</li>";
                    
                } else {
                    //otherwise build out normal links
                    newItems += "<li><a rel='nofollow' href='" + burl + ref.addRefinementUrl + "' onclick='dcsMultiTrack(\"WT.cg_n\",\"PC - Add category filter from: \" + dcsTitle + \"; PC - Number of filters applied\",\"WT.cg_s\",\"" + ref.refinement_name + ";" + $(".breadbox li").length + 1 + "\",\"DCS.dcsuri\",window.location.pathname+\"AddCategoryFilters\",\"WT.ti\",\"Add Category Filters\",\"WT.z_catfilter\",\"1\")'>" + ref.refinement_name + " (" + ref.size + ")</a>"+ multiSelectCheckbox +"</li>";
                }   
                
            }

            $('#' + parId).html(newItems);
        });
    });

    // End block

    snapManager.init();
    snapCompareTrayManager.init();

    //Make sure the 2 featuredRecordsHoriz divs on the L1 page are sized the same
    $('.featuredRecordsHoriz:eq(0)').each(function () {
        if ($(this).height() > $('.featuredRecordsHoriz:eq(1)').height()) {
            $('.featuredRecordsHoriz:eq(1)').height($(this).height());
        } else {
            $(this).height($('.featuredRecordsHoriz:eq(1)').height());
        };
    });

    //If this is a gallery then add a mouseover for the product images in the gallery
    $('#productRecords .mainProdImg').hover(function () {

        var starRatingHtml = $(this).parent().find('.corpBVInlineRating').clone().wrap('<p>').parent().html();

        if ($(this).find("a").attr("href").indexOf("rt=d") > -1 || $(this).find("a").attr("href").indexOf("rt=rud") > -1) {
            if ($('BUTTON', this).length > 0) {
                $('BUTTON', this).show();
            } else {
                var $imgCont = $(this);

                var href = $('A', this).attr('href') + '&soloMode=true&app=qv';
                var $button = $('<BUTTON CLASS="tertiarybutton qvButton">' + txt_quickView + '</BUTTON>');
                $(this).append($button);
                $button.button().position({
                    my: "center top+40",
                    at: "center top",
                    of: $imgCont
                });
                $(this).find('.qvButton').click(function () {
                    openQuickView(href, this, starRatingHtml);
                })
            };
        }
    },

    function () {
        $('BUTTON', this).hide();
    });

    $("#bcMainCategory .categoryName").on("click", function () {
        if ($(this).find("h5").hasClass("catClosed")) {
            $(this).parent(".category").addClass("categorySelected");
            $(this).addClass("catNameSelected");
            $(this).find("h5").removeClass("catClosed").addClass("catOpen");
            $("#bcMainCategory ul." + $(this).attr("rel")).show();
        } else {
            $(this).parent(".category").removeClass("categorySelected");
            $(this).removeClass("catNameSelected");
            $(this).find("h5").removeClass("catOpen").addClass("catClosed");
            $("#bcMainCategory ul." + $(this).attr("rel")).hide();
        }
    });

    try {
        //Initialize the Also Viewed carousel
        loadAV();
    } catch (err) {};

    try {
        if(pageTypeModule === 'snapsJsDetailsObject') {
            loadRatings();
        }
    } catch (err) {};

    //WTB CI
    try {
        $(".wtbCIButton").colorbox({
            width: "600px",
            height: "500px",
            iframe: true
        });
    } catch (err) {};
    //WTB CI for Consumer
    try {
        $("#wtbCIButton").colorbox({
            width: "600px",
            height: "500px",
            iframe: true
        });
    } catch (err) {};


    $('#needHelpContainer div.liveChatBox').css('display', 'block');

    //Initiate the tabs interface and hide the nonjs tabs
    $('div#mainTabInterface ul').css('display', 'block');
    $('.nonJSTabHeader').css('display', 'none');
    $('div#mainTabInterface').tabs();

    $('#relProdsAccordion').accordion();

    //Hide any reviews over 5
    $('.reviewContainer:gt(4)').css('display', 'none');
    //Unhide the display all reviews link
    $('#viewAllReviews').css('display', 'inline');
    //Change the number of displayed reviews to 5
    $('#reviewDisplayNum').html('5');


    //Instantiate the brightcove player(s)
    try {
        if ($("#myExperience").length > 0) {
            brightcoveMarkup = $("#myExperience").clone();
            brightcove.createExperiences();
        }
        initBCPlayerColorbox();
    } catch (err) {};


    //If we have more than one thumbnail we need to initialize the mediaBlock
    if ($('#mediaBlock div').length > 0) {
        //Size the media block (it needs to retain maximum height if no js)
        $('#mediaBlock').height(50);
        //Highlight the first media block since it should be selected by default
        $('#mediaBlock div:eq(0)').addClass('HOVER');
        //Unhide the media block
        $('#mediaBlock').css('display', 'block');
        //Mouseover for image blocks under the main image
        $('#mediaBlock div').mouseover(function () {
            $('#mediaBlock div').removeClass('HOVER');
            $(this).addClass('HOVER');
            //Only hide the main image and display a new one if they hover over an image, not a video
            if ($(this).attr('type') == 'image') {
                var imagename = $(this).attr('parentImage');
                $('#mainImageBlock div').css('display', 'none');
                $('#' + imagename).css('display', 'block');
            } else if ($(this).attr('type') == 'img360'){
                $('#mainImageBlock div').css('display', 'none');
                $('#mainImageBlock .full360Img').css("display", "block").find("img").attr("src", $(this).attr("parentimage")).attr("alt", $(this).find("img").attr("alt")).attr("title", $(this).find("img").attr("title"));
            }
        })

        $('#mediaBlock div').colorbox({
            photo: false,
            inline: true,
            href: "#mediaColorBox",
            onOpen: function () {
                if ($('#cbFPPlayer').length > 0) {
                    initFP()
                };
                selectPlayer($(this));
            },
            onCleanup: function () {
                if ($('#cbFPPlayer').length > 0) {
                    $f('cbFPPlayer').unload();
                };
                bcExp = null;
                modVP = null;
                $('#colorboxBC').remove();
            }
        });

        //Onclick events for the listed media items in the actual colorbox
        $('#mediaColorBox .mediaListItem').click(function () {
            selectPlayer($(this));
        });

        if ($('#mediaBlock div').length > 5) {
            //Setup the allMediaLink so it opens the first image/video if we have more than 5 thumbnails
            $('#allMediaLink').css('display', 'block');
            $('#allMediaLink').colorbox({
                photo: false,
                inline: true,
                href: "#mediaColorBox",
                onOpen: function () {
                    if ($('#cbFPPlayer').length > 0) {
                        initFP()
                    };
                    selectPlayer($('#mediaBlock div:eq(0)'))
                },
                onCleanup: function () {
                    if ($('#cbFPPlayer').length > 0) {
                        $f('cbFPPlayer').unload();
                    };
                    bcExp = null;
                    modVP = null;
                    $('#colorboxBC').remove();
                }
            });
        }
    }


    variantSkuInit();
    originalNavHTML = $("#variantDimensions").html();
    variantNavInit();

    var relatedProds = new Array();
    var numProds = 0;

    $("#relatedUL li").each(function (i) {
        relatedProds[i] = $(this);
    });
    $("#relatedUL").remove();
    $(".relatedProdCarousel li").remove();
    var relatedUL = $("#relatedProdCarouselContainer").html();
    for (i = 0; i < relatedProds.length; i++) {
        if ($(relatedProds[i]).hasClass($("#relatedList li:first-child").attr("rel"))) {
            $(".relatedProdCarousel").append($(relatedProds[i]).clone());
            numProds++;
        }
    }
    if (numProds % 4 != 0) {
        for (i = 0; i < 4 - (numProds % 4); i++) {
            $(".relatedProdCarousel").append("<li>&nbsp;</li>");
        }
    }
    if (numProds < 5) $("#relProdPagination").hide();
    $(".relatedProdCarousel").jcarousel({
        animation: 'slow',
        scroll: 4,
        wrap: "both",
        buttonNextHTML: $("#relatedProdCarouselContainer .carouselrightbutton"),
        buttonPrevHTML: $("#relatedProdCarouselContainer .carouselleftbutton"),
        initCallback: carouselCallback,
        itemFallbackDimension: 160,
        itemFirstInCallback: function (carousel, item, idx, state) {
            // Count the previous number of products for the tooltip
            var prevProd = 0;
            if (idx == 1) {
                for (i = 0; i < 4; i++) {
                    if ($(".jcarousel-item:eq(" + ($(".jcarousel-item").length - i - 1) + ")").text().replace(/\s/g, "") != "") prevProd++;
                }
            }
            if (prevProd == 0) prevProd = 4;
            $("#relatedProdCarouselContainer .carouselleftbutton").attr("title", relProdPrev + " " + prevProd + " " + relProdProducts);
        },
        itemLastInCallback: function (carousel, item, idx, state) {
            // Count the next number of products for the tooltip
            var nextProd = 0;
            for (i = 0; i < 4; i++) {
                if ($(".jcarousel-item:eq(" + (idx + i) + ")").text().replace(/\s/g, "") != "") nextProd++;
            }
            if (nextProd == 0) nextProd = 4;
            $("#relatedProdCarouselContainer .carouselrightbutton").attr("title", relProdNext + " " + nextProd + " " + relProdProducts);
        }
    });
    $(".relatedProdCarousel").css({
        "width": ($(".relatedProdCarousel li").length * 160) + "px"
    });
    if ($(".relatedProdCarousel li").length < 5) $("#relatedProdCarouselContainer button").hide();

    $("#relatedList li").on("click", function () {
        var numProds = 0;
        $("#relatedList li").removeClass("selected");
        $(this).addClass("selected");
        $("#relatedProdCarouselContainer").html(relatedUL);
        for (i = 0; i < relatedProds.length; i++) {
            if ($(relatedProds[i]).hasClass($("#relatedList li.selected").attr("rel"))) {
                $(".relatedProdCarousel").append($(relatedProds[i]).clone());
                numProds++;
            }
        }
        if (numProds % 4 != 0) {
            for (i = 0; i < 4 - (numProds % 4); i++) {
                $(".relatedProdCarousel").append("<li>&nbsp;</li>");
            }
        }
        if (numProds < 5) $("#relProdPagination").hide();
        else {
            $("#curPage").text("1");
            $("#totalPage").text(Math.ceil(numProds / 4));
            $("#relProdPagination").show();
        }
        $(".relatedProdCarousel").jcarousel({
            animation: 'slow',
            scroll: 4,
            wrap: "both",
            buttonNextHTML: $("#relatedProdCarouselContainer .carouselrightbutton"),
            buttonPrevHTML: $("#relatedProdCarouselContainer .carouselleftbutton"),
            initCallback: carouselCallback,
            itemFallbackDimension: 160,
            itemFirstInCallback: function (carousel, item, idx, state) {
                // Count the previous number of products for the tooltip
                var prevProd = 0;
                if (idx == 1) {
                    for (i = 0; i < 4; i++) {
                        if ($(".jcarousel-item:eq(" + ($(".jcarousel-item").length - i - 1) + ")").text().replace(/\s/g, "") != "") prevProd++;
                    }
                }
                if (prevProd == 0) prevProd = 4;
                $("#relatedProdCarouselContainer .carouselleftbutton").attr("title", relProdPrev + " " + prevProd + " " + relProdProducts);
            },
            itemLastInCallback: function (carousel, item, idx, state) {
                // Count the next number of products for the tooltip
                var nextProd = 0;
                for (i = 0; i < 4; i++) {
                    if ($(".jcarousel-item:eq(" + (idx + i) + ")").text().replace(/\s/g, "") != "") nextProd++;
                }
                if (nextProd == 0) nextProd = 4;
                $("#relatedProdCarouselContainer .carouselrightbutton").attr("title", relProdNext + " " + nextProd + " " + relProdProducts);
            }
        });
        if ($(".relatedProdCarousel li").length < 5) $("#relatedProdCarouselContainer button").hide();
        else $("#relatedProdCarouselContainer button").show();
    });

    $("#simpleSkuSelector .skuSelect").on("change", function () {
        location.href = location.href.substring(0, location.href.indexOf("?")) + $(this).val();
    });

    $("#simpleSkuSelector a").on("click", function (e) {
        e.preventDefault();
        location.href = location.href.substring(0, location.href.indexOf("?")) + $(this).attr("href").replace("rt=r3", "rt=rud");
    });

    $("#prodInfoContainer .prodResultsLink, #prodResultsSupport .prodResultsRedLink, #prodResultsButton .prodResultsLink").on("click", function (e) {
        var modelsTab = 0;
        $("#mainTabInterface .ui-tabs-nav a").each(function (i) {
            if ($(this).text().indexOf(modelsTxt) > -1) modelsTab = i;
        });
        $('div#mainTabInterface').tabs({
            selected: modelsTab
        });
    });

    // Find the tallest product image and set the container height to the height of the tallest image
    $("#mainImageBlock .productImage").each(function (index) {
        $(this).show();
        if ($(this).find("img").height() > maxImgHeight) maxImgHeight = $(this).find("img").height();
        if (index !== 0) $(this).hide();
    }).height(maxImgHeight);

    // Determine the target for any WTB URL buttons
    if ($("#wtbUrlBtn").length && !$("#wtbUrlBtn").attr("target")) {
        var WTBUrl = !! $("#wtbUrlBtn").attr("href") ? $("#wtbUrlBtn").attr("href") : '';
        if (WTBUrl.indexOf(location.host.replace("previewext", "").replace("solutionsstage", "").replace("solutions", "")) < 0) $("#wtbUrlBtn").attr("target", "_blank");
    }

    // Facebook two click like button
    $("#fbTwoClick a").on("click", function () {
        $(this).hide();
        addFacebook(document, 'script', 'facebook-jssdk');
    });


    if (brightcoveMarkup != "") {
        $("#mainTabInterface li[role=tab] a").on("click", function () {
            try {
                var bcParent = $("#myExperience").parent();
                $("#myExperience").remove();
                bcParent.prepend(brightcoveMarkup);
                brightcove.createExperiences();
            } catch (e) {}
        });
    }

	// Count the 360-type images
    $(".js-360").each(function(){        
        img360Count++;
	});
	
	// 360 Image
    $(".js-360").each(function() {
        $.ajax({
            url: "http://multimedia.mmm.com/mws/media360/" + $(this).data("celum") + "/properties.json?callback=init360",
            dataType: "jsonp",
            error: function(){
                $(this).hide();
            }
        });
    });	
}); // end doc.ready()