// IMPORTANT: Since serializeJSON converts numeric values to float,
// we added space in front of the size to keep it as string value.
// We must trim the size to remove the white space.

// Global var hold value to help decide that the inline Add to cart pop-up is already open.
var inlinePopUpOpened = 0;
var defaultsku = "";
var wishlistID = 0;
var wlitemID = 0;

$(document).ready(function() {
	var sku = $("#pdp_selectedSKU").val();
	defaultsku = sku;
	//reset the form for firefox
	document.getElementById("product_form").reset();
	if (location.href.indexOf("#tab-sizing") != -1){
		viewTab('sizing', true);
	}
	if ($("#WISHLIST_ID").length){
		wishlistID = $("#WISHLIST_ID").val();
		wlitemID = $("#WISHLIST_ITEM_ID").val();
	}
	for (styleSKU in styles) {
		var style = styles[styleSKU];
		style.SKU = styleSKU;

		// preloading wide (300px) images
		var imageObj = new Image();
		imageObj.src = getImageForSKU(styleSKU);
		if (inline_zoom_enabled 
			&& sku == styleSKU // only load selected sku on load
			&& style[idx_isscene7]) {
			var scene7imageObj = new Image();
			scene7imageObj.src = getScene7ZoomURL(styleSKU);
		}
	}
	
	$("#pdp_styles a").hover(
		function() {
			hoverStyle(_getIDFromString(this.id));
			//$("#pdp_zoomImageSKU").val($("#pdp_selectedSKU").val());
		},
		revertStyle
	);
	$("#pdp_styles a").click(function() {
		selectStyle(_getIDFromString(this.id));
		OpenShopTogetherToolBar();
		updateMyBuysData();
		activeAltImgForSku[_getIDFromString(this.id)] = null;

		// restore Read review link href for IE
		if ($.browser.msie && typeof(bv_RR_enabled) != "undefined" && bv_RR_enabled == true) {
			var originalURL = $(location).attr('href');
			var restoreReadReviewsURL = originalURL.slice(0, originalURL.indexOf("#")) + '#BVRRWidgetID';
			$("#BVRRRatingSummaryLinkReadID a").attr("href", restoreReadReviewsURL);
			$("#BVRRRatingSummaryLinkReadID a").bind("click", function() {
				if (typeof readReviews == 'function') {
					readReviews();
					return false;
				}
			});
		}
	});
	
	$("#pdp_sizes li a").hover(hoverSize, revertSize);
	$("#pdp_sizes li a").click(selectSize);
	
	$("#pdp_tabs li a").click(gotoTab);
	$("#pdp_tabs li a").hover(hoverTab, revertTab);
	pdp_selected_tab = $("#pdp_tabs li.selected a").attr("rel");

	// Select size if there is only one available for style
	var defaultStyle = styles[sku];
	if (defaultStyle[idx_sizes].length == 1) {
		var size = defaultStyle[idx_sizes][0][sizeString_index].trim();
		if (size != "")
			$("#pdp_selectedSize").val(size);
	}
	
	if (defaultSize.trim() != "") {
		$("#pdp_selectedSize").val(defaultSize);
	}
	
	selectHashValues();

	toggleScene7Zoom(sku);

	if (typeof(alternateProductImagesEnabled) != "undefined" && alternateProductImagesEnabled == true) {
		showAlternateImages(sku);
	}
	
	scrollToSKU();
	
	$("#pdp_sizeAvailable").html("(Select a size)");
	var selectedSize = $("#pdp_selectedSize").val();
	if (selectedSize != "") {
		var selectedSizeTag = _anchorTagForSize(selectedSize);
		if (selectedSizeTag != null) {
			selectedSizeTag.addClass("selected");
			selectedSizeTag.each(hoverSize); // this is to select or reset availability and price	
		}
	}
	
	initializeHotLaunchCounter();
    checkHotSkuLimit(sku);
	var shadowboxOptions = {
		loadingImage: shadowboxPath + 'loading.gif', 
		overlayBgImage: shadowboxPath + 'overlay-85.png',
		flvPlayer: shadowboxPath + 'flvplayer.swf'
	}
	Shadowbox.init(shadowboxOptions);
	
	if (inlineAddToCartEnabled) {
		$.ajaxSetup({ cache: false });
		/* handle click close outside of ILATC window*/
		$(document).click(function(e){
			if ($("#cartAdd_box").length){
				var UpX = parseFloat($("#cartAdd_box").position().left);
				var UpY = parseFloat($("#cartAdd_box").position().top);
				var BotX = parseFloat($("#cartAdd_box").width() + UpX)
				var BotY = parseFloat($("#cartAdd_box_bottom").height() + $("#cartAdd_box_bottom").position().top + UpY);
				
				var Mx = parseFloat(e.pageX);
				var My = parseFloat(e.pageY);
				if (Mx < UpX || My < UpY || Mx > BotX || My > BotY){
					closeCartAdd();
				}
			}
		});
	}
			
	//defaultavailability(sku);
	setBVQASessionParams();

	if (typeof(bv_RR_enabled) != "undefined" && bv_RR_enabled == true) {
		if (typeof(cm_Attributes) != "undefined") {
			if (cm_Attributes != null) {
				$("#bvRRAttributes").val(cm_Attributes);
			}
		}
	}

 	displayVideoButton(sku);
	displayBatGuarantee(sku);

// ipad/iphone/ipod touchend event fix for jquery hover
	$('a').live('touchend', function(e) {
    var el = $(this);
    var link = el.attr('href');
    //window.location = link;
	});

});

function hoverTab() {
	var tab = $(this).attr("rel");
	
	$(this).parent("li").addClass("hover");
}

function revertTab() {
	var tab = pdp_selected_tab;
	
	$(this).parent("li").removeClass("hover");
}

function gotoTab() {
	$(this).parent("li").addClass("selected");
	$(this).parent("li").siblings().removeClass("selected");
	
	pdp_selected_tab = $(this).attr("rel");
	$("#pdp_tabContents .tabContent").removeClass("selected");
	$("#pdp_tabContent_" + pdp_selected_tab).addClass("selected");
	
	if ($("#pdp_tabContent_" + pdp_selected_tab).hasClass("notLoaded")) {
		$("#pdp_tabContent_" + pdp_selected_tab).html(pdp_tabContent[pdp_selected_tab]);
		$("#pdp_tabContent_" + pdp_selected_tab).removeClass("notLoaded");
	}
	
	if (pdp_selected_tab != "description") {
		var tabContainerID = "";
		var tabContainerType = "";
		if (pdp_selected_tab == "sizing") {
			tabContainerID = "productsizing";
			tabContainerType = "frame";
			$("#" + tabContainerID).load(function() {
				adjustTabSize(tabContainerID, tabContainerType);
			});
		} else {
			tabContainerID = "pdp_tabContent_" + pdp_selected_tab;
			tabContainerType = "div";
			adjustTabSize(tabContainerID, tabContainerType);
		}
	}
}

function viewTab(tab, scroll) {
	if (tab == "sizing") {
		cmCreateConversionEventTag("Sizing Help", 1, "PDP Sizing", 0);
	}
	
	var tabBar = $("#pdp_tabs a[rel='" + tab + "']").parent("li");
	tabBar.addClass("selected");
	tabBar.siblings().removeClass("selected");
	
	$("#pdp_tabContents .tabContent").removeClass("selected");
	$("#pdp_tabContent_" + tab).addClass("selected");	
	
	pdp_selected_tab = tab;

	if ($("#pdp_tabContent_" + pdp_selected_tab).hasClass("notLoaded")) {
		$("#pdp_tabContent_" + pdp_selected_tab).html(pdp_tabContent[pdp_selected_tab]);
		$("#pdp_tabContent_" + pdp_selected_tab).removeClass("notLoaded");
	}

	if (scroll) {
		var offset = tabBar.offset();
		$("html,body").animate({scrollTop: offset.top - 45});
	}
	
	if (tab == "sizing") {
		cmCreateConversionEventTag("Sizing Help", 2, "PDP Sizing", 0);
	}
}

function displayVideoButton(sku) {
	var style = styles[sku];
        if (style[idx_hasVideo]) {
                $("#viewVideos").show();
                $("#pdp_viewLargerImage").css('float','left');
                $("#pdp_viewFullScreen").css('float','left');
                $("#pdp_viewLargerImage").css('text-align','left');
                $("#pdp_viewFullScreen").css('text-align','left');
        }
	else {	
		$("#viewVideos").hide();
                $("#pdp_viewLargerImage").css('float','none');
                $("#pdp_viewFullScreen").css('float','none');
                $("#pdp_viewLargerImage").css('text-align','center');
                $("#pdp_viewFullScreen").css('text-align','center');
	}
}
function displayBatGuarantee(sku) {
	var style = styles[sku];
	var specificProductType = style[idx_styleAttributes]["SPECIFIC_PRODUCT_TYPE"];
	var button = $("#pdp_batguarantee");
	if (button.length == 0)
		return;

	button.hide();

	if (specificProductType && "Senior League Bats,Baseball Bats,Little League Bats,Softball Bats,".indexOf(specificProductType+",") != -1) {
		button.show();
		button.css("cursor","pointer");
		button.css("margin","5px 0");
		button.click(function() {
			var overlay = $("#pdp_batguarantee_window");
			if (overlay.length != 0) {
				overlay.css("z-index","1111");
				overlay.css("cursor","pointer");
				overlay.css("position","absolute");
    				overlay.css("top", ( $(window).height() - overlay.outerHeight() ) / 2+$(window).scrollTop() + "px");
				overlay.css("left", ( $(window).width() - overlay.outerWidth() ) / 2+$(window).scrollLeft() + "px");
				overlay.show();
				overlay.click(function() {
					$("#pdp_batguarantee_window").hide();
               		 		cmCreateConversionEventTag("Bat Guarantee", 2, "PDP", 0);
				});

		                cmCreateConversionEventTag("Bat Guarantee", 1, "PDP", 0);
			}
		});
	}

        if (style[idx_hasArticle]) {
		pdp_selected_tab = "articles";
                viewTab('articles', false);
		$("#pdp_tab_articles a").html("Bat Rules");

        }
}

function loadTabContents(sku) {
	var style = styles[sku];
	var hasArticle = false;
	var hasVideo = false;
	
	if (style[idx_hasArticle]) {
		hasArticle = true;
		$("#pdp_tab_articles").removeClass("hidden");
		$("#pdp_tabContent_articles").removeClass("hidden");
	}
	else {
		$("#pdp_tab_articles").addClass("hidden");
		$("#pdp_tabContent_articles").addClass("hidden");		
	}

	if (hasArticle) _loadTabContents("articles", sku);

	if (style[idx_hasVideo]) {
		hasVideo = true;
		$("#pdp_tab_videos").removeClass("hidden");
		$("#pdp_tabContent_videos").removeClass("hidden");
		//viewTab('videos', false);
	}
	else {
		$("#pdp_tab_videos").addClass("hidden");
		$("#pdp_tabContent_videos").addClass("hidden");
		//viewTab('description', false);
	}

	//if (hasVideo) _loadTabContents("videos", sku);
}

function _loadTabContents(tab, sku) {
	var tabURL = pdp_path + "/tab.cfm?tab=" + tab;
	$("#pdp_tabContent_" + tab).load(tabURL, {sku: sku}, function(responseText, textStatus, XMLHttpRequest) {	
		if (textStatus != "success") {
			// $("body").html(responseText); // this is for debugging
			alert("Error: An error occurred while retrieving content.");
		}
		else {
			// reset shadowbox
			Shadowbox.clearCache();
			Shadowbox.setup();	
		}
	});
}

function adjustTabSize(tabSelected, tabType) {
	if (tabType == "frame") {
		if ($.browser.msie) {
			document.getElementById(tabSelected).style.height = document.getElementById(tabSelected).contentWindow.document.body.scrollHeight + "px";
		} else {
			$("#" + tabSelected).css("height", $("#" + tabSelected).contents().find("html").height() + "px");
		}
	} else {
		$("#" + tabSelected).css("height", "auto");
	}
}

/* select style/size from hash values */
function selectHashValues() {
	var hashString = location.hash.replace("#", "");
	var selectedSKU = "";
	var selectedSize = "";

	if (hashString.trim() != '') {
		var hashItems = hashString.split("&");
		for (hashItemIndex = 0; hashItemIndex < hashItems.length; hashItemIndex++) {
			var hashItem = hashItems[hashItemIndex];
			var keyValueArray = hashItem.split("=");
			if (keyValueArray.length == 2) {
				var key = keyValueArray[0];
				var value = keyValueArray[1];
				
				if (key.trim() == "sku") {
					selectedSKU = value.trim();
				}
				else if (key.trim() == "size") {
					selectedSize = value.trim();
				}
			}
		}
		
		if (selectedSKU.trim() != '' && $("#pdp_selectedSKU").val() != selectedSKU && styles[selectedSKU]) {
			$("#pdp_selectedSKU").val(selectedSKU);
			$("#pdp_zoomImageSKU").val(selectedSKU);
		}
		if (selectedSize.trim() != '' && $("#pdp_selectedSize").val() != selectedSize)
			$("#pdp_selectedSize").val(selectedSize);
			
		if (selectedSKU.trim() != '') {
			loadTabContents(selectedSKU);
		}
			
		// update facebook like button iframe
		if (typeof(fb_reload_like_iframe) != "undefined") {
			fb_reload_like_iframe();
		}			
	}
}


function updateHash() {
	var sku = $("#pdp_selectedSKU").val();

	var size = $("#pdp_selectedSize").val();
	
	var hashString = "#sku=" + sku;
	if (size.trim() != '') hashString += "&size=" + size;
	
	var locationHash = location.hash;
	var newLocation = location + '';
	if (locationHash.trim() != '') {
		newLocation = newLocation.replace(locationHash, hashString);
	}
	else {
		newLocation = newLocation + hashString;
	}
	//necessary for safari javascript urls
	if($.browser.safari) {
		newLocation = newLocation.replace('%2F','%252F');
	}
	setBVQASessionParams();
	location.replace(newLocation);
}

//indexes for style array
var idx_attributes		= 0;
var idx_excluded		= 1;
var idx_available		= 2;
var idx_xforyimage		= 3;
var idx_icon			= 4;
var idx_list_price		= 5;
var idx_sale_price		= 6;
var idx_sizes			= 7;
var idx_isscene7		= 8;
var idx_hasArticle		= 9;
var idx_hasVideo		= 10;
var idx_tierPricing		= 11;
var idx_styleAttributes	= 12;

// indexes for size array
var sizeString_index 	= 0;
var pr_list_index 		= 1;
var pr_sale_index 		= 2;
var availability_index 	= 3;




function scrollToSKU() {
	var selectedSKU = $("#pdp_selectedSKU").val();
	var styleID = "#pdp_style_" + selectedSKU;

	// This is for firefox not resetting the form value on reload
	{
		$("#pdp_styles a").removeClass("selected");
		$("#pdp_style_" + selectedSKU).addClass("selected");
		hoverStyle(selectedSKU);
	}
	
	var styleObj = $("img", styleID);
	var containerObj = $("#pdp_styles");
	var containerOffset = containerObj.offset();
	var styleOffset = styleObj.offset();
	if (typeof(styleOffset) == "undefined") return;
	var top = styleOffset.top - containerOffset.top;
	if (top > containerObj.height() - 5) {
		containerObj.scroll(0,0); // start at top
		containerObj.animate({scrollTop:top});
	}
}

/******************************
	style functions
******************************/

var hoverSKU = null;

function hoverStyle(sku) {
	hoverSKU = sku;
	setTimeout("makeAsyncHoverStyleFunctionsCall('" + sku + "')", 200);
}

function makeAsyncHoverStyleFunctionsCall(sku) {
	if (sku != hoverSKU) return;
	
	var style = styles[sku];
	
	replaceImageForSKU(sku);
	$("#productAttributes").html(style[idx_attributes]);
	$("#productSKU").html(sku);
	displayDefaultPriceForStyle(sku);
	displayThisShoeRunsIcon(sku);
	displayTierPricing(sku);
	displayStyleAttributes(sku);
	highlightAvailableSizesForStyle(style);
	highlightNoSizeStyle(sku);
	initializeHotLaunchCounter(sku);
	
	if (style[idx_excluded]) {
		$("#pdp_excludedMessage").html(exclusionMessage);
		$("#pdp_excludedMessage a").click(showExcludedBubble);
		$("#pdp_excludedMessage a").mouseout(hideExcludedBubble);
	}
	else {
		$("#pdp_excludedMessage").html("");
	}
	checkHotSkuLimit(sku);
	showXforY(style);
}

function displayStyleAttributes(sku) {
	var style = styles[sku];
	var html = "";
	if (typeof(inStoreAvailabilityEnabled) != "undefined" && inStoreAvailabilityEnabled == true) {
		$("#pdp_inStoreAvailability").hide();
	}
	if (style[idx_styleAttributes]['CHANNEL_AVAIL_ICON'] == 'WEB_ONLY') {
		html = '<img src="' + onlineOnlyIcon + '" alt="' + onlineOnlyAlt + '" />';
	}
	else if (style[idx_styleAttributes]['CHANNEL_AVAIL_ICON'] != null) {
		html = '<img src="' + alsoInStoreIcon + '" alt="' + alsoInStoreAlt + '" />';
		if (typeof(inStoreAvailabilityEnabled) != "undefined" && inStoreAvailabilityEnabled == true) {
			$("#pdp_inStoreAvailability").show();
			$("#pdp_inStoreAvailability a").attr("href", "javascript:lookupStores()");
			$("#pdp_inStoreAvailability a").attr("target", "_self");
			$("#pdp_inStoreAvailability a").attr("onMouseOut", "hideBubble()");
		}
	}
	$("#pdp_onlineOnly a").html(html);
	if (html != "") {
		$("#pdp_onlineOnly").css("margin-right", "16px");
	}

	var striperhtml = "";
	if (style[idx_styleAttributes]['IS_STRIPERPEDIA'] == true) {
		striperhtml = '<a href="/striperpedia/shoe/' + sku +'/'+ $("#model_name").val() +'" target="_blank"><img src="' + striperpediaImgBanner + '" alt="go to striperpedia"></a>';
	}
	$("#pdp_striperpedia").html(striperhtml);

	if (typeof(ShipToStoreEnabled) != "undefined" && ShipToStoreEnabled == true && style[idx_styleAttributes]['ELIGIBLE_SHIPTOSTORE'] == true) {
		var shipToStoreHTML = "";
		shipToStoreHTML = '<img src="' + shopToStoreIcon + '" alt="' + shopToStoreAlt + '" />';
		$("#pdp_shipToStore a").html(shipToStoreHTML);
		if (shipToStoreHTML != "") {
			$("#pdp_shipToStore").css("margin-right", "6px");
		}
	}
	else {
		$("#pdp_shipToStore a").html();
	}

        if (typeof(altShippingEnabled) != "undefined" && altShippingEnabled) {
              $("#alt_shipping").show();
	}

	if (typeof(FreeStandardShippingEnabled) != "undefined" && FreeStandardShippingEnabled == true && style[idx_styleAttributes]['FREE_STANDARD_SHIPPING'] == true) {
		$("#pdp_freeShipping").html(freeStandardShippingMessage);
		if (style[idx_excluded]) {
			$("#pdp_freeShipping").addClass('pdp_freeShipping_padding');
		}
		$("#pdp_freeShipping a").click(showFreeShippingBubble);
		$("#pdp_freeShipping a").mouseout(hideFreeShippingBubble);
	}
	else {
		$("#pdp_freeShipping").html("");
		if (style[idx_excluded]) {
		$("#pdp_freeShipping").removeClass('pdp_freeShipping_padding');
		}
	}
	/*if (typeof(FreeStandardShippingEnabled) != "undefined" && FreeStandardShippingEnabled == true && style[idx_styleAttributes]['FREE_STANDARD_SHIPPING'] == true) {
		var freeShippingHTML = "";
		freeShippingHTML = '<img src="' + freeStandardShippingIcon + '" alt="' + freeStandardShippingAlt + '" />';
		$("#pdp_freeShipping a").html(freeShippingHTML);
	}
	else {
		$("#pdp_freeShipping a").html();
	}*/
	
	var exclusiveMsg = "";
	if (style[idx_styleAttributes]['IS_NEW_ARRIVAL']) {
		exclusiveMsg += "New! ";
	}
	if (style[idx_styleAttributes]['IS_CCS_EXCLUSIVE']) {
		exclusiveMsg += "CCS Exclusive!";
	}
	$("#pdp_exclusiveMsg").html(exclusiveMsg);
	
	// update facebook like class
	$(".fb_edge_widget_with_comment").css("z-index", "888");
}

function showExcludedBubble() {
	var excludedDetail = 'The dollar value of this item will count toward meeting a required minimum purchase total necessary to receive a discount, but the price of this item itself will not be discounted. Only other eligible items in your cart will be discounted. (Example: You can purchase this product to reach the order threshold to receive a discount, but you will only receive the discount on other eligible items in your cart.)';

	var offset = $(this).offset();
	var left = offset.left - 70;
	var top = offset.top - 190;
	
	$(this).before('<div id="pdp_excluded_bubble"><p style="margin: 5px 10px;"></p></div>');
	
	$("#pdp_excluded_bubble").css("left", left);
	$("#pdp_excluded_bubble").css("top", top);
	$("#pdp_excluded_bubble").css("opacity", 0.9);
	$("#pdp_excluded_bubble p").html(excludedDetail);
	$("#pdp_excluded_bubble").show();
}

function hideExcludedBubble() {
	$("#pdp_excluded_bubble").fadeOut(function() {
		$("#pdp_excluded_bubble").remove();
	});
}

function showFreeShippingBubble() {
	var freeShippingDetail = FreeStandardShippingDetails;

	var offset = $(this).offset();
	var left = offset.left - 70;
	var top = offset.top - 285;
	
	$(this).before('<div id="pdp_freeShipping_bubble"><p style="margin: 20px 10px;"></p></div>');
	
	$("#pdp_freeShipping_bubble").css("left", left+'px');
	$("#pdp_freeShipping_bubble").css("top", top+'px');
	$("#pdp_freeShipping_bubble").css("opacity", 0.9);
	$("#pdp_freeShipping_bubble p").html(freeShippingDetail);
	$("#pdp_freeShipping_bubble").show();
}

function hideFreeShippingBubble() {
	$("#pdp_freeShipping_bubble").fadeOut(function() {
		$("#pdp_freeShipping_bubble").remove();
	});
}

function revertStyle() {
	hoverStyle($("#pdp_selectedSKU").val());
	highlightSelectedSize();
	
}

function selectStyle(sku) {	
	$("#pdp_selectedSKU").val(sku);
	$("#pdp_zoomImageSKU").val(sku);
	var hasXYPromo = (styles[sku][idx_xforyimage] != "") ? "true" : "false";
	$("#pdp_hasXYPromo").val(hasXYPromo);
	
	$("#pdp_styles a").removeClass("selected");
	$("#pdp_style_" + sku).addClass("selected");
	highlightSelectedSize();
	// select size if there's only 1 available
	if ($("#pdp_sizes li a.available").size() == 1) {
		$("#pdp_sizes li a.available").each(selectSize);
	}	
	loadSimilarStyles(sku);
	updateHash();
	initializeHotLaunchCounter();
	
	// load tab contents
	loadTabContents(sku);

	toggleScene7Zoom(sku);

	if (typeof(alternateProductImagesEnabled) != "undefined" && alternateProductImagesEnabled == true) {
		showAlternateImages(sku);
	}
	
	var style = styles[sku];
	if (style[idx_isscene7]) {
		var scene7imageObj = new Image();
		scene7imageObj.src = getScene7ZoomURL(sku);
	}
	// coremetrics tagging
	var ModelName = $("#pdp_info h1").html();
	var cm_OtherStylePageID = "PDP: Other Styles: " + ModelName + ": " + sku;

	cmCreateOtherStyleProductviewTag(sku, ModelName, cm_CategoryID, microsite);
	
	if (typeof(thecurrentsku) != "undefined") {
		//update sku for BazaarVoice URLs
		updateBVReturnURL(sku);
	}
	highlightSelectedSize();
	//defaultavailability(sku);
	setBVQASessionParams();	
	
	// update facebook like button iframe
	if (typeof(fb_reload_like_iframe) != "undefined") {
		fb_reload_like_iframe();
	}

 	displayVideoButton(sku);
	displayBatGuarantee(sku);
}

function highlightAvailableSizesForStyle(style) {
	var availableSizes = new Object();

	for (i = 0; i < style[idx_sizes].length; i++) {
		var size = style[idx_sizes][i][sizeString_index].trim();
		availableSizes[size] = true;
	}
	
	var selectedSize = $("#pdp_selectedSize").val();
	$("#pdp_sizes ul li a").removeClass("available");
	$("#pdp_sizes ul li a").removeClass("selected");
	$("#pdp_sizes ul li a").each(function(i) {
		var sizeHTML = $(this).html();
		for (i = 0; i < style[idx_sizes].length; i++) {
			var size = style[idx_sizes][i][sizeString_index].trim();
			if (size == sizeHTML) { 
				$(this).addClass("available");
				if (sizeHTML == selectedSize) {
					$(this).each(selectSize);
				}
			}
		}
	});
}

function loadSimilarStyles(sku) {
  if (document.getElementById('pdp_similarStyles')){
	$("#pdp_similarStyles").fadeOut(function() {
		$.get(similarStylesTemplatePath, {sku: sku, microsite: microsite}, function(data, textStatus) {
			$("#pdp_similarStyles").html(data);
			$("#pdp_similarStyles").fadeIn();
			initializeQuickview();
		});
	});
  }
}

function showXforY(style) {
	if (style[idx_xforyimage] != "") {
		if(xforyURL.substring(xforyURL.length-5) == "sku--")
		{
			$("#pdp_xfory a").attr("href", xforyURL + style.SKU);
		}
		else if(xforyURL.substring(xforyURL.length-5) == "sku:/")
		{
			var newxforyURL = xforyURL.replace("sku:/", "sku:" + style.SKU + "/");
			$("#pdp_xfory a").attr("href", newxforyURL);
		}
		else
		{	var newxforyURL = xforyURL.replace(defaultsku, style.SKU);
			$("#pdp_xfory a").attr("href", newxforyURL);
		}
		$("#pdp_xfory img").attr("src", xforyImagePath + style[idx_xforyimage]);
		$("#pdp_xfory").css("display", "block");
	}
	else {
		$("#pdp_xfory a").attr("href", "");
		$("#pdp_xfory img").attr("src", pixelImg);
		$("#pdp_xfory").css("display", "none");		
	}
}

function highlightNoSizeStyle(sku) {
	var style = styles[sku];
	if (style[idx_sizes].length == 1 && style[idx_sizes][0][sizeString_index].trim() == "") {
		// set id so that hoverSize will know that it's for no size item
		 $("<a id='sku_" + sku + "'></a>").each(hoverSize);
	}	
}

function displayDefaultPriceForStyle(sku) {
	var style = styles[sku];
	displayPrices(style[idx_sale_price], style[idx_list_price]);
}

function displayThisShoeRunsIcon(sku) {
	var style = styles[sku];
	var icon = style[idx_icon];
	var iconTag = "";
	
	if (icon != "") {
		iconTag = '<img src="' + iconFlagPath + icon + '" alt="' + getThisShoeRunsAltTxt(icon) + '" />';
	}
	$("#pdp_thisShoeRunIcon").html(iconTag);
}

function getThisShoeRunsAltTxt(icon) {
	var text = "";
	
	switch(icon) {
		case "1big.gif":
			text = "1 Size Big";
			break;
		case "1small.gif":
			text = "1 Size Small";
			break;
		case "2big.gif":
			text = "2 Size Big";
			break;
        case "2small.gif":
            text = "2 Sizes Small";
			break;
        case "05big.gif":
            text = "0.5 Size Big";
			break;
        case "05small.gif":
            text = "0.5 Size Small";
			break;
        case "15big.gif":
            text = "1.5 Size Big";
			break;
        case "15small.gif":
            text = "1.5 Size Small";
			break;
        case "truesize.gif":
            text = "True To Size";
			break;
	}
	
	return "This Shoe Runs " + text;
}

function displayTierPricing(sku) {
	var style = styles[sku];
	var tierPrices = style[idx_tierPricing];
	
	if (tierPrices.length > 0) {
		var html = "<ul>";
		for (i = 0; i < tierPrices.length; i++) {
			html += '<li>' + tierPrices[i] + '</li>';
		}
		html += "</ul>";
		
		$("#pdp_priceTier").html(html);
	}
	else {
		$("#pdp_priceTier").html("");
	}
}


/******************************
	size functions
******************************/

function hoverSize() {
	var selectedSKU = $("#pdp_selectedSKU").val();
	if (this.id) {
		selectedSKU = _getIDFromString(this.id); // display style under the mouse
	}
	
	var selectedStyle = styles[selectedSKU];
	
	if (this.tagName != null) {
		var size = $(this).html();
		$("#pdp_selectedSizeDisplay").html(size);
		for (i = 0; i < selectedStyle[idx_sizes].length; i++) {
			if (selectedStyle[idx_sizes][i][sizeString_index].trim() == size) {
				changeAvailability(selectedStyle[idx_sizes][i][availability_index]);
				sale = selectedStyle[idx_sizes][i][pr_sale_index];
				list = selectedStyle[idx_sizes][i][pr_list_index];
				displayPrices(sale, list);
				return;
			}
		}
		
		changeAvailability("unavailable");
		return;
	}
	$("#pdp_selectedSizeDisplay").html("none");
	$("#pdp_sizeAvailable").html("(Select a size)");
	displayDefaultPriceForStyle(selectedSKU);
}
function changeAvailability(msg){
	if (msg == "") {
		$("#pdp_sizeAvailable").html("In Stock");
		$("#pdp_shipToStore").show();
	}
	else if (msg == "unavailable") {
		$("#pdp_sizeAvailable").html("<span style='color: red'>Sold Out - Please Choose Another Style</span>");
		$("#pdp_shipToStore").hide();
	}
	else {
		$("#pdp_sizeAvailable").html("<span style='color: red'>Back-ordered, Expected to Ship " + msg + "</span>");
		$("#pdp_shipToStore").show();
	}
}

function revertSize() {
	var sizeTag = _anchorTagForSize($("#pdp_selectedSize").val());
	if (sizeTag != null)
		sizeTag.each(hoverSize);
	else
		hoverSize();
}

function selectSize() {
	var sizeObj = $(this);
	// select size only when available
	if (sizeObj.hasClass("available")) {
		$("#pdp_selectedSize").val(sizeObj.html());
		$("#pdp_sizes li a").removeClass("selected");
		sizeObj.addClass("selected");
		updateHash();
		OpenShopTogetherToolBar('size');
		removeWishListRelated();
	}
}

function selectGripTape(){
	removeWishListRelated();
}

function removeWishListRelated(){
	if ($("#WISHLIST_ID").length){
		if ($("#pdp_selectedSize").val() != defaultSize.trim() || $("#wlgriptape").val() != $("#pdp_griptape").val()){
			$("#product_form input[name='WISHLIST_ITEM_ID']").remove();
			$("#product_form input[name='WISHLIST_ID']").remove();
		}
	}/*else if (wishlistID != 0){		// This section is to reconnect wishlist to the item.
		var wlstring = '<input type="Hidden" name="WISHLIST_ID" id="WISHLIST_ID" value="' + wishlistID + '"><input type="Hidden" name="WISHLIST_ITEM_ID" id="WISHLIST_ITEM_ID" value="' + wlitemID + '">';
		if ($("#pdp_selectedSize").val() == defaultSize.trim()){
			if ($("#wlgriptape").length){
				if ($("#wlgriptape").val() == $("#pdp_griptape").val()){
					$('#product_form').append(wlstring);
				}
			}else{
				$('#product_form').append(wlstring);
			}
		}
	}*/
}

function highlightSelectedSize() {
	var selectedSize = $("#pdp_selectedSize").val();
	var selectedSizeTag = _anchorTagForSize(selectedSize);
	if (selectedSize != "" 
		&& selectedSizeTag != null
		&& selectedSizeTag.hasClass("available")) {
		selectedSizeTag.addClass("selected");
		selectedSizeTag.each(hoverSize); // this is to select or reset availability and price	
	}
	else {
		$("#pdp_selectedSize").val(' ');
		hoverSize();			
		var selectedSKU = $("#pdp_selectedSKU").val();		
		highlightNoSizeStyle(selectedSKU);	
	}
}

function displayPrices(sale, list) {
	var priceHTML = "";
	
	if (sale == 0 && list == 0) {
		priceHTML = "CALL";
	}
	else if (sale == 0) {
		priceHTML = "$" + list.toFixed(2);
	}
	else if (list > sale && (list - sale) / list >= sale_percentage) {
		priceHTML = '<span class="oldPrice">$' + list.toFixed(2) + '</span><br />' 
					+ '<span class="salePrice"><strong>Now:</strong> $' + sale.toFixed(2) + '</span>';
	}
	else {
		priceHTML = "$" + sale.toFixed(2);
	}
	
	$("#pdp_price .current_price").html(priceHTML);	
}

/******************************
	add to cart functions
******************************/

function validateProduct() {
	var size = $("#pdp_selectedSize").val();
	var quantity = $("#pdp_quantity").val();
	var sku = $("#pdp_selectedSKU").val();
	var style = styles[sku];
	var errMsg = "";
	var errCount = 0;
	if (checkHotLaunchItem(sku) || !style[idx_available]) {
		errMsg = "<li>This item is currently unavailable for purchase.</li>";
		return errMsg;
	}
	
	if (!noSize && size.trim() == "") {
		errMsg += "<li>Please select a size.</li>";
		errCount++; 
	}
	if (/^\d+$/.test(quantity) == false || quantity <= 0 || quantity >= 256) {
		errMsg += "<li>Please enter a valid quantity.</li>";
		errCount++;
	}
	if (errCount < 2 && typeof hasgriptape != 'undefined' && hasgriptape == true) {
		var griptape = $("#pdp_griptape").val();
		if (griptape.trim() == "") {
			errMsg += "<li>Please select a grip tape.</li>";
			errCount++;
		}
	}
	
	if (checkHotSkuQtyOverMax(sku, quantity)) {
		errMsg = "<li>Order quantity is limited on this product to " + hot_launch_max_per_order + " per customer.</li>";
		return errMsg;
	}
	
	return errMsg;
}

function checkHotLaunchItem(sku) {
	if (timeToHL < 0) return false;
	if (listFind(shoelaunch_skuList, sku)) return true;

	return false;
}

function checkHotSkuQtyOverMax(sku, quantity) {

	if ( listFind(hot_skus, sku) && hot_launch_max_per_order > 0 && checkHowManyHLSKU(sku) + parseInt(quantity) > hot_launch_max_per_order ){
		return true;
	}
	return false;
}

function checkHowManyHLSKU(sku) {
	// sku,qty|sku,qty
	var hlincart = readCookie("HLCOUNT");
	if (hlincart != null) {
		var hlitems = decodeURIComponent(hlincart).split( "|" );
		for (var e = 0; e < hlitems.length; e++) {
			var hlitem = hlitems[ e ].split(":");
			if (hlitem[ 0 ] == sku) { 
				return parseInt(hlitem[ 1 ]);
			}
		}
	}
	return 0
}

function checkHotSkuLimit(sku) {
	if (listFind(hot_skus, sku)) {
		if (hot_launch_max_per_order > 0 && hot_launch_max_per_order - checkHowManyHLSKU(sku) == 0) {
			$("#pdp_addToCart").hide();
			$("#pdp_timer").hide();
			$("#pdp_hotsku_max").show();
		}
	}
}


function addToCart() {
	var errMsg = validateProduct();
	
	if (errMsg != "") return;
	var ILATC_EnableVal = readCookie("ILATC_Enable");
	if (ILATC_EnableVal != null)
		inlineAddToCartEnabled = false;

	if (!inlineAddToCartEnabled || isAJAXEnabled() == false) {
		// disable the submit button
		disableToCartButton();
		// submit the form
		$("#product_form input[name='inlineAddToCart']").remove();
		document.getElementById('product_form').submit();
		return;
	}

	var personalizationCheckBox = false;
	if (document.product_form.pdp_personalization != null)
	{ 
		personalizationCheckBox =   document.product_form.pdp_personalization.checked;
	}
	
	var protectivePackagingCheckBox = false;
	if (document.product_form.protective_packaging != null)
	{
		protectivePackagingCheckBox = document.product_form.protective_packaging.checked;
	}
	
	if (inlinePopUpOpened != 1)
	{
		// Inline cart add - if only the product doesn't have x for y and personalization and protective packaging are 'off'.
		if ($("#pdp_hasXYPromo").val() == "false" && personalizationCheckBox == false && protectivePackagingCheckBox == false) { 
			miniAddToCart.openMiniAddToCart("product_form");
			return;
		}
	}

	if (inlinePopUpOpened == 0) {	
		// disable the submit button
		disableToCartButton();
		// submit the form	
		document.getElementById('product_form').submit(); 
	}
}

function disableToCartButton() {
	$("#pdp_addToCartButton").hide();
	$("#pdp_addToCartButtonProcessing").show();	
}

function enableToCartButton() {
	$("#pdp_addToCartButton").show();
	$("#pdp_addToCartButtonProcessing").hide();	
}

function closeCartAdd(){
	var addToCartImg = $("#addToCartLink img");
	var addToCartImgOffset = addToCartImg.offset();
	inlinePopUpOpened = 0;
	$("#tellafriend_sent").remove();
	$("#cartAdd_box").animate({height: addToCartImg.height(), width: addToCartImg.width(), left: addToCartImgOffset.left, top: addToCartImgOffset.top}
		,	function () {
			if ($.browser.msie && $.browser.version < 7)
				$("select").show();
			$("#overlayBGinlineATC").remove();
			$("#cartAdd_box").remove();
		}
	);
}


function showBubble(thisObj, adjustLeft) {
	var errMsg = validateProduct();
	
	if (errMsg != "") {
		var offset = $("img", thisObj).offset();
		if (adjustLeft) {
			var left = offset.left - adjustLeft;
		} else {
			var left = offset.left - 20;
		}
		var top = offset.top - 72;
		
		$("#pdp_addtocart_bubble").css("left", left);
		$("#pdp_addtocart_bubble").css("top", top);
		$("#pdp_addtocart_bubble").css("opacity", 0.9);
		$("#pdp_addtocart_bubble ul").html(errMsg);
		$("#pdp_addtocart_bubble").show();
	}
}

function showBubbleForID(id) {
	var errMsg = validateProduct();
	
	if (errMsg != "") {
		var thisObj = $("#" + id);
		var offset = $("img", thisObj).offset();
		var left = offset.left - 20;
		var top = offset.top - 72;
		
		$("#pdp_addtocart_bubble").css("left", left);
		$("#pdp_addtocart_bubble").css("top", top);
		$("#pdp_addtocart_bubble").css("opacity", 0.9);
		$("#pdp_addtocart_bubble ul").html(errMsg);
		$("#pdp_addtocart_bubble").show();
	}
}

function showCustomBubble (id, message, adjustLeft) {
	if (message != "") {
		var thisObj = $("#" + id);
		var offset = $("img", thisObj).offset();
		if (adjustLeft) {
			var left = offset.left - adjustLeft;
		} else {
			var left = offset.left - 20;
		}
		var top = offset.top - 72;
		
		$("#pdp_addtocart_bubble").css("left", left);
		$("#pdp_addtocart_bubble").css("top", top);
		$("#pdp_addtocart_bubble").css("opacity", 0.9);
		$("#pdp_addtocart_bubble ul").html(message);
		$("#pdp_addtocart_bubble").show();
	}
}

function hideBubble() {
	$("#pdp_addtocart_bubble").fadeOut(function() {
		killHotLaunchTimer();
		$("#pdp_addtocart_bubble ul").html("");	
	});
}

var timerID = null;



function initializeHotLaunchCounter(sku) {
	$("#pdp_addToCart").hide();
	$("#pdp_timer").hide();
	$("#pdp_hotsku_max").hide();
	killHotLaunchTimer();
	
	if (!sku)
		sku = $("#pdp_selectedSKU").val();
	if (checkHotLaunchItem(sku)) {
		startHotLaunchTimer();
	}
	else {
		$("#pdp_addToCart").show();
	}
}

function startHotLaunchTimer() {
	timeToHL -= 1;
	
	if (timeToHL < 0) {
		$("#pdp_addToCart").show();
		$("#pdp_timer").hide();
		$("#pdp_hotsku_max").hide();
		killHotLaunchTimer();
		return;
	}
	
	$("#pdp_addToCart").hide();
	$("#pdp_hotsku_max").hide();
	$("#pdp_timer").show();
	
	var sec = timeToHL % 60;
	var min = parseInt(timeToHL / 60) % 60;
	var hour = parseInt(timeToHL / (60 * 60));
	
	$("#pdp_timer div").html(hour + " hours " + min + " min " + sec + " sec");
	timerID = setTimeout("startHotLaunchTimer()", 1000);
}

function killHotLaunchTimer() {
	clearTimeout(timerID);
}


/******************************
	image functions
******************************/

var currentZoomImageSKU = "";

function zoomImage() {
	
	currentZoomImageSKU = $("#pdp_selectedSKU").val();
	
	$("#zoomImageDiv").remove();
	$("#zoomBackground").remove();
	
	$.get(zoomTemplatePath, {sku: currentZoomImageSKU}, function(data) {
		$("#pdp_image").prepend(data);
		$("#zoomImageDiv").hide();
		$("#zoomBackground").hide();
		$("#zoomBackground").css("opacity", "0.9");
		$("#zoomBackground").fadeIn();
		$("#zoomImageDiv").fadeIn();
		// hide select tag on ie6 because they will appear above zoom layer
		if ($.browser.msie && $.browser.version < 7) $("select").hide();			
	});
}

function zoomCustomProdImage() {
	currentZoomImageSKU = $("#pdp_selectedSKU").val();
	
	$("#zoomImageDiv").remove();
	$("#zoomBackground").remove();
	
	$.get(zoomTemplatePath, {sku: currentZoomImageSKU}, function(data) {
		$("#pdp_customprod_image").prepend(data);
		$("#zoomImageDiv").hide();
		$("#zoomBackground").hide();
		$("#zoomBackground").css("opacity", "0.9");
		$("#zoomBackground").fadeIn();
		$("#zoomImageDiv").fadeIn();
		// hide select tag on ie6 because they will appear above zoom layer
		if ($.browser.msie && $.browser.version < 7) $("select").hide();			
	});	
}

function closeZoom() {
	$("#zoomImageDiv").remove();
	$("#zoomBackground").remove();
	
	try {
		removeZoom();
	}
	catch (e) {}
	
	// show select tag on ie6
	if ($.browser.msie && $.browser.version < 7) $("select").show();
}

function swapZoomImage(sourceSKU) {
	var currentSKU = currentZoomImageSKU;
	var currentCartImagePath = getCartImagePathForSKU(currentZoomImageSKU);
	
	var source = $("#thumb_" + sourceSKU);
	
	var href = 'javascript:swapZoomImage("' + currentSKU + '")';
	var id = "thumb_" + currentSKU;
	source.attr("href", href).attr("id", id);
	source.children("img").attr("src", currentCartImagePath);
	
	currentZoomImageSKU = sourceSKU;
	$("#zoomImage").load(zoomProductTemplatePath, { sku: sourceSKU }, function() {
		$("#zoomImage img").hide();
		$("#zoomImage img").fadeIn();
	});
}

activeAltImgForSku = new Object();
function replaceImageForSKU(sku) {

	if(activeAltImgForSku[sku]) {
		var imagePath = activeAltImgForSku[sku]; 
	} else {
		var imagePath = getImageForSKU(sku); 
	}
	$("#productImage img").attr("src", imagePath);
	//$("#productImage").attr("href", zoomPath);
}

function getImageForSKU(sku) {
	var style = styles[sku];
	if (inline_zoom_enabled && style[idx_isscene7])
		return getScene7URL(sku);
	else 
		return getWideImagePathForSKU(sku);
}

function showAlternateImages (sku) {

	$("#pdp_alternateViews").html('');

	var style = styles[sku];
	if (!style[idx_isscene7]) {
		$("#pdp_viewLargerImage").show();
		$("#pdp_viewFullScreen").hide();
		return;
	}

	//$(".zoomText").hide();
	var company = "EB";
	$("#pdp_viewLargerImage").hide();
	$("#pdp_viewFullScreen").show();
	var imageSet = new Object();
	loadImageSet(company + '/' + sku);
}

function toggleScene7Zoom(sku) {
	$(".zoomText").show();
	if (inline_zoom_enabled) {
		var style = styles[sku];
		
		if (style[idx_isscene7]) 
			enableZoom();
		else 
			disableZoom();
	}
}

function getScene7URL(sku) {
	var width = 300;
	var height = 300;
	var imageURL = scene7URL;
	
	imageURL = imageURL.replace("<SKU>", sku);
	imageURL = imageURL.replace("<WIDTH>", width);
	imageURL = imageURL.replace("<HEIGHT>", height);
	return imageURL;
}

function getScene7ZoomURL(sku) {
	var width = 2000;
	var height = 2000;
	var imageURL = scene7URL;
	
	imageURL = imageURL.replace("<SKU>", sku);
	imageURL = imageURL.replace("<WIDTH>", width);
	imageURL = imageURL.replace("<HEIGHT>", height);
	imageURL = imageURL + "&qlt=60"
	return imageURL;
}

function selectedZoomImageObject() {
	var imageObject = new Image();
	var returnObject = new Object();
	//var sku = $("#pdp_selectedSKU").val();
	var sku = $("#pdp_zoomImageSKU").val();
	
	imageObject.src = getScene7ZoomURL(sku);
	returnObject.url = getScene7ZoomURL(sku);
	returnObject.width = imageObject.width;
	returnObject.height = imageObject.height;
	
	return returnObject;
}

/******************************
	private/utility functions
******************************/

function openPersonalizeWindow() {
	var currentSKU = $("#pdp_selectedSKU").val();
	var url = personalizePopUpPath + "&sku=" + currentSKU;
	openPopUpWindow(url, 550, 560);
}

function _anchorTagForSize(size) {
	var returnObj = null;
	$("#pdp_sizes li a").each(function(i) {
		if ($(this).html() == size) {
			returnObj = $(this);
		}
	});
	return returnObj;
}

/* modified version of cmCreateProductviewTag from cmdatataguitls.js to support other style product view */
function cmCreateOtherStyleProductviewTag(productID, productName, categoryID, microsite) {

	var cm = new _cm("tid", "5", "vn2", "e4.0");

	if (productName == null) 
		productName = "";

	if (microsite != null && microsite != "")
		microsite += ": ";
	else if (readCookie('COBRANDED') != null) {
		var tempcobrand = unescape(readCookie('COBRANDED'));
 	 	var tempcobrandstr = tempcobrand.split('|');
		microsite = tempcobrandstr[1];
		microsite += ": ";	
	}
	else
		microsite = "";

	// if available, override the referrer with the frameset referrer
	if (parent.cm_ref != null) {
		cm.rf = parent.cm_ref;
		parent.cm_ref = document.URL;
	}

	// if parent had mmc variables and this is the first pageview, add mmc to this url
	if(parent.cm_set_mmc) {
		cm.ul = document.location.href + 
				((document.location.href.indexOf("?") < 0) ? "?" : "&") + 
				parent.cm_mmc_params; 
		parent.cm_ref = cm.ul;
		parent.cm_set_mmc = false;
	}

	cm.pr = productID;
	cm.pm = productName;
	cm.cg = categoryID;

	cm.pc = "Y";
	cm.pi = microsite + "PDP: Other Styles: " + productName + ": " + productID;
	if (typeof(bv_RR_enabled) != "undefined" && bv_RR_enabled == true) {
		bvattribute=$("#bvRRAttributes").val();
		if (bvattribute.length > 0) {
			var attr_array = bvattribute.split("-_-");
			cm.pr_a1 = attr_array[0];
			cm.pr_a2 = attr_array[1];
			cm.pr_a3 = attr_array[2];
		}
	}
	cmCheckCMEM();
	if(typeof(cmGomezKeynoteFlag) == "undefined" || !cmGomezKeynoteFlag)
		cm.writeImg();
}

function addtocomplete() {
	var deck = $("#pdp_selectedSKU").val();
	var decksize = $.trim($("#pdp_selectedSize").val());
	var griptape = $("#pdp_griptape").val();
	if (griptape != "") {
		var index = griptape.indexOf(",");
		griptape = griptape.substring(0,index);
	}
	// for validation, don't require a griptape check
	var errMsg = validateProduct();
	if (errMsg != "") return;
	location = skateboardbuilderPath + '#deck=' + deck + '_' + decksize + '&trucks=&wheels=&parts=&bearings=&griptape=' + griptape + '&hardware=&risers=';
}

function cmSetProductSizingPageTag() {
	var model_name = $("#model_name").val();
	var sku = $("#pdp_selectedSKU").val();
	var cm_CategoryID = "PDP: Sizing Tab";
	var cm_PageID = "PDP: Sizing Tab: " + model_name +": " + sku;
	cmCreatePageviewTag(cm_PageID, cm_CategoryID, null, null);
}
function cmSetVideoConversionEventTag(source) {
	if (source == "viewvideos_btn") {
		//registerConversionEvent('PDP Videos','View Videos Button');
		cmCreateConversionEventTag("View Videos Button", 1, "PDP Videos", 0);
		cmCreateConversionEventTag("View Videos Button", 2, "PDP Videos", 0);
	} else if (source =="videotab") {
		//registerConversionEvent('PDP Videos','View Videos Tab');
		cmCreateConversionEventTag("View Videos Tab", 1, "PDP Videos", 0);
		cmCreateConversionEventTag("View Videos Tab", 2, "PDP Videos", 0);
	}
	
}


function updateBVReturnURL(selectedsku) {
	var bv_customerRatings = $("#BVCustomerRatings").html();
	var bv_reviews = $("#BVReviewsContainer").html();
	var bv_secondaryCustomerRatings = $("#BVSecondaryCustomerRatings").html();
	var regex = "/"+thecurrentsku+"/g";
	if (bv_customerRatings != null) {
		if (bv_customerRatings.trim() != "") {
			bv_customerRatings = bv_customerRatings.replace(eval(regex), selectedsku);
			$("#BVCustomerRatings").html(bv_customerRatings);		
		}
	}
	if (bv_reviews != null) {
		if (bv_reviews.trim() != "") {
			bv_reviews = bv_reviews.replace(eval(regex), selectedsku);
			$("#BVReviewsContainer").html(bv_reviews);		
		}
	}
	if (bv_secondaryCustomerRatings != null) {
		if (bv_secondaryCustomerRatings.trim() != "") {
			bv_secondaryCustomerRatings = bv_secondaryCustomerRatings.replace(eval(regex), selectedsku);
			$("#BVSecondaryCustomerRatings").html(bv_secondaryCustomerRatings);		
		}
	}
	thecurrentsku = selectedsku;
}

function defaultavailability(sku) {
	var selectedStyle = styles[sku];
	var available = "";
	var countinstock = 0;
	var countnotavailable = 0;
	for (i = 0; i < selectedStyle[idx_sizes].length; i++) {
		available = selectedStyle[idx_sizes][i][availability_index];
		if (available == "") {
			countinstock += 1;
		}
		if (available != "") {
			countnotavailable += 1;
		}
	}
	if (countinstock > 0 && countnotavailable > 0) {
		$("#pdp_sizeAvailable").html("(Select a size)");
	}
}


// The following function is to swap style on PDP for ShopTogether.

function OpenShopTogetherToolBar (theID){
	if ($("#pdp_ShopTogether").length > 0){
		var newSelSku = $('#productSKU').html();
		if (newSelSku != curDispSku || (theID && theID == "size")){
			with (ShopTogether){
				id = newSelSku;
				URL = URL.replace(curDispSku, newSelSku);
				name = curDispName + " - " + $('#productAttributes').html();
				description = name + curDispDes;
				imageThumbnailURL = imageThumbnailURL.replace(curDispSku, newSelSku);
				imageLargeURL = imageLargeURL.replace(curDispSku, newSelSku);
				changeColorAndLink(imageThumbnailURL, URL);
			}
			curDispSku = newSelSku;
		}
		if (theID && theID == "pdp_ShopTogether"){
			ShopTogether.openToolbar();
		}
	}
}

function setBVQASessionParams() {
	var sku = $("#pdp_selectedSKU").val();
	var size = $("#pdp_selectedSize").val();
	var bv_QAParams = "sku=" + sku;
	if (size.trim() != '') {
		bv_QAParams += "&size=" + size;
	}
	var bv_QASessionParams = $("#BVQASessionParams").html();
	if (bv_QASessionParams != null) {
		$("#BVQASessionParams").html(bv_QAParams);
	}
}

function updateMyBuysData (){
	if ($("#mybuyszone1").length > 0){
		var newSelSku = $('#productSKU').html();
		mybuys.setPageType("PRODUCT_DETAILS");
		mybuys.set("productid", newSelSku);
		mybuys.initPage();
	}
}

function cmConversionEventViewLargerImage () {
	cmCreateConversionEventTag("View Larger", 1, "PDP Images", 0);
	cmCreateConversionEventTag("View Larger", 2, "PDP Images", 0);
}

function cmConversionEventSizeSelection () {
	cmCreateConversionEventTag("Size Selection", 1, "PDP Sizing", 0);
	cmCreateConversionEventTag("Size Selection", 2, "PDP Sizing", 0);
}

