document.domain="which.co.uk";

function loadCustomerRatingsInformation(serverUrl, productId) {
	var requestBatch = new RequestBatch();
	requestBatch.AddToRequest(new ReviewPage(new ArticleKey(productId), 10,1));
	//done in one request to minimise server hits
	requestBatch.BeginRequest(serverUrl, renderRatings);
}

function renderRatings(responseBatch) {

	if (responseBatch.Messages[0].Message != 'ok' || responseBatch.Responses.length == 0){
		return;
	}

	if (responseBatch.Responses[0].ReviewPage.NumberOfReviews != null) {
		$(".js-mgc").show();
		var totalNumberReviews = responseBatch.Responses[0].ReviewPage.NumberOfReviews;			
		var tabName = $("#customer-ratings-tab").html();
		$("#customer-ratings-tab").html(tabName+" ("+totalNumberReviews+")");
		$(".total-reviews-count").html(totalNumberReviews);
		if(totalNumberReviews > 0){$(".total-reviews-text").html("Average customer view");}
		else {$(".total-reviews-text").html("Be the first to post a view!");}
		
		if(totalNumberReviews == 0){
			$("#member-rating-sidebar a").html("Tell us what you think");
		}
		
	}
	
	/* 
		The following commented code is for Average Customer reviews.
	 */
	//if (responseBatch.Responses[0].ReviewPage.AverageReviewRating > 0) {
	//	var averageReviews = responseBatch.Responses[0].ReviewPage.AverageReviewRating;
	//	averageReviews = Math.round(averageReviews);
	//	var image_server = $("#image-server").html().replace(/^\s+|\s+$/g,"");
	//	if(image_server != null){
	//		$("#customer-views-average-image").html("<img src='"+image_server+"/assets/images/icons/"+averageReviews+"-ticks.png' alt='"+averageReviews+" out of 5' width='80' height='13'/>");
	//	}
	//}
	//$("#member-rating-sidebar").show();
	
	//Set showPluckForm = true; in the html, $(document).ready
	//if (showPluckForm){commentsSetup()}

	   if (showPluckForm){commentsSetup()}
		
	
}

function commentsSetup() {
	$("#average-views-container").after("<div id='do-you-own'><h3>Do you own this product? If so, tell us about your experience of using it.</h3> <p class='pluck-intro'>We want to know how you use it, plus your tips for getting the best from it. Your experiences can help others identify whether it's the right choice for them and add to the picture provided by our rigorous, comparative and independent testing.</p> </div>"); // Write form heading to page
	
	var cookie = getCookie("at"); // retrieve HD or AT cookie
	if (cookie != null){
		var screenName = unescape(cookie.split("&")[1]);
		screenName = screenName.substring(2, screenName.length);
	} else {
		screenName = null
	}
					
	if (cookie == null) { 
		$("#do-you-own p.pluck-intro").after("<p>To give us your view either <a href='/login'>login</a> or <a href='/signup'>sign up to Which?</a>.</p>");	// If not signed in write login and register links to page

	} else if (cookie != null && cookie.length > 0) {
		if (screenName == (null || "")) { // If screen name isn't found in the cookie then write create user name link to page 
			$("#do-you-own p.pluck-intro").after("<p>If this is your first time posting your view you will need to <a href='/account/editdisplayname'>create a screen name</a>. </p>");
		} else if (/^\d+$/i.test(screenName)) /*Checks if the screen name is numeric only*/ {
			$("#do-you-own").html("<h3>Please set your screen name</h3><p>You need a screen name to use this feature. Screen names should contain either letters a-z or a combination of letters a-z and numbers 0-9 and be minimum 6 characters in length.</p><p><a href='/account/editdisplayname'>Please amend your screen name</a>.</p>");
		} else {
			$("#do-you-own p.pluck-intro").after('<p><a href="#reviewsiframe">Post my view</a></p>');  
			$("#do-you-own p.pluck-intro").after("<p>Your screen name is currently "+ screenName +". <a href='/account/editdisplayname'>Change screen name</a>. </p>");								
			$("p.views-conditions").show(); 
		}
	}
	$(function() {
		addPluckFunctionality(screenName);
	});
}

function getCookie(name) {
	var dc = document.cookie;               // this returns/reads all cookies for the domain separated by a semicolon
	var prefix = name + "=";                // creates "hd=" ("hd" is passed in to the function)
	var begin = dc.indexOf("; " + prefix);  // returns a -1 or whole number for position of "; hd"
	if (begin == -1){                       // "; hd" string does not exist - meaning that hd is the first cookie in the collection of cookies for the domain
			begin = dc.indexOf(prefix);     // begin is 0 since prefix ("hd") is at the 0 position
			if (begin != 0) {return null;}  // begin should be at index 0 - fail if not
			} else {
				begin += 2;                     // add 2 to current begin -- not sure why. perhaps this is useful if hd is not the first cookie for the domain
			}
	var end = document.cookie.indexOf(";", begin); // search the cookie collection for ";", start the search at begin
			if (end == -1) {                        // end does not exist so there is only one cookie for the domain
					end = dc.length;                // only one cookie for the domain so the end is the length
				}
	return unescape(dc.substring(begin + prefix.length, end)); // return the values between the end of "hd=" and the end of the cookie
}

// function to attach additional content and behaviour to pluck functionality
function addPluckFunctionality(screenName) {
	var timer = null; // timer to check whether the iframe is available now
    var timesFound = 0;
	// Show form if the user has a screen name and it's not numeric
	var showForm = screenName && screenName.length > 0 && !(/^\d+$/i.test(screenName));
	
	// this function checks whether the iframe already exists or not
    // if yes, it clears the interval timer & calls the loader
    var check = function() {
        if ($('#reviewsiframe').contents().find(".Reviews_Submit").length) {
			timesFound = timesFound + 1;
			if (timesFound > 1000 || timesFound > 1 && !$.browser.msie) {
				clearInterval(timer);
			}
			loader();
        }
    };
	
    // the loader attaches a load event to the iframe
    // one potential problem could be that the load event gets
    // fired between 2 checks, i.e. iframe wasn't available yet
    // this time it is, but it already loaded as well & the event
    // is fired before we attached it.
    // you could try solving that by reducing the time between calls in the call below
    var loader = function() {
		if (showForm) {
			$("#reviewsiframe").contents().find("form").show();
		} else {
			$("#reviewsiframe").contents().find("form").hide();
		}
    };
    
    // calls the check & sets the interval in which it should be called
    // again if the iframe wasn't available yet.
    // you could try reducing the length of this if you run into
    // the problem mentioned above
	timer = setInterval(check, 10);
};