//************************************************************************************************************************************
// @@@@@@ Boston Green Goods - All rights reserved 2009 @@@@@@
// Functions to populate review elements for multiple items.
// Start with BV-anonymous element ids that are tagged with associated item identifiers.  
// Sequentially for each reviewable item in turn: (leverage tail of ratingsDisplayed() to anonymize and drive iteration)
// - Modify each BV element set in turn to be recognizible by BV.
// - Modify the src for BVFrame to invoke population of the BV divs.
// - Make the elements BV-anonymous again.
//************************************************************************************************************************************

//** GLOBALS - what are the IDs of reviewable items?  What is the current item being processed? Are we done yet?
// Does this page have expert review content in the reviews section?
var reviewableItems = [];
var currentItem = 0;
var allReviewsShown = false;
var hasExpertReviews = false;

//******** TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO *
var stagingString = "";  // TODO - Modify this to blank string when we go live.
//******** TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO * TODO *
var reviewsId = 4449;
var reviewDomain  = "allergybuyersclubshopping";

var inShowDelay = false;
var invitationShown = false;


// Pull this stuff out once BV gets their side fixed.  Also pull invocation from bgg_finalizeReviewSetup()
var fixedTopTry = 0;
var fixedBottomTry = 0;
var MAXFIXTRIES = 30;
var FIXRETRYDELAY = 250;

//**********************************************************************************************************
function bgg_fixBVProblem(location) {

var okToTry = false;

var badElements = new Array();

if(location == "TOP")
	{
	fixedTopTry++;
	badElements[0] = document.getElementById("BVCustomerRatings");
	if(fixedTopTry < MAXFIXTRIES)
		{
		okToTry = true;
		}
	}
else
	{
	fixedBottomTry++;
	var targetSection = document.getElementById("customerReviewHead");
	if(targetSection != null)
		{
		if(browserType != "IE")
			{
			badElements[0] = targetSection.childNodes[5];
			}
		else
			{
			badElements[0] = targetSection.childNodes[2];
			}
		}

	if((fixedBottomTry < MAXFIXTRIES) && (badElements[0] != null))
		{
		okToTry = true;
		}
	}

//alert(badElements[0] + " : " + location + " : " + okToTry);


if(badElements[0] != null)
	{
	if(okToTry)
		{
		for (var index = 0; index < badElements.length; index++)
			{
			var badChildren = badElements[index].childNodes;
			if(badChildren && (badChildren.length > 0))
				{
				var badChild = null;
				if(browserType != "IE")
					{
					badChild = badChildren[1].childNodes[1];
					}
				else
					{
					badChild = badElements[0].getElementsByTagName("table")[0];
					}
	
				if((badChild != null) && (badChild.className.indexOf("BVRatingSummaryZeroReviews") > -1))
					{
					var culprit = null;
	
					if(browserType != "IE")
						{
						culprit = badChild.childNodes[1].childNodes[0];
						}
					else
						{
						culprit = badChild.childNodes[0].childNodes[0];
						}
	
					while(culprit.lastChild != null)
						{
						culprit.lastChild.parentNode.removeChild(culprit.lastChild);
						}
					}
				}
			}
		}
	}

else
	{
	if(okToTry)
		{
//alert(badElements[0] + " : " + okToTry);
		var retryCommand = "bgg_fixBVProblem('" + location + "')";
		setTimeout(retryCommand,FIXRETRYDELAY);
		}
	}
}

//**********************************************************************************************************
// Setup the correct BV context values.  Default pertains to ABC.  Override defaults for GAM.
//**********************************************************************************************************
function bgg_setupReviewContext(domain) {

if(domain == "GAM")
	{
	reviewsId = 4450;
	reviewDomain  = "greenandmore";
	}
}

//**********************************************************************************************************
// Strip away the anonmization tags from target divs so they can be seen by BV.
//**********************************************************************************************************
function bgg_prepReviewInline(itemID) {

var ratingsDiv = document.getElementById("BVCustomerRatings-" + itemID);
if(!ratingsDiv)
	{
	ratingsDiv = document.getElementById("BVCustomerRatings_" + itemID);
	}

if(ratingsDiv)
	{
	ratingsDiv.id = "BVCustomerRatings";
	}

var linkDiv = document.getElementById("BVSVPLinkContainer-" + itemID);
if(!linkDiv)
	{
	linkDiv = document.getElementById("BVSVPLinkContainer_" + itemID);
	}

if(linkDiv)
	{
	linkDiv.id = "BVSVPLinkContainer";
	}

var reviewsDiv = document.getElementById("BVReviewsContainer-" + itemID);
if(!reviewsDiv)
	{
	reviewsDiv = document.getElementById("BVReviewsContainer_" + itemID);
	}

if(reviewsDiv)
	{
	reviewsDiv .id = "BVReviewsContainer";
	}


var activeFrame = document.getElementById("BVFrame");
if(activeFrame && ratingsDiv)
	{
	var discussionItem = ratingsDiv.getAttribute('bgg_dItem');
	ratingsDiv.id = "BVCustomerRatings";
	bgg_showReview(discussionItem);
	}

}

//**********************************************************************************************************
// Anonymize the divs that have been updated.  DON'T anonymize the BVCustomerRatings
// div at the TOP of the page, since the CSS depends on its id to contol content display.
//**********************************************************************************************************
function bgg_anonymizeReviewInline() {
var ratingsDiv = document.getElementById("BVCustomerRatings" );
if(ratingsDiv)
	{
	if(!(ratingsDiv.getAttribute('bgg_itemId').indexOf("TOP") > -1))
		{
		ratingsDiv.id = "BVCustomerRatings_" + ratingsDiv.getAttribute('bgg_itemId');
		}
	}

var linkDiv = document.getElementById("BVSVPLinkContainer");
if(linkDiv)
	{
	linkDiv.id = "BVSVPLinkContainer_" + ratingsDiv.getAttribute('bgg_itemId');
	}
}


//**********************************************************************************************************
// Set baseline to populate all review divs, sequentially, and start the series.  Work backward
// so TOP (highest placement ranked) item gets reviewed LAST.
//**********************************************************************************************************
function bgg_setupReviews() {
	currentItem = reviewableItems.length - 1;
	invitationShown = false;
	bgg_showNextReview();
}

//**********************************************************************************************************
// Control which set of divs get refreshed.  Set up by bgg_setupReviews() then runs
// automatically through BV's ratingsDisplayed() function.
//**********************************************************************************************************
function bgg_showNextReview() {

if((currentItem >= 0) && (!allReviewsShown))
	{
	var reviewID = reviewableItems[currentItem];
	bgg_prepReviewInline(reviewID);
	currentItem -= 1;
	}
else
	{
	if(!allReviewsShown && (reviewableItems.length > 0))
		{
		if(reviewDomain  == "greenandmore")
			{
			bgg_GAMshowReview();
			}
		else
			{
			bgg_finalizeReviewSetup();
			}
		}
	allReviewsShown  = true;
	}
}


//**********************************************************************************************************
// Update the iframe to invoke review populaton - how handy that iframes behave as they do!
//**********************************************************************************************************
function bgg_GAMshowReview() {

var currentTopRating = document.getElementById("BVCustomerRatings_-TOP");
if(currentTopRating)
	{
	var itemId = currentTopRating.getAttribute("bgg_dItem");
	currentTopRating.id = "BVCustomerRatings";
	invitationShown = false;
	bgg_showReview(itemId);
	triggerShowReviewInvite();
	}
}

//**********************************************************************************************************
// Take care of last-stage housekeeping.
//**********************************************************************************************************
function bgg_finalizeReviewSetup() {
	bgg_reviseReviewLinks();
	bgg_manageCustReviewSection();
	invitationShown = true;
	inShowDelay = false;
//	setTimeout("bgg_fixBVProblem('TOP')",FIXRETRYDELAY);
//	setTimeout("bgg_fixBVProblem('BOTTOM')",FIXRETRYDELAY);
}

//**********************************************************************************************************
// Decorate the reviews tab correctly.  If there are expert reviews, create a horizontal divider.
// If there are no customer reviews yet, present the option to write the first.
//**********************************************************************************************************
function bgg_manageCustReviewSection() {

if(hasExpertReviews)
	{
	var reviewDivider = document.getElementById("reviewHRDivider");
	if(reviewDivider)
		{
		var rowDivider = document.createElement("hr");
		rowDivider.size = 1;
		reviewDivider.innerHTML = "<hr size='1'/>";
		}
	}

var testDiv = document.getElementById("BVSummaryReadReviewsLink"); //BVReviewsContainer
if(!testDiv)
	{
	var custReviewHead = document.getElementById("customerReviewHead");
	if(custReviewHead)
		{
		var sourceDiv = document.getElementById("BVCustomerRatings");
		if(sourceDiv)
			{
			var destDiv = sourceDiv.cloneNode(true);
			custReviewHead.appendChild(destDiv); // innerHTML = "Be the first to review!!";
			}

		}
	}
}

//**********************************************************************************************************
// Set the "Read reviews" link to jump to the BGG anchor, rather than the BV anchor.
//**********************************************************************************************************
function bgg_reviseReviewLinks() {

var links = document.getElementsByTagName('a');
for (var index = 0; index < links.length; index++ )
	{
	if(links[index].id == "BVSummaryReadReviewsLink") 
		{
		var anchor = links[index];

		// Find the parent with the correct discussion SKU

		var dSKU = "";
		var parent = anchor.parentNode;

		while(parent && (dSKU == ""))
			{
			if(parent.className == "BVRR")
				{
				dSKU = parent.parentNode.getAttribute('bgg_dItem');
				break;
				}
			parent = parent.parentNode;
			}
		if(dSKU != "")
			{
			var dSKUString = dSKU.toString();
			anchor.href = "javascript:bgg_jumpAndShowReview(" + dSKUString + ");";
			}
		}
	}
}


//**********************************************************************************************************
// If no reviews, present invitation in review section.  Delay to wait for BV content.  Do ONCE!
//**********************************************************************************************************
function triggerShowReviewInvite() {

if((!inShowDelay) && (!invitationShown))
	{
	inShowDelay = true;
	setTimeout('bgg_finalizeReviewSetup()',5000);
	}
}

//**********************************************************************************************************
// Update the iframe to invoke review populaton - how handy that iframes behave as they do!
//**********************************************************************************************************
function bgg_showReview(itemID) {

var activeFrame = document.getElementById("BVFrame");
if(activeFrame)
	{
	activeFrame.src = "http://reviews." + reviewDomain + ".com/" + stagingString + reviewsId + "/" + itemID  +  "/reviews.htm?format=embedded&sortOrder=rating";
	}

}

//**********************************************************************************************************
// Populte review section with correct content and then jump there.
//**********************************************************************************************************
function bgg_jumpAndShowReview(itemID) {
	bgg_showReview(itemID);
	location = "#bgg_reviews";
}


//**********************************************************************************************************
// Get the item identifier (discussion item id) and invoke the review display process.
//**********************************************************************************************************
function bgg_updateReviewElements(nodeClone) {

var reviewChild = null;
var currentChild = nodeClone.firstChild;

while((currentChild != null) && (reviewChild == null))
	{
	if((currentChild.id) && (currentChild.id.indexOf("BVCustomerRatings") > -1))
		{
		reviewChild = currentChild;
		var updateReviewElementID = reviewChild.getAttribute('bgg_itemId').replace(/CHOICE/,"TOP");
		reviewChild.id = "BVCustomerRatings-" + updateReviewElementID;
		reviewChild.setAttribute('bgg_itemId',updateReviewElementID);
		if(updateReviewElementID)
			{
			bgg_prepReviewInline(updateReviewElementID);
			}
		}
	currentChild = currentChild.nextSibling;
	}
}

//**********************************************************************************************************
// Parse arguments from the incoming URL.
//**********************************************************************************************************
function bgg_bv_parseArg(argName) { 

var urlString=location.href.replace(/\%26/g,"&").replace(/\%3D/g,"=");

var itemIdString=new Array(); 
var itemIdString=urlString.split(argName + '='); 

// Look for following arguments "&" and truncate the string just prior.
var result=itemIdString[1]; 

if((result != null) && (result.indexOf("&") != -1))
	{
	result = result.split("&")[0];
	}
return result;
}

//**********************************************************************************************************
// Populate the iframe src.  This will cause the review content to be refreshed.
//**********************************************************************************************************
function bgg_setReviewLink() {

var reporter = document.getElementById('original');
if(reporter)
	{
	reporter.innerHTML = location.href;
	}

var bgg_bvDiv = document.getElementById('BVSubmissionFrame');
if(bgg_bvDiv)
	{
	bgg_bvDiv.src = bgg_getReviewLink();
	}
}

//**********************************************************************************************************
// Create the string that will be used as the src value for the iframe.
//**********************************************************************************************************
function bgg_getReviewLink() {

var returnPage = bgg_bv_parseArg('return').replace(/%25/g,"%").replace(/%3A/g,":").replace(/%2F/g,"/").replace(/%23/g,"#");
if(returnPage.indexOf("#") > -1)
	{
	returnPage = returnPage.substr(0,returnPage.indexOf("#"));
	}

var reviewArg = "";
var reviewID = bgg_bv_parseArg('review');

if(reviewID)
	{
	reviewArg = "&review=" + bgg_bv_parseArg('review');
	}

var srcString = "http://reviews." + reviewDomain  + ".com/" + stagingString + bgg_bv_parseArg('bvdisplaycode') + "/"  + bgg_bv_parseArg('bvproductid') + "/action.htm?format=embedded&action=" + bgg_bv_parseArg('action') + "&user=" + bgg_bv_parseArg('user') + "&userdisplayname=" + bgg_bv_parseArg('userdisplayname') + "&return=" + returnPage + "&campaignid=" + bgg_bv_parseArg('campaignid') + reviewArg;

var reporter = document.getElementById('reporter');
if(reporter)
	{
	reporter.innerHTML = srcString;
	}
return srcString;
}