/* combine : /javascript/common/jdwAffinities.js*/
var titleFunctions = [];
var placements = new Array();
var placementsArray = new Array();
var mobilePlacementIndex=0;
var mobileLastPlacementIndex=0;
var celvar_automatedAffinitiesSource = "rr";;
var insideClickthrough = false;
var localClickthrough;
var RR_pageId;
var R3_COMMON;
var R3_HOME;
var R3_ITEM;
var R3_SEARCH;
var R3_CATEGORY;
var R3_CART;
var R3_PURCHASED;
if(typeof isPdpAffinities == "undefined"){
	isPdpAffinities = false;
}
var currency = "&pound;";
if(typeof dataLayer != "undefined"){
	if( dataLayer[0].Currency === 'EUR'){
		currency="&euro;";
	}
}
var calledBefore = 0;
var offset = 0;

var automatedAffinitiesCallbackReceived = false;
var automatedAffinitiesSupplied = false;
var automatedAffinitiesDocumentReadyFired = false;

var noOfPlacements = 0;
if(typeof manualAffinityProducts != "undefined") {
	noOfPlacements = 1;
}

function jdwAffinitiesDisplayedOnPage() {
	celvar_automatedAffinitiesSource = "jdw";
}

function PlacementProduct(productCode, clickUrl) {
	this.productCode = productCode;
	this.clickUrl = clickUrl;
}

function Placement(index, strategy) {
	this.addProduct = function (product) {
		this.products[product.productCode] = product;
		this.productArray.push(product);
	};
	this.index = index;
	this.strategy = strategy;
	this.products = {};
	this.productArray = new Array();
	this.fragments = "";
	this.placementId = "#rr_placement_" + index;
}

// boolean tracks the first time that we create the click handler for RR carousel clicks as pages
// which refresh their content via ajax (category pages) will call processAffinities each time
// leading to several click handlers stacking up which breaks things.
var clicksDelegated = false;
function processAffinities(affinityData) {
	if(typeof useRetainedRRRecs != 'undefined' && !useRetainedRRRecs) {
		// Store the new RR recommendations via ajax
		RR_storeRRRecommendations(affinityData);
	}
	automatedAffinitiesCallbackReceived = true;
	
	// Add position information to manual affinities carousel for celebrus tracking
	noOfPlacements = noOfPlacements + affinityData.length;
	if(typeof manualAffinityProducts != "undefined") {
		$('#jdw-rr-slider-holder-manual1').attr('name', '1of'+noOfPlacements);
	}
	
	automatedAffinitiesSupplied = affinityData.length > 0;
	if (automatedAffinitiesSupplied) {
		//If page reloads rapidly due to ajax we can end up with more placements returned from RR than
		//we have slots to put them in.
		// This ensures that we only use the most recent results returned.
		if (calledBefore>0){
			offset= (affinityData.length/(++calledBefore));
			affinityData = affinityData.slice(offset);
		}
		placementsArray = affinityData;
		placements.length=0;
		//placements is still used in a few places, have to phase it out in next release.
		for (var placementIndex = 0; placementIndex < affinityData.length; placementIndex++) {
			var currentPlacement = new Placement(placementIndex, affinityData[placementIndex].message);
			placements.push(currentPlacement);
			var placementItemCount = affinityData[placementIndex].items.length;
			// On mobile, show the accordion if there are items to show in in
			if(placementItemCount > 0) {
				$("#affinityWrapper"+(placementIndex+1)).removeClass("beforeResponse");
			}
			for (var itemIndex = 0; itemIndex < placementItemCount; itemIndex++) {
				var productCode = affinityData[placementIndex].items[itemIndex].itemId;
				var clickUrl = affinityData[placementIndex].items[itemIndex].url;
				var placementProduct = new PlacementProduct(productCode, clickUrl);
				currentPlacement.addProduct(placementProduct);
			}
			if(!isPdpAffinities){
				requestFragments(placementIndex);	
			}
		}
		if(isPdpAffinities){
			$.each(affinityData, function (index, affinity){
				//process the items in the array and display in the relevant slots.
				if(affinity.placement_name == 'item_page.rr1'){
					addResponsiveAffinities(1,affinity.items, affinity.message);
				}else if (affinity.placement_name == 'item_page.rr2'){
					addResponsiveAffinities(2,affinity.items, affinity.message);
				}else if (affinity.placement_name == 'item_page.rr3'){
					addResponsiveAffinities(3,affinity.items, affinity.message);
				}else if (affinity.placement_name == 'item_page.mobile_rr2'){
					addMobileAffinities(1,affinity.items, affinity.message,0);
				}else if (affinity.placement_name == 'item_page.mobile_rr3'){
					addMobileAffinities(2,affinity.items, affinity.message,0);
				}else if(affinity.placement_name === "add_to_cart_page.rr1"){
					buildPostAddtoBagSlider(affinity.items, affinity.message);
				}else if(affinity.placement_name==='item_page.search_referrer_rr1' && searchReferrerEnabled){
					buildSearchReferrerSlider(affinity.items, affinity.message, false);
				}else if(affinity.placement_name==='item_page.mobile_search_referrer_rr1'&& searchReferrerEnabled){
					buildSearchReferrerSlider(affinity.items, affinity.message, true);
				}
			});	
		}
	} else {
		if (automatedAffinitiesDocumentReadyFired) {
			// We have not received any items from RR so they must be in listening
			// mode - therefore we need to show our own recently viewed items
			showJdwRecentlyViewedItems();
		}
	}
	
	// New handler for RR clickthroughs etc.
	if( (!clicksDelegated) && !( typeof responsive != 'undefined' && responsive )){
		var placementClass = '.rr_placement';
		$(placementClass).delegate(".productPreview a", "click", function() {
			var placement_div = $(this).parents(placementClass);
			var placement_id = placement_div.prop("id");
			var placement_index = placement_id.substring(placement_id.length-1);
			var placement = placements[placement_index];
			var id = $(this).prop("id");
			var productCode = id.substr(id.indexOf("-") + 1);
			if(!insideClickthrough) {
				insideClickthrough = true;
				navigator.sendBeacon(placement.products[productCode].clickUrl);
				localClickthrough = $(this);
				return true;
			} else {
				return false;
			}
		});
		clicksDelegated = true;
	}
}

function addMobileAffinities(divid, itemArray, message, startAt){
	var count=0;
	var colourImages='';
	if(itemArray.length > 0){
		$.each(itemArray, function(index,item){
			if(index >= startAt){
				var url = (item.url).split("ct=");
				if(item.colour_images.trim().length >1){
					colourImages = item.colour_images.split(",");	
				}
				var divtag = '<div id="celid_cms3r3_affinities_pos-'+index+'_item-'+item.itemId+'" class="two-col-grid">';
				divtag += '<div class="productFragment productPreview" itemscope="" itemtype="//schema.org/Product" itemid="'+item.itemId+'">';
				divtag += '<meta content="'+item.name+'" itemprop="name"><meta itemprop="sku" content="'+item.itemId+'">';
				divtag += '<a id="image-'+item.itemId+'" data-jdw-test-id="productCode_'+item.itemId+'" href="'+unescape(url[1])+'" data-rr-url="' + item.url + '">';
				if(colourImages.length > 1 || item.colour_images.length==0){
					divtag += '<div id="prodItem"><img src="'+item.image+'" alt="'+item.name+'" itemprop="image"></div>';	
				}else{
					var colourImage = colourImages[0].split("|");
					divtag += '<div id="prodItem"><img src="'+colourImage[1]+'" alt="'+item.name+'" itemprop="image"></div>';
				}
				divtag += '<div class="productInfo">';
				divtag += '<h3 itemprop="name">'+item.name+'</h3>';
				divtag += '<p class="savePrice"></p>';
				divtag += '<p class="productPrice">'+ currency + item.saleprice+'</p>';
				divtag += '</div>';
				divtag += '</a>';
				divtag += '</div></div></div>';
				$("div#affinities"+divid).find("div.rr_placement").append(divtag);
				++count;
				return count < view_more_increment;
			}
		});
		if($("div#tab_affinity"+divid+"Details").hasClass("disabled")){
			$("div#tab_affinity"+divid+"Details").removeClass("disabled");	
		}
		$("div#affinities"+divid).css("display", "block");
		$("div#rr_placement_"+divid*1-1).css("display", "block");
		$("div#affinities"+divid).find("div.rr_placement").css("display", "block");
		if($("div#affinityWrapper0").length) {
		   divid = (divid*1)-1;
		}
		$("div#affinityWrapper"+divid).find("h2").html(message);
		$("div#affinityWrapper"+divid).css("display", "block");
	}
}

function mobileViewMorePlacements(divid, placementIndex, startAt) {
	var idstring = divid.split("-");
	addMobileAffinities(idstring[idstring.length-1], placementsArray[placementIndex].items, placementsArray[placementIndex].message, startAt);
	return (startAt+view_more_increment >= placementsArray[placementIndex].items.length
			|| startAt+view_more_increment >= 16);
}

function addResponsiveAffinities(divid, itemArray, message){
	var ulTag = '<ul id="ul-rr_placement_'+divid+'" class="jdw-rr-scroll-content"></ul>';
	var liTag = '';
	var colourImages = '';
	if(itemArray.length > 0){
		$("div#jdw-rr-slider-holder-rr"+divid).find("div.jdw-rr-productHolder").append(ulTag);
		$.each(itemArray, function(index,item){
			var url = (item.url).split("ct=");
			if(item.colour_images.trim().length >1){
				colourImages = item.colour_images.split(",");	
			}
			index=(index*1)+1;
			liTag = '<li id="celid_cms3r3_affinities_pos-'+index+'_item-'+item.itemId+'" class="productPreview" jdw-thumbnail-index="'+index+'">';
			liTag += '<div class="productPreviewTop">';
			liTag += '<a id="image-'+item.itemId+'" href="'+unescape(url[1])+'" title="'+item.name+'" class="affinityimagelink" data-rr-url="' + item.url + '">';
			if(colourImages.length > 1 || item.colour_images.length==0){
				liTag += '<img class="jdw-rr-prodImage" src="'+item.image+'" alt="'+item.name+'"/>';
			}else{
				var colourImage = colourImages[0].split("|");
				liTag += '<img class="jdw-rr-prodImage" src="'+colourImage[1]+'" alt="'+item.name+'"/>';
			}			
			liTag += '</a>';
			if((item.rating).length>1){
				var ratingNum = getRating(item.rating);
				var ratingText = getRatingText(ratingNum);
				liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="//schema.org/AggregateRating">';
				liTag += '<strong class="score '+ratingText+'" title="'+ratingNum+' out of 5 stars">Average customer rating is '+ratingNum+' out of 5 stars.</strong>';
				liTag += '</div>';	
			}else{
				liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="//schema.org/AggregateRating"></div>';
			}
			liTag += '<div class="jdw-rr-productInfo"><h2 itemprop="name">'+item.name+'</h2></div>';
			var wasPrice = item.saleprice != item.price;
            liTag += '</div>';
            liTag += '<div class="productPreviewBottom">';
            if(wasPrice){
                  liTag += '<div class="jdw-rr-priceInfo discounted-price"><p class="jdw-rr-priceText">';
                  var saveprice = (Number(item.price.replace(",", ""))*1) - (Number(item.saleprice.replace(",", ""))*1);
                  liTag += '<p class="wasPriceFormat">Was '+currency + item.price+'</p>';
                  liTag += '<p class="salePrice">Save '+ currency + saveprice.toFixed(2)+'</p>';
            }else{
                  liTag += '<div class="jdw-rr-priceInfo"><p class="jdw-rr-priceText">';
            }
			liTag += '<p class="productPrice">'+currency + item.saleprice+'</p>';
			liTag += '</p></div>';
			liTag += '<a id="button-'+item.itemId+'" class="jdw-rr-button" href="'+unescape(url[1])+'" title="'+item.name+'">Shop Now</a>';
			liTag += '</div>';
			$("ul#ul-rr_placement_"+divid).append(liTag);
		});
	}
	$("div#jdw-rr-slider-holder-rr"+divid).closest(".pdp-affinities").children("h3").html(message);
	$("div#jdw-rr-slider-holder-rr"+divid).find("div.jdw-rr-productHolder").css("display", "block");
	$("div#jdw-rr-slider-holder-rr"+divid).closest(".pdp-affinities").removeClass("pdp-affinities-hidden");
	$('.jdw-rr-productHolder').each(function(index) {
		new jdw.simpleScroller().create(this, $(this).children('ul').children('li').length,  index);
	});
}

function buildSearchReferrerSlider(itemArray, message, isMobile){
    var ulTag = $("div#rr-search-referrer-container ul");
    if(isMobile){
           ulTag = $("div.rr-search-referrer-flexslider ul.slides");
    }
    var liTag = '';
    var colourImages = '';
    if(itemArray.length > 0){
           $.each(itemArray, function(index,item){
                  if(index <4){
                	    var url = (item.url).split("ct=");
                        if(item.colour_images.trim().length >1){
                               colourImages = item.colour_images.split(",");   
                        }
                        index=(index*1)+1;
                        liTag = '<li id="celid_cms3r3_affinities_pos-'+index+'_item-'+item.itemId+'" class="rr-search-referrer-column" jdw-thumbnail-index="'+index+'">';
                        liTag += '<a href="'+unescape(url[1])+'">';
                        liTag += '<div class="rr-search-referrer-content">';
                        if(colourImages.length > 1 || item.colour_images.length==0){
                               liTag += '<img src="'+item.image+'" alt="'+item.name+'"/>';
                        }else{
                               var colourImage = colourImages[0].split("|");
                               liTag += '<img src="'+colourImage[1]+'" alt="'+item.name+'"/>';
                        }
                        liTag += '<div class="rr-search-referrer-info">';
                        liTag += '<div class="rsProductName">';
                        liTag += '<span class="rr-search-referrer-product-name">'+item.name+'</span>';
                        liTag += '</div>';
                        if((item.rating).length>1){
                               var ratingNum = getRating(item.rating);
                               var ratingText = getRatingText(ratingNum);
                               liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="//schema.org/AggregateRating">';
                               liTag += '<strong id="rsProductReviewStyle" class="score '+ratingText+'" title="'+ratingNum+' out of 5 stars">Average customer rating is '+ratingNum+' out of 5 stars.</strong>';
                               liTag += '</div>';   
                        }else{
                               liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="//schema.org/AggregateRating"></div>';
                        }
                        var wasPrice = item.saleprice != item.price;
                        if(wasPrice){
							liTag += '<div class="jdw-rr-priceInfo discounted-price">';
							var saveprice = (Number(item.price.replace(",", ""))*1) - (Number(item.saleprice.replace(",", ""))*1);
                            liTag += '<p id="pWasPrice" class="wasPriceFormat">Was '+currency + item.price+'</p>';   
                            liTag += '<p id="pSalePrice" class="salePrice">Save '+ currency + saveprice.toFixed(2)+'</p>';
                		}else{
						    liTag += '<div class="jdw-rr-priceInfo">';
						}
                        liTag += '<p id="pProductPrice" class="productPrice">'+currency + item.saleprice+'</p>';
                        liTag += '</div>';
                        liTag += '</div>';
                        liTag += '</div>';
                        liTag += '</a>';
                        liTag += '</li>';
                        ulTag.append(liTag);
                  }
           });
    }
    $("h3.rr-search-referrer-title").html(message);
    $("div#rr-search-referrer-container").css("display", "block");
    if(isMobile){
    	callTheSlider();
    }
}


function callTheSlider(){
  $('.flexslider').flexslider({
    animation: "slide"
  });
}

function getRatingText(rating){
	var text = "";
	if(rating.indexOf("0.") != -1){
		text = "half";
	}else if(rating.indexOf("1.") != -1){
		text = "one";
		if( (rating*1)>1.5 ){
			text = "oneAndHalf";
		}
	}else if(rating.indexOf("2.") != -1){
		text="two";
		if( (rating*1)>2.5 ){
			text = "twoAndHalf";
		}
	}else if(rating.indexOf("3.") != -1){
		text = "three";
		if( (rating*1)>3.5 ){
			text = "threeAndHalf";
		}
	}else if(rating.indexOf("4.") != -1){
		text = "four";
		if( (rating*1)>4.5 ){
			text = "fourAndHalf";
		}
	}else if(rating.indexOf("5.") != -1){
		text = "five";
	}
	return text;
}

function getRating(ratingUrl){
	var rating = ratingUrl.split("/");
	return rating[rating.length-3];
}
//added this to fix Post addto bag slider
function buildPostAddtoBagSlider(itemArray, message){
	if(rrAffinityData === undefined){
		var productParameters = "";
		$.each(itemArray, function(index,item){
			productParameters += "&productIds=" + item.itemId;
		});
		var ajaxUrlJsonResponse = "/shop/product/ajax/OutfitAffinityProducts.action?displayPriceRanges=true&maxProducts=";
		$.ajax({
			url: ajaxUrlJsonResponse+maxProductsInCarousel + productParameters,
			dataType: "json",
			async:false,
			success: function(data){
				rrAffinityData = data.outfitMap;
				rrAffinityMessage = message;
			},
			error: function (data, status, xhr){
				if (typeof console != "undefined") {
					console.log("Error in fragment request");
				}
			},
			complete: function(){
				jdw.productDetailsOutfitBuilder.openOutfitBuilder(currentAddToBagReturnData);				
			}
		});	
	}
}


function requestFragments(placementIndex, startAt) {
	// Most calls won't provide a startAt value so default to zero
	if(typeof(startAt)==='undefined') startAt = 0;
	
	var placement = placements[placementIndex];
	var productParameters = "";
	
	if(placement.productArray.length == 0) {
		// If RR sent us nothing back don't bother going through the second ajax call to render
		// products.
		return;
	}
	
	for (var i = startAt; i < placement.productArray.length; i++) {
		productParameters += "&productIds=" + placement.productArray[i].productCode;
	}
	
	var ajaxUrl = "/shop/product/fragment/AffinityProductFragmentList.action?displayPriceRanges=true&maxProducts=";
	if(typeof responsive != 'undefined' && responsive) {
		ajaxUrl = "/shop/product/ajax/AffinityProductFragmentListResponsive.action?displayPriceRanges=true&maxProducts=";
	}
	
	var ajaxUrlJsonResponse = "/shop/product/ajax/OutfitAffinityProducts.action?displayPriceRanges=true&maxProducts=";
	
	if(placementIndex == 0) {
		$.ajax({
			url: ajaxUrlJsonResponse+maxProductsInCarousel + productParameters,
			dataType: "json",
			success: function(data){
				rrAffinityData = data.outfitMap;
				rrAffinityMessage = placements[0].strategy;
			},
			error: function (data, status, xhr){
				if (typeof console != "undefined") {
					console.log("Error in fragment request");
				}
			}

		});
	}
	
	
	$.ajax({
		url: ajaxUrl+maxProductsInCarousel + productParameters,
		success: (function (_placements, _placementIndex){
			return function (data, status, xhr){
				_placements[_placementIndex].fragments = data;
				var placementId = _placements[_placementIndex].placementId;
				if ($(placementId).length) {
					populateAutomatedAffinities(_placements, _placementIndex, startAt);
				} else {
					setTimeout(function(){
						if ($(placementId).length) {
							populateAutomatedAffinities(_placements, _placementIndex, startAt);
						} else {
							$(document).ready(function () {populateAutomatedAffinities(_placements, _placementIndex, startAt);});
						}
					}, 500);
				}
			};
		})(placements, placementIndex),
		error: function (data, status, xhr){
			if (typeof console != "undefined") {
				console.log("Error in fragment request");
			}
		}

	});
}

function setupJCarousel(carouselBase, len) {
	var minLengthForCarousel = (typeof MIN_LIST_ITEMS_FOR_JCAROUSEL !== "undefined") ? MIN_LIST_ITEMS_FOR_JCAROUSEL : 4;
	if (((typeof len !== "undefined") ? len : carouselBase.children("li").length) > minLengthForCarousel) {
		if (typeof(carouselBase.jcarousel) == "function") {
			carouselBase.jcarousel();
		}
	}
}

function processPageAffinities(placements, placementIndex) {
	var placement = placements[placementIndex];
	var affinities = $(placement.placementId).parentsUntil(".affinityWrapper", ".carouselContainer").parent();
	affinities.find("h2.carouselHeader").html(placement.strategy);
	var affinityList = affinities.find('ul');
	var affinityCount = affinityList.children("li.carouselElement").length;
	if (affinityCount) {
		if (typeof(initCarousel) == "function") {
			initCarousel(placementIndex);
		}

		affinities.show();
	}
}

function processResponsivePageAffinities(placements, placementIndex) {
	var placement = placements[placementIndex];
	var affinities = $(placement.placementId).parentsUntil(".pdp-affinities").parent();
	affinities.find('h3').html(placement.strategy);
	var posOnPage = placementIndex + 1;
	if(typeof manualAffinityProducts != "undefined") {
		posOnPage = posOnPage + 1;
	}
	$(placement.placementId).parent().attr("name", posOnPage+"of"+noOfPlacements);
	affinities.removeClass('pdp-affinities-hidden');
}

function populateAutomatedAffinities(placements, placementIndex, startAt) {
	var placement = placements[placementIndex];

	var ulTag = '<ul>';
	if(typeof responsive != 'undefined' && responsive === true) {
		ulTag = '<ul class="jdw-rr-scroll-content">';
	}
	
	if(startAt === 0) {
		$(placement.placementId).html(ulTag+placement.fragments+'</ul>').show();
	} else {
		$(placement.placementId + " ul").append(placement.fragments);
	}

	if(typeof responsive != 'undefined' && responsive) {
		processResponsivePageAffinities(placements, placementIndex);
	} else {
		processPageAffinities(placements, placementIndex);
	}
	
	// Call back to the page that the affinities have loaded.
	if(typeof(affinitiesLoaded) !== 'undefined' && affinitiesLoaded.length > placementIndex) {
		affinitiesLoaded[placementIndex](placement.productArray.length);
	}
}

function RR_init(pageId) {
	
	try {
		if (!resetForAjax()){
			return false;
		}
		RR_pageId = pageId;
		R3_COMMON = new r3_common();
		R3_COMMON.setApiKey(RR_apiKey);
		R3_COMMON.setBaseUrl(window.location.protocol+'//'+RR_server);
		R3_COMMON.setClickthruServer(window.location.protocol+'//'+window.location.host);
		R3_COMMON.setSessionId(RR_sessionId);
		R3_COMMON.setUserId(RR_userId);
		var isTablet = $('meta[name=jdw-isTablet]').attr("value") == "true";
		var isMobile = $('meta[name=jdw-isMobileDevice]').attr("value") == "true";
		var channel = RR_apiKey;
		if(isTablet) {
			channel += "-tablet";
		} else if(isMobile) {
			channel += "-mobile";
		} else {
			channel += "-desktop";
		}
		R3_COMMON.setChannel(channel);
	} catch (e) {
		console.log("jdwAffinities::RR_init failed with " + e.message);
	}
	
	return true;
}

function RR_initHome() {
	try {
		if (!RR_init("home_page")){
			return false;
		};
		R3_HOME=new r3_home();
		RR_setupHome();
		r3();
	} catch (e) {
		console.log("jdwAffinities::RR_initHome failed with " + e.message);
	}

}

function RR_initItem() {
	try {
		if (!RR_init("item_page")){
			return false;
		}
		R3_ITEM=new r3_item();
		R3_ITEM.setId(RR_item);
		RR_setupItem();
		r3();
	} catch (e) {
		console.log("jdwAffinities::RR_initItem failed with " + e.message);
	}
}

function RR_initSearch() {
	try {
		if (!RR_init("search_page")){
			return false;
		}
		
		R3_SEARCH=new r3_search();
		R3_SEARCH.setTerms(RR_searchTerm);
		RR_setupSearch();
		r3();
	} catch (e) {
		console.log("jdwAffinities::RR_initSearch failed with " + e.message);
	}
}

function RR_initCategory() {
	try {
		if (!RR_init("category_page")){
			return false;
		}
		R3_CATEGORY=new r3_category();
		R3_CATEGORY.setId(RR_categoryId);
		R3_CATEGORY.setName(RR_categoryName);
		RR_setupCategory();
		r3();
	} catch (e) {
		console.log("jdwAffinities::RR_initCategory failed with " + e.message);
	}
}

function RR_initCart() {
	try {
		// If we have kept hold of existing recommendations, we want to load those existing rather than
		// request new ones
		if(typeof useRetainedRRRecs != 'undefined' && useRetainedRRRecs) {
			RR_loadRetainedRecommendations();
			return false;
		}
		if (!RR_init("cart_page")){
			return false;
		}
		R3_CART=new r3_cart();
		RR_setupCart();
		r3();
	} catch (e) {
		console.log("jdwAffinities::RR_initCart failed with " + e.message);
	}
}

function RR_initPurchased(title) {
	try {
		if (!RR_init("purchased_page")){
			return false;
		}
		R3_PURCHASED=new r3_purchased();
		R3_PURCHASED.setOrderNumber(RR_orderNumber);
		titleFunctions['RR_setupPurchased'+title]();
		r3();
	} catch (e) {
		console.log("jdwAffinities::RR_initPurchased failed with " + e.message);
	}
}
// Posts the Rich Relevance recommendations to the PersistRRRecommendationsAction via ajax. The
// action stores the recs as a JSON string in the session so they can be retrieved and re-displayed
// in on-screen carousels.
function RR_storeRRRecommendations(affinityData) {
	$.ajax({
		url: "/shop/viewbag/ajax/StoreRRRecommendations.action",
		data: {recommendationsJson: JSON.stringify(affinityData)},
		error: function() {
			if (typeof console != "undefined") {
				console.log("Failed to store RR recommendations.");
			}
		},
		type: "POST"
	});
}
// Makes an ajax call to the PersistRRRecommendationsAction to retrieve any Rich Relevance
// recommendations stored in the session and passes the retrieved placements array into
// processAffinities to build carousels displaying them.
function RR_loadRetainedRecommendations() {
	$.ajax({
		url: "/shop/viewbag/ajax/RetrieveRRRecommendations.action",
		success: function(data) {
			var affinityData = JSON.parse(data.recommendationsJson);
			processAffinities(affinityData);
		},
		error: function() {
			if (typeof console != "undefined") {
				console.log("Unable to retrieve stored RR recommendations.");
			}
		}
	});
}

function resetForAjax(){
	// Clear the itemObjArray as it seems to be holding onto previous placement details resulting
	// in duplicated carousels in some specific cases (i.e. when the user has no 'recently viewed'
	// items to populate the second placement)
	if(typeof itemObjArray !== "undefined") {
		itemObjArray = new Array();
	}

	rr_placement_place_holders.length=0;
	RR.onloadCalled = false;
	var makeRRCall = true;

	function getHash(){
		try{
			return History.getHash();
		}catch (error){
			return false;
		}
	}

	if (getHash()){
		//this is not the base version of the page

		if (History.stateChanged){
			//page refreshed due to ajax

		}else{
			//*Not* refreshed by ajax, page is about to be reloaded. RR call should be aborted
			makeRRCall=false;
			rr_onload_called = false;
		}
	}
	return makeRRCall;
}

function initCarousel(placementIndex) {
    setProductSlider("#rr_placement_" + placementIndex, getSliderAttributes());
    var x = 1;
}

function setProductSlider(containerSelector, slideArray) {
	var container = $(containerSelector);
    if (container.data('flexslider')) {
        container.removeData('flexslider')
    }
	container.addClass("flexslider");
	$(containerSelector+" ul").addClass("slides");
	
    container.flexslider({
        animation: "slide",
        direction: slideArray.direction,
        controlNav: false,
        touch: false,
        animationLoop: false,
        slideshow: false,
        itemWidth: $(containerSelector +' ul.slides > li').outerWidth(),
        itemHeight: 130,
        itemMargin: 0,
        maxItems: slideArray.items,
        move: 1
    });
    // parseInt($('.rr_placement.flexslider li.carouselElement:first-child').css('margin-right').replace('px', ''))
    setProductSliderCSS(containerSelector, slideArray);
}

function setProductSliderCSS(containerSelector, slideArray) {
	var container = $(containerSelector);
    if ($(containerSelector + " ul > li").length <= slideArray.items) {
        container.find('.flex-prev').hide();
        container.find('.flex-next').hide();
        if (!container.hasClass('inactive')) container.addClass('inactive');
    } else {
        container.find('.flex-prev').show();
        container.find('.flex-next').show();
        if (container.hasClass('inactive')) container.removeClass('inactive');
    }
}

function getSliderAttributes() {
    /* Horizontal by default */
    var direction = $(window).width() > 769 ? "horizontal" : "vertical";
    
    var items = direction == "horizontal" ? 4 : 3;
    if (typeof HORIZONTAL_OVERRIDE !== "undefined" && direction == "horizontal") {
    	items = HORIZONTAL_OVERRIDE;
    }
    if (typeof VERTICAL_OVERRIDE !== "undefined" && direction == "vertical") {
    	items = VERTICAL_OVERRIDE;
    }
    
    return {'direction' : 'horizontal', 'items' : items}; 
}

function showJdwRecentlyViewedItems() {
	if ($("#recentlyViewedContainer").length) {
		$("#recentlyViewedContainer").show();
	} else if ($("#recentlyViewedItems").length) {
		$("#recentlyViewedItems").show();
	}
}

function mobileViewMore(placementIndex, startAt) {
	requestFragments(placementIndex, startAt);
	// Return value, true means there are no more fragments left and the view more button should
	// be disabled.
	return (startAt+view_more_increment >= placements[placementIndex].productArray.length
			|| startAt+view_more_increment >= 16);
}

$(document).ready(function() {
	if (automatedAffinitiesCallbackReceived
		&& !automatedAffinitiesSupplied) {
		// We have not received any items from RR so they must be in listening
		// mode - therefore we need to show our own recently viewed items
		showJdwRecentlyViewedItems();
	}
	automatedAffinitiesDocumentReadyFired = true;
});


// Mobile manual affinities details to allow view more for manual
//Expect an array manualAffinityProducts containing product ids to be defined on the page.
var fragments;
var manualPlacementId = '#manual_placement_0';
function requestManualFragments(startAt) {
	// Most calls won't provide a startAt value so default to zero
	if(typeof(startAt)==='undefined') startAt = 0;
	
	var productParameters = "";
	for (var i = startAt; i < manualAffinityProducts.length; i++) {
		productParameters += "&productIds=" + manualAffinityProducts[i];
	}
	$.ajax({
		url: "/shop/product/fragment/AffinityProductFragmentList.action?displayPriceRanges=true&maxProducts="+maxProductsInCarousel + productParameters,
		success: (function (data, status, xhr){
			fragments = data;
			if ($(manualPlacementId).length) {
				populateManualAffinities(startAt);
			} else {
				setTimeout(function(){
					if ($(manualPlacementId).length) {
						populateManualAffinities(startAt);
					} else {
						$(document).ready(function () {populateManualAffinities(startAt);});
					}
				}, 500);
			}
		}),
		error: function (data, status, xhr){
			if (typeof console != "undefined") {
				console.log("Error in fragment request");
			}
		}
	});
}

function populateManualAffinities(startAt) {
	if(startAt === 0) {
		$(manualPlacementId).html('<ul>'+fragments+'</ul>').show();
	} else {
		$(manualPlacementId + " ul").append(fragments);
	}
}

function manualViewMore(startAt) {
	requestManualFragments(startAt);
	// Return value, true means there are no more fragments left and the view more button should
	// be disabled.
	return (startAt+view_more_increment >= manualAffinityProducts.length
			|| startAt+view_more_increment >= 16);
}

function r3_placementSAFE(a) {
    var b = "rr_placement_" + rr_placement_place_holders.length;
    $('div.rrPlacement').first().attr('id', b).removeClass('rrPlacement');
    rr_placement_place_holders.push({
        elementId: b,
        placementType: a
    })
}/* complete : /javascript/common/jdwAffinities.js*/


