// Return whether suggestions are enabled.
// (So we can disable all suggestions with a static update.)
function killSuggestions() {
	return false;
}

// Return the Javascript object representing the Bagbuilder.
function getBagbuilder() {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window["bagbuilder"];
	} else {
		return document["bagbuilder"];
	}
}

// Populates the Suggestions box if this customProductId is valid.
// Called by the Bagbuilder when a user chooses a color.
function colorwaySelected(customProductId,colorId1,colorId2,colorId3) {
	var cp = customProductSizeAndSkuset[customProductId];
	if(cp) {
		var sizeId = cp[0];
		var skusetId = cp[1];
		populateSuggestions(skusetId,sizeId,colorId1,colorId2,colorId3);
	}
}

// Instruct the Flash app to select the indicated colorway,
// as suggested by the Suggestions box.
function setBagbuilderPalette(index) {
	var s = suggestionData[index];
	var response = getBagbuilder().setBagbuilderPalette(s[0],s[1],s[2],s[3],s[4]);
	// to print verbose errors and confirmations: 
	// alert("setBagbuilderPalette(..) response=\n" + response);
	return response;
}

// Given a colorway (or part of a colorway), request suggestions
// for similar bags from the server. Register an asych JSON
// handler and draw suggestions as needed.
function populateSuggestions(skusetId, sizeId, colorId1, colorId2, colorId3) {

	if(!suggestions_lock) {  // global semaphore
		if(killSuggestions()) return;
		if(!skusetId || !sizeId) return;

		if(!suggestions_initialized) {
			// unfold suggestions, but do not actually draw them on the screen:
			setSuggestionsVisible(true);
			suggestions_initialized=true;
		}

		var url = "/tb2/retail/colorSuggest.htm?results=8" +
			"&skusetId=" + skusetId +
			"&sizeId=" + sizeId;

		if(colorId1) url += "&color1=" + colorId1;
		if(colorId2) url += "&color2=" + colorId2;
		if(colorId3) url += "&color3=" + colorId3;

		var suggestions = $("#BB-suggestions");
		var thumbnailPrefix = "/tb2/comp/100x75_";

		suggestions_lock = true;
		suggestions.empty();
		suggestions.append("<img src='/static/widgets/bagbuilderCradle/loading_colors.gif' class='BB-suggestions-loading' />");
		$.getJSON(url, function(data) {
			if(data == null || data.products.length < 1) {
				setSuggestionsEnabled(false);
			} else {
				suggestions.empty();
				var max_product = -1;
				$.each(data.products, function(i, item) {
					max_product = i;
					var suggestions = $("#BB-suggestions");
					if(i > 0) {
						var divider = new Image();
						divider.src = "/static/widgets/bagbuilderCradle/bag_separator.gif";
						suggestions.append(divider);
					}
					var img = new Image();
					var img_suffix = ".jpeg"; // use ".png" for more vivid images, but twice the filesize (5.7K vs. 2.4K).
					img.src = thumbnailPrefix + item.id + img_suffix;
					img.className = "BB-suggestions-thumbnail";

					// If they are given, send colors, logo and binding to Flash.
					// If not given in JSON, send null rather than undefined.
					var logoColorId = item.logo || null;
					var bindingColorId = item.binding || null;

					var colors = item.colors || [];
					var cwlen = colors.length
					var color1 = cwlen > 0 ? colors[0] : null;
					var color2 = cwlen > 1 ? colors[1] : null;
					var color3 = cwlen > 2 ? colors[2] : null;

					suggestionData[i] = [color1,color2,color3,logoColorId,bindingColorId];

					img.onclick=function() {
						// The Bagbuilder defines setPalette(...) when it first invokes the suggestion
						// service on this page. This is bound to EventRecorder.setBagbuilderPalette(...).
						setBagbuilderPalette(i);
						_gaq.push(['_trackEvent', 'BB-Suggestions', skusetId + '/size_' + sizeId, 'click-' + (i + 1)]);
					}
					suggestions.append(img);
				});
				suggestions.append('<br/>');
				for(var j=0; j<max_product + 1; j++) {
					var css = "BB-suggestions-label"
					if(j==max_product) css += " BB-suggestions-label-final";
					suggestions.append('<img src="/static/widgets/bagbuilderCradle/use_these_colors.gif" class="'+css+'" onclick="setBagbuilderPalette('+j+');" />');
				}
				if(max_product >= 0) {
					setSuggestionsEnabled(true);
				}
			}
			suggestions_lock = false;
		});
	} // endif suggestions_lock
}

function setSuggestionsEnabled(enable) { // hide or show the div
	if(killSuggestions()) return;
	setComponentEnabled('suggestions',enable);
}

function setReviewsEnabled(enable) { // hide or show the div
	setComponentEnabled('reviews',enable);
}

function setSuggestionsVisible(visible) { // min- or maximize
	if(killSuggestions()) return;
	setComponentVisible('suggestions',visible);
}

function setReviewsVisible(visible) { // min- or maximize
	setComponentVisible('reviews',visible);
}

// Show or hide 'reviews' or 'suggestions'.
function setComponentEnabled(token,enable) {
	if(enable) {
		$('#BB-'+token+'-container').show();
	} else {
		$('#BB-'+token+'-container').hide();
	}
}

// Toggle visibility on 'reviews' or 'suggestions'.
function toggleComponentVisisble(token) {
	var o='BB-header-button-open'
	var visible = $('#BB-'+token+'-header-button').hasClass(o);
	setComponentVisible(token,!visible);
}

// Minimize or maximize 'reviews' or 'suggestions'.
function setComponentVisible(token,make_visible) {
	var element_id = '#BB-' + token;
	var jqbutton = $(element_id+'-header-button');
	var o='BB-header-button-open'
	var c='BB-header-button-closed'
	if(make_visible) {
		jqbutton.removeClass(c).addClass(o);
		$(element_id).show();
	} else {
		jqbutton.removeClass(o).addClass(c);
		$(element_id).hide();
	}
}

// Returns the base proxy object required by getPwrRedrawProxy()
// and getPwrInitMonkeyProxy(), which further monkey-patch
// this object for intercepting pwr's document.*() calls.
// Purges the contents of #BB-reviews-pwr.
function getPwrBaseProxy() {
	var proxy = $('#BB-reviews-pwr');
	proxy.empty();
	proxy.getElementById = function(id) {
		return document.getElementById(id);
	};
	return proxy;
}

// Monkey-patch a JQuery proxy for diverting the
// output of engine() by posing as document.
// Inserts the CSSes initialized by getPwrInitMonkeyProxy
// before the first write() call, since pwr only inserts
// the CSSes when first initializing their display engine.
// Proxies writes to #BB-reviews-pwr via JQ append().
function getPwrRedrawProxy() {
	var proxy = getPwrBaseProxy();
	proxy.css_initialized = false;
	proxy.write = function(content) {
		if(!proxy.css_initialized) {
			if(pwr_content_cache.length >= 2) {
				proxy.append(pwr_content_cache[0]);
				proxy.append(pwr_content_cache[1]);
			}
			proxy.css_initialized = true;
		}
		proxy.append(content);
	};
	return proxy;
}

// Monkey-patch a JQuery proxy for diverting the
// output of engine() by posing as document.
// Intercepts and caches all content written to
// the document. Poses as document for the purposes
// of proxying writes directly to #BB-reviews-pwr.
function getPwrInitProxy() {
	var proxy = getPwrBaseProxy();
	proxy.write = function(content) {
		proxy.append(content);
		pwr_content_cache.push(content);
	};
	return proxy;
}

// Return the standard config hash for pwr.
function getPwrConfig(pwr_reviews_id) {
	return { 
		pr_page_id : pwr_reviews_id,
		pr_write_review : "/tb2/products/reviews?pageId=" + pwr_reviews_id,
		pr_zip_location : "/static",
		pr_locale : "en_US"
	};
}

// If ratings have not been initialized, first init the pwr display engine.
// (Re)load pwr reviews for the specified customProductSet.
function showRatings(customProductSetId,rating,maximizeReviews) {
	// 'rating' (float) is ignored but required by our API spec
	$('#BB-reviews-title').html(customProductSetIdToName[customProductSetId]);
	pwr_reviews_id = customProductSetIdToPwrId[customProductSetId];
	var pwr_config = getPwrConfig(pwr_reviews_id);
	var proxy = null;
	if(pwr_initialized) {
		proxy = getPwrRedrawProxy();
	} else {
		proxy = getPwrInitProxy();
	}
	POWERREVIEWS.display.engine(proxy,pwr_config);
	pwr_initialized = true;

	if(maximizeReviews) {
		setReviewsVisible(true);
	}
	setReviewsEnabled(true);
}

function showRatingsIfOpen(customProductSetId) {
	showRatings(customProductSetId, 0, $("BB-reviews").is(":visible"));
}

