// 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;

$(document).ready(function() {
	var sku = $("#pdp_selectedSKU").val();
	//reset the form for firefox
	document.getElementById("product_form").reset();
	
	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));
		},
		revertStyle
	);
	$("#pdp_styles a").click(function() {
		selectStyle(_getIDFromString(this.id));
		OpenShopTogetherToolBar();
	});
	
	$("#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 = style[idx_sizes][0][sizeString_index].trim();
		if (size != "")
			$("#pdp_selectedSize").val(size);
	}
	
	if (defaultSize.trim() != "") {
		$("#pdp_selectedSize").val(defaultSize);
	}
	
	selectHashValues();

	toggleScene7Zoom(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();

	var shadowboxOptions = {
		loadingImage: shadowboxPath + 'loading.gif', 
		overlayBgImage: shadowboxPath + 'overlay-85.png',
		flvPlayer: shadowboxPath + 'flvplayer.swf'
	}
	Shadowbox.init(shadowboxOptions);
	
	if (inlineAddToCartEnabled) {
		$(window).resize(resizeOverlay);
	}
	
	// select size if there's only 1 available
	/*
	if ($("#pdp_sizes li a.available").size() == 1) {
		$("#pdp_sizes li a.available").each(selectSize);
	}
	*/
	
	//defaultavailability(sku);
	setBVQASessionParams();

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

function resizeOverlay() {
	var documentWidth = $(document).width();
	$("#overlayBG").css("width", documentWidth);
	var bodyWidth = $("body").width();
	var leftOffset = (bodyWidth - $("#cartAdd_box").width()) / 2;
	var offsetTop = getViewpointTop() + ((getViewpointHeight() - $("#cartAdd_box").height()) / 2);
	$("#cartAdd_box").animate({left: leftOffset, top: offsetTop});	
}

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

function viewTab(tab, scroll) {
	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 (scroll) {
		var offset = tabBar.offset();
		$("html,body").animate({scrollTop: offset.top - 45});
	}
}

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

/* 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 key = hashItem.split("=")[0];
			var value = hashItem.split("=")[1];
			
			if (key.trim() == "sku") {
				selectedSKU = value.trim();
			}
			else if (key.trim() == "size") {
				selectedSize = value.trim();
			}
		}
		
		if (selectedSKU.trim() != '' && $("#pdp_selectedSKU").val() != selectedSKU) {
			$("#pdp_selectedSKU").val(selectedSKU);
		}
		if (selectedSize.trim() != '' && $("#pdp_selectedSize").val() != selectedSize)
			$("#pdp_selectedSize").val(selectedSize);
			
		// load tab contents
		loadTabContents(selectedSKU);
	}
}

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;
	}
	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.css("overflow", "auto");
		containerObj.animate({scrollTop:top});
		//containerObj.css("overflow", "hidden");
	}
}
/*
function toggleStyleOverflow() {
	var pdp_styles = $("#pdp_styles");
	if (pdp_styles.css("overflow") == "hidden") {
		pdp_styles.css("overflow", "auto");
		$("#pdp_viewMoreStyles").hide();
		
		// coremetrics tagging
		var cm_ViewMoreStylesPageID = "PDP: View More Styles: " + model_nbr;
		cmCreatePageviewTag(cm_ViewMoreStylesPageID, cm_CategoryID, null, null);	
	}
	else {
		pdp_styles.css("overflow", "hidden");
		$("#pdp_viewMoreStyles").show();	
	}
}
*/
/******************************
	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);
	
	if (style[idx_excluded]) {
		$("#pdp_excludedMessage").html(exclusionMessage);
		$("#pdp_excludedMessage a").click(showExcludedBubble);
		$("#pdp_excludedMessage a").mouseout(hideExcludedBubble);
	}
	else {
		$("#pdp_excludedMessage").html("");
	}
	showXforY(style);
	//highlightAvailableSizesForStyle(style);
	//highlightNoSizeStyle(sku);
	//displayDefaultPriceForStyle(sku);
	//displayThisShoeRunsIcon(sku);
	//displayTierPricing(sku);
	//displayStyleAttributes(sku);
	//defaultavailability(sku);
}

function displayStyleAttributes(sku) {
	var style = styles[sku];
	var html = "";
	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 + '" />';
	}
	$("#pdp_onlineOnly a").html(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);
}

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></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 revertStyle() {
	hoverStyle($("#pdp_selectedSKU").val());
	highlightSelectedSize();
}

function selectStyle(sku) {	
	$("#pdp_selectedSKU").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);

	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;
	//cmCreatePageviewTag(cm_OtherStylePageID, cm_CategoryID, null, null);
	cmCreateOtherStyleProductviewTag(sku, ModelName, cm_CategoryID, microsite);
	
	if (typeof(thecurrentsku) != "undefined") {
		//update sku for BazaarVoice URLs
		updateBVReturnURL(sku);
	}
	highlightSelectedSize();
	//defaultavailability(sku);
	setBVQASessionParams();	
}

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) {
	$("#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
		{
			$("#pdp_xfory a").attr("href", xforyURL);
		}
		$("#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;
			}
		}
	}
	$("#pdp_selectedSizeDisplay").html("none");
	$("#pdp_sizeAvailable").html("(choose a size)");
	//re-check availablilty message
	changeAvailability(selectedStyle[idx_sizes][0][availability_index]);
	displayDefaultPriceForStyle(selectedSKU);
}
function changeAvailability(msg){
	if (msg == "")
		$("#pdp_sizeAvailable").html("In Stock");
	else if (msg == "unavailable")
		$("#pdp_sizeAvailable").html("<span style='color: red'>Currently Unavailable for Purchase</span>");
	else
		$("#pdp_sizeAvailable").html("<span style='color: red'>Back-ordered, Expected to Ship " + msg + "</span>");
}

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")) {
		// remove wishlist id if size is changed
		if ($("#pdp_selectedSize").val() != sizeObj.html()) {
			$("#product_form input[name='WISHLIST_ITEM_ID']").remove();
			$("#product_form input[name='WISHLIST_ID']").remove();			
		}
		$("#pdp_selectedSize").val(sizeObj.html());
		$("#pdp_sizes li a").removeClass("selected");
		sizeObj.addClass("selected");
		updateHash();
		OpenShopTogetherToolBar('size');
	}
}

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 >= 0.10) {
		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++;
		}
	}
	
	return errMsg;
}

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

	return false;
}

function addToCart() {
	var errMsg = validateProduct();
	
	if (errMsg != "") return;
	
	
	if (!inlineAddToCartEnabled || isAJAXEnabled() == false) {
		// disable the submit button
		disableToCartButton();

		// submit the form
		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)
		{ 
		
			closeCartAdd();
				
			// hide select tag on ie6 because they will appear above zoom layer
			//if ($.browser.msie && $.browser.version < 7) $("select").hide();
			var documentWidth = $(document).width();	
			var documentHeight = $(document).height();
			$("body").prepend('<div id="overlayBG" ></div>');
			$("#overlayBG").css({opacity: 0.6, left:0, position: "absolute", "z-index": 700, width: documentWidth, height: documentHeight,"background-color": "black" });
			//var cartAdd_box = '<div id="cartAdd_box"><div id="cartAdd_box_top"><div id="cartAdd_box_topRight"></div></div><div id="cartAdd_content"><div class="loading"></div></div><div id="cartAdd_close"><a href="javascript:closeCartAdd()">x close</a></div><div id="cartAdd_box_bottom"></div></div>';
			var cartAdd_box = '<div id="cartAdd_box"><div id="cartAdd_box_top"><div id="cartAdd_box_topRight"></div></div><div id="cartAdd_midLeft"><div id="cartAdd_midRight"><div id="cartAdd_content"><div class="loading"></div></div><div style="clear: both"></div></div></div><div id="cartAdd_box_bottom"><div id="cartAdd_box_bottomRight"><a href="javascript:closeCartAdd()"><span class="red">x close</span></a></div></div></div>';
			$("body").prepend(cartAdd_box);
			var addToCartImg = $("#addToCartLink img");
			var addToCartImgOffset = addToCartImg.offset();
			var offsetTop 		   = addToCartImgOffset.top - 60;
			var offsetTop 	       = getViewpointTop() + ((getViewpointHeight() - 495) / 2);	
			
			var bodyWidth = $("body").width();
			var leftOffset = (bodyWidth - 520) / 2;
			
			$("#cartAdd_box").css({ width: addToCartImg.width(), height: addToCartImg.height(), left: addToCartImgOffset.left, top: addToCartImgOffset.top});
			//var arguments = new Object();
			var sku 	= $("#pdp_selectedSKU").val();
			var size 	= $("#pdp_selectedSize").val();
			var qty 	= $("#pdp_quantity").val();
			var TID     = $("#theTID").val();
			var model_nbr = $("#the_model_nbr").val();
			var id        = $("#theID").val();
			var hasymals  = $("#hasymals").val();
			//$("#cartAdd_box").addClass("loading");
			
			$("#cartAdd_box").animate({height: 465, width: 520, left: leftOffset, top:offsetTop}
				, 	"slow"
				,	function () {
					$.post(
						$("#cartAddAction").val(),				
						{sku: sku, size: size, qty: qty, inlineAddToCart: 1, TID: TID, model_nbr: model_nbr, hasymals: hasymals},
						function (responseText, textStatus, XMLHttpRequest) {
							$("#cartAdd_content").removeClass("loading");
							if (textStatus != "success") {
								alert("There was a problem while adding to cart. Please try again later.");
							}
							else {
								$("#cartAdd_content").html(responseText);	
								if (inlinePopUpOpened == 0)
								{inlinePopUpOpened = 1; }
								if (InlineCartSummaryEnabled)
								{$("#order_summary").load(cartTemplate);}
							}
						}
					)				
				}
			); 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 closeCartAdd(){
	var addToCartImg = $("#addToCartLink img");
	var addToCartImgOffset = addToCartImg.offset();
	inlinePopUpOpened = 0;
	//$("#postcard").remove();
	$("#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();
			$("#overlayBG").remove();
			$("#cartAdd_box").remove();			
		}
	);
}


function showBubble(thisObj) {
	var errMsg = validateProduct();
	
	if (errMsg != "") {
		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 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 hideBubble() {
	$("#pdp_addtocart_bubble").fadeOut(function() {
		killHotLaunchTimer();
		$("#pdp_addtocart_bubble ul").html("");	
	});
}

var timerID = null;



function initializeHotLaunchCounter() {
	$("#pdp_addToCart").hide();
	$("#pdp_timer").hide();
	killHotLaunchTimer();
	
	var 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();
		killHotLaunchTimer();
		return;
	}
	
	$("#pdp_addToCart").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();
	});
}

function replaceImageForSKU(sku) {
	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 toggleScene7Zoom(sku) {
	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("&hei=<HEIGHT>", "");
	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("&hei=<HEIGHT>", "");
	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();
	
	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;
	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 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 (document.getElementById('pdp_ShopTogether')){
		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);
	}
}
