//explorer_unoptimized.js Copyright 2007-2009 RichRelevance, Inc. All Rights Reserved.
var RR = {
	un: 'undefined',
	d: document,
	dr: document.referer,
	drr: document.referrer,
	id: function(id) { return RR.d.getElementById(id); },
	l: location.href,
	lc: function(n) {
		if (n.indexOf('=') === -1) {
			n += '=';
		}
		if (n.indexOf('?') === -1 && n.indexOf('&') === -1) {
			var pidx = RR.l.indexOf('?'+n);
			if (pidx === -1) pidx = RR.l.indexOf('&'+n);
			return pidx !== -1;
		} else {
			return (RR.l.indexOf(n) !== -1);
		}
	},
	u: 'recs.richrelevance.com/rrserver/',
	au: 'media.richrelevance.com/rrserver/',
	le: function(f) {
		var of = window.onload;
		if (typeof of != 'function') {
			window.onload = f;
		} else {
			window.onload = function() { of(); f(); };
		}
	},
	ce : function(t,n) {
		if (typeof n !== "undefined") {
			// IE 6,7 do not let you change the name of an element after creating it.
			// Other browsers do not let you create an element in the way done above.
			/*@cc_on @if (@_jscript)
			return RR.d.createElement('<'+t+' name="'+n+'">');
			@else */
			var newNode = RR.d.createElement(t);
			newNode.name = n;
			return newNode;
			/* @end @*/
		}
		return RR.d.createElement(t);
	},
	ac : function(p, c) {
		p.appendChild(c);
	},
	ia : function(p,c1,c2) {
		p.insertBefore(c1,c2.nextSibling);
	},
	ap: function(p,n,v) {
		if (typeof p[n] == RR.un || !p[n]) {
			p[n] = '';
		} else {
			p[n] += '|';
		}
		p[n] += v;
	},
	pq: function(n){
		var pidx = RR.l.indexOf("?"+n+'=');
		if (pidx == -1) pidx = RR.l.indexOf("&"+n+'=');
	 	var v;
	 	if(pidx !== -1){
	 		pidx++;
			var didx = RR.l.indexOf("&", pidx);	
			if(didx != -1){
				v = RR.l.substring(pidx+n.length+1, didx);
			}else{
				v = RR.l.substring(pidx+n.length+1, RR.l.length);
			}
		}else{
			v='';
		}
		return v;
	},
	cs: function(s,p,a){
		for (var n in p) {
			if (typeof p[n] !== RR.un) {
				s += ((a)?'&':'')+n+'='+encodeURIComponent(p[n]);
				a = true;
			}
		}
		return s;
	},
	creatScript: function(src) {
	    var script = RR.d.createElement('script');
		script.type = 'text/javascript';
	    script.src = src;
		RR.d.getElementsByTagName('head')[0].appendChild(script);
	},
	show: function(elems){
		for (var i=0;i<elems.length;i++) {
			elems[i].style.display = '';
		}
	},
	hide: function(elems){
		for (var i=0;i<elems.length;i++) {
			elems[i].style.display = 'none';
		}
	},
	getElementsByClass: function(searchClass,node,tag) {
		var classElements = new Array();
		if ( node == null )
			node = document;
		if ( tag == null )
			tag = '*';
		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
		for (i = 0, j = 0; i < elsLen; i++) {
			if ( pattern.test(els[i].className) ) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	},
	jsonCallback: function(recs) {},
	onloadCalled: false,
	useJsonRecs: function () {},
	useJsonRecsOnload: function () {
		if (!RR.onloadCalled) {
			RR.onloadCalled = true; 
			RR.useJsonRecs();
		}
	}
};
RR.explorer = {
	 fetchRecs: function(addon) {
		var C = RR.explorer.COMMON;
		if (RR.lc('r3_forceDisplay=true')){
			C.forceDisplayMode();
		}
		if (RR.lc('r3_forceDev=true')){
			C.forceDevMode();
		}
		if (RR.lc('r3_useDummyData=true')){
			C.useDummyData();
			C.forceDisplayMode();
		}
		if (RR.lc('r3_forcedTreatment=')){
			C.setForcedTreatment(RR.pq('r3_forcedTreatment'));
		}
		var scriptSrc = C.getUrl();
		if (scriptSrc.toLowerCase().indexOf('https://') == 0) {
			scriptSrc += '&ssl=t';
		}
		if (addon !== null) {
			scriptSrc += addon;
		}
		
		var preferer = '';
		if (RR.drr !== '' && typeof RR.drr != RR.un) {preferer = RR.drr;}
		if (preferer === '' && RR.dr !== '' && typeof RR.dr != RR.un) {preferer = RR.dr;}
		if (preferer !== '') {scriptSrc += '&pref=' + encodeURIComponent(preferer);}
		scriptSrc += '&l=1';
		setTimeout('RR.creatScript("'+scriptSrc+'")',10);

	 },
	 placement: function() {
		 if (RR.explorer.LAYOUT) {
			 document.write(RR.explorer.LAYOUT);
		 }
		 if (RR.explorer.afterLayout) {
			 RR.explorer.afterLayout();
		 }
	 },
	 makeItem: function(item, rank) {
		var div = RR.ce('div');
		div.id=item.itemId;
		if (RR.explorer.ITEM) {
			// replace placeholders in item
			
			var html = RR.explorer.ITEM.replace(/\$ID\$/g,item.itemId).replace(/\$IMAGE\$/g,item.image).replace(/\$URL\$/g,item.url).replace(/\$NAME\$/g,item.name).replace(/\$LARGEIMAGE\$/g,item.largeimage);
			html = html.replace(/\$CUSTOMattr_savestory\$/g,item.attr_savestory);
			//.replace(/$RANK$/,rank);
			
			div.innerHTML = html;
		}
		return div;
	 },
	 COEFFICIENT: .412,
	 REMOVAL_THRESHOLD: (1.0/10000.0),
	 maxMatrixItems: 100,
	 thumbsUpItems: [],
	 nonThumbsUpItems: [],
	 productScoreMap: {},
	 compareItems: [],
	 /*printProductScores: function() {
		 var i = 0;
		 for (var product in RR.explorer.productScoreMap) {
			 var arr = RR.explorer.productScoreMap[product];
			 console.log((i + 1) + '.) product: ' + product + ' arr: ' + arr.toString());
			 i++;
		 }
	 },*/
	 addProductScores: function(seedId, idToScoreMap) {
		 for (var existingItem in RR.explorer.productScoreMap) {
			if (!idToScoreMap[existingItem]) {
				 RR.explorer.addProduct(existingItem, 0.0);
			}
		 }
		 for (var newItem in idToScoreMap) {
			 RR.explorer.addProduct(newItem, idToScoreMap[newItem]);
		 }
//				 RR.explorer.printProductScores();
	 },
	 addProduct: function(id, score) {
//				console.log('adding product: ' + id + ' score: ' + score);
		var arr = RR.explorer.productScoreMap[id];
		if (!arr) {
			arr = [];
			var putInNonThumbsUp = true;
			for (var i = 0; i < RR.explorer.thumbsUpItems.length; i++) {
				arr.push(0.0);
				if (RR.explorer.thumbsUpItems[i] == id) {
					putInNonThumbsUp = false;
				}
			}
			if (putInNonThumbsUp) {
				RR.explorer.nonThumbsUpItems.push(id);
			}
		}
		// add the new score to the beginning of the array
		arr.unshift(score);
		RR.explorer.productScoreMap[id] = arr;
	 },
	 removeProduct: function(id) {
//				console.log('removing item from productScoreMap: ' +  id);
		if (RR.explorer.productScoreMap[id]) {
			delete RR.explorer.productScoreMap[id];
		}
	 },
	 makeThumbsUpItemFirst: function(index) {
		 for (var item in RR.explorer.productScoreMap) {
			 var scoreArr = RR.explorer.productScoreMap[item];
			 if (scoreArr) {
				var itemToMoveToFront = scoreArr[index];
				scoreArr.splice(index, 1);
				scoreArr.unshift(itemToMoveToFront);
//					 } else {
//						console.log('unable to obtain scores for item: ' + item);
			 }
		 }
		 // now move the actual thumbs up item
		 var itemToMove = RR.explorer.thumbsUpItems[index];
		 RR.explorer.thumbsUpItems.splice(index, 1);
		 RR.explorer.thumbsUpItems.unshift(itemToMove);
	 },
	 removeProductScores: function(thumbsUpIndex) {
		 for (var item in RR.explorer.productScoreMap) {
			 var scoreArr = RR.explorer.productScoreMap[item];
			 if (scoreArr) {
				 if (scoreArr.length > thumbsUpIndex) {
					scoreArr.splice(thumbsUpIndex, 1);
					RR.explorer.productScoreMap[item] = scoreArr;
//						 } else {
//							console.log('not enough scores for item: ' + item + ' size: ' +  scoreArr.length);
				 }
//					 } else {
//						console.log('unable to obtain scores for item: ' + item);
			 }
		 }
//				 RR.explorer.printProductScores();
	 },
	 calculateScore: function(id) {
		 var scoreArr = RR.explorer.productScoreMap[id];
		 var score = 0.0;
		 if (scoreArr) {
			 for (var i = 0; i < scoreArr.length; i++) {
				 score += scoreArr[i]*Math.pow(RR.explorer.COEFFICIENT,i);			 
			 }
//				 } else {
//					 console.log('calculate score not found for: ' + id);
		 }
		 return score;
	 },
	 sortProductScores: function(id1, id2) {
		 var score1 = RR.explorer.calculateScore(id1);
		 var score2 = RR.explorer.calculateScore(id2);
		 return score2 - score1; 
	 },
	 recalculateScores: function() {
		 // this will go through all of the products and compute the score that should 
		 // be used and set it appropriately
		 RR.explorer.nonThumbsUpItems.sort(RR.explorer.sortProductScores);
		var idsToRemove = [];
		var idsToHide = [];
		var lastId = null;
		for (var i=0;i<RR.explorer.nonThumbsUpItems.length;i++) {
			var id = RR.explorer.nonThumbsUpItems[i];
			var score = RR.explorer.calculateScore(id);
			if ($('#' + id)) {
				if (RR.id('rank'+id)) {
					RR.id('rank'+id).innerHTML = score;
//						} else {
//							console.log('id ' + id + ' found but rank div not found');
				}
				if (score <= 0.0) {
					idsToRemove.push(id);
				} else if (score <=  RR.explorer.REMOVAL_THRESHOLD) {
					idsToHide.push(id);
				} else {
					if (lastId) {
						$('#'+id).insertAfter($('#'+lastId));
					}
					lastId = id;
				}
				
//					} else {
//						console.log(id + ' not found score: ' + score);
			}
		}

		for (var i=0;i<idsToRemove.length;i++) {
			var id = idsToRemove[i];
			RR.explorer.removeFrom(id, RR.explorer.nonThumbsUpItems, true);
		}

		for (var i=0;i<idsToHide.length;i++) {
			var id = idsToHide[i];
			$('#'+id).hide();
		}
	 },
	 removeFrom: function(id, arrItemIds, fromDomToo) {
		// remove the product from the productScoreMap
		if (arrItemIds === RR.explorer.nonThumbsUpItems && fromDomToo) {
			RR.explorer.removeProduct(id);
		}
		for (var i=0;i<arrItemIds.length;i++) {
			if (id == arrItemIds[i]) {
				if (fromDomToo) {
					$(RR.id(id)).remove();
				}
				// if we are removing an item from the thumbsup items
				if (arrItemIds === RR.explorer.thumbsUpItems && fromDomToo) {
					RR.explorer.removeProductScores(i);
				}
				arrItemIds.splice(i,1);
				return i;
			}
		}
		return -1;
	},
	placeNewItem: function(item, rank) {
		var elem = RR.id(item.itemId);
		if (!elem) {
			elem = RR.explorer.makeItem(item, rank);
		}
		var isThumbsUpItem = false;
		for (var i=0;i<RR.explorer.thumbsUpItems.length;i++) {
			if (RR.explorer.thumbsUpItems[i] == item.itemId) {
				isThumbsUpItem = true;
			}
		}
		if (!isThumbsUpItem) {
			for (var i=0;i<RR.explorer.nonThumbsUpItems.length;i++) {
				var compareId = RR.explorer.nonThumbsUpItems[i];
				if (RR.explorer.calculateScore(compareId) < rank) {
					if (compareId != item.itemId) {
						$(elem).insertBefore($('#'+compareId));
					}
					break;
				}
			}
		}
		return elem;
	},
	pushChildren : function(navHtml,nav) {
		navHtml.push('<ul>');
		for (var i=0;i<nav.length;i++) {
			navHtml.push('<li><a href="');
			navHtml.push(nav[i].link);
			navHtml.push('">');
			navHtml.push(nav[i].name);
			navHtml.push('</a>');
			if (nav[i].children.length>0) {
				RR.explorer.pushChildren(navHtml,nav[i].children);
			}
			navHtml.push('</li>');
		}
		navHtml.push('</ul>');
	},
	initialize: function() {
		 RR.jsonCallback = function(recs) {
			 if (typeof recs.explorerId !== 'undefined') {
				RR.explorer.sessionId = recs.explorerId;
			 }
			 if (typeof recs.placements === 'undefined' || typeof recs.placements[0] === 'undefined' || typeof recs.placements[0].items === 'undefined' || recs.placements[0].items.length == 0) {
				 $('#rr_no_products').show();
			 } else {
				$('#rr_other_filters').hide();
				RR.explorer.maxMatrixItems = recs.placements[0].maxItems;
				var matrix = RR.id('rr_matrix');
				// reset matrix
				matrix.innerHTML = ''; // should put a loading image in here
				RR.explorer.productScoreMap = {};
				RR.explorer.nonThumbsUpItems = [];
	
				for (var i=0;i<recs.placements[0].items.length;i++) {
					var item = recs.placements[0].items[i];
					var elem = RR.explorer.makeItem(item, 1.0/(2.0+i));
					RR.explorer.addProduct(item.itemId, 1.0/(2.0+i));
					matrix.appendChild(elem);
				}
				
				if (typeof rrafterMatrixInsert == 'function') rrafterMatrixInsert();
				
				var clear = RR.ce('div');
				clear.style.clear='both';
				matrix.appendChild(clear);
				clear = RR.ce('div');
				clear.style.clear='both';
				RR.id('rr_thumbsUp').appendChild(clear);

				if (typeof RR.explorer.constraint === 'undefined') {
					if (RR.lc("rr_st=")) {
						var searchTerm = RR.pq('rr_st');
						while (searchTerm.indexOf('+')>-1) {
							searchTerm = searchTerm.replace('+',' ');
						}
						RR.id('rr_matrixMsg').innerHTML='Click on an item to start exploring items related to "'+decodeURIComponent(searchTerm)+'"';
					} else if (RR.lc("rr_ph=") && RR.lc("rr_phn=")) {
						var seedProductName = RR.pq('rr_phn');
						RR.id('rr_matrixMsg').innerHTML='Click on an item to start exploring more items like "'+decodeURIComponent(seedProductName)+'"';
					} else {
						if (RR.lc("rr_cn=")) {
							var categoryNameTerm = RR.pq('rr_cn');
							while (categoryNameTerm.indexOf('+')>-1) {
								categoryNameTerm = categoryNameTerm.replace('+',' ');
							}
							RR.id('rr_matrixMsg').innerHTML='Click on an item to start exploring "' + decodeURIComponent(categoryNameTerm) + '"';
						} else {
							RR.id('rr_matrixMsg').innerHTML='Click on an item to start exploring this category';
						}
					}
				 } else {
						RR.id('rr_matrixMsg').innerHTML = 'Click on an item to start exploring';
				 }
			 }
			// navigation
			if (typeof recs.navigation !== 'undefined') {
				var nav = recs.navigation;
				if (nav.length>0) {
					var navRootName = 'Choose Categories'; 
					if (recs.navigationRootName && recs.navigationRootName != 'ROOT') {
						navRootName = recs.navigationRootName;
					}
					//navHtml = ['<ul class="sf-menu"><li class="current" onmouseover="$(this).addClass(\'sfHover\')" onmouseout="$(this).removeClass(\'sfHover\')"><a href="#" onclick="return false;" class="sf-with-ul">' + navRootName + '<span class="sf-sub-indicator">&nbsp;V</span></a><ul>'];
					navHtml = ['<ul class="sf-menu">'];
					for (var i=0;i<nav.length;i++) {
						navHtml.push('<li onmouseover="$(this).addClass(\'sfHover\')" onmouseout="$(this).removeClass(\'sfHover\')" onclick="RR.explorer.switchGenre(this, \'');
						navHtml.push(nav[i].link);
						navHtml.push('\');"');
						if (nav[i].selected === 'true') {
							navHtml.push(' class="current"');
							if (typeof RR.explorer.COMMON.getGiftSee() !== 'undefined') {
								RR.explorer.constraint.gid = encodeURIComponent(nav[i].link.substring(nav[i].link.indexOf('rr_gid=')+7, nav[i].link.indexOf('&rr_tg=')));
								RR.explorer.constraint.tg = nav[i].link.substring(nav[i].link.indexOf('&rr_tg=')+7, nav[i].link.length);
							}
						}
						navHtml.push('><span>');
						navHtml.push(nav[i].name);
						navHtml.push('</span>');
						if (nav[i].children.length>0) {
							RR.explorer.pushChildren(navHtml,nav[i].children);
						}
						navHtml.push('</li>');
					}
					navHtml.push('</ul>');
					$('.rr_genres_filter').prepend(navHtml.join(''));
				}
			}
		};
		 
		 RR.explorer.categoryConstraint = '';
		 RR.explorer.productConstraint = '';
		 if (typeof RR.explorer.constraint === 'undefined') {
			 RR.explorer.constraint = {};
			 var filprinc = false;
			 if (RR.lc('rr_gid') && RR.lc('rr_tg')) {
				 RR.explorer.gid = RR.pq('rr_gid');
				 RR.explorer.constraint.gid = RR.pq('rr_gid');
				 RR.explorer.constraint.tg = RR.pq('rr_tg');
				 RR.explorer.categoryConstraint += '&g='+RR.pq('rr_gid')+'&tg='+RR.pq('rr_tg');
			 }
			 if (RR.lc('rr_c=')) {
				 RR.explorer.constraint.filcat = RR.pq('rr_c').split('|');
				 RR.explorer.categoryConstraint += '&filcat='+RR.pq('rr_c')+'&filcatinc=true';
			 }
			 if (RR.lc('rr_b=')) {
				 RR.explorer.constraint.filbr = RR.pq('rr_b').split('|');
				 RR.explorer.categoryConstraint += '&filbr='+RR.pq('rr_b')+'&filbrinc=true';
			 }
			 if (RR.lc('rr_p=')) {
				 RR.explorer.constraint.products = RR.pq('rr_p').split('|');
				 RR.explorer.productConstraint += '&p='+RR.pq('rr_p');
			 }
			 if (RR.lc('rr_lp=')) {
				 RR.explorer.constraint.filprmin = RR.pq('rr_lp');
				 RR.explorer.categoryConstraint += '&filprmin='+RR.pq('rr_lp');
				 filprinc = true;
			 }
			 if (RR.lc('rr_hp=')) {
				 RR.explorer.constraint.filprmax = RR.pq('rr_hp');
				 RR.explorer.categoryConstraint += '&filprmax='+RR.pq('rr_hp');
				 filprinc = true;
			 }
			 if (filprinc) {
				 RR.explorer.categoryConstraint += '&filprinc=true';
			 }
		 } else {
			 var filprinc = false;
			 RR.explorer.categoryConstraint = '&nav=f&g='+RR.explorer.constraint.gid+'&tg='+encodeURIComponent(RR.explorer.constraint.tg);;
			if (typeof RR.explorer.constraint.filcat !== 'undefined' && RR.explorer.constraint.filcat.length > 0) {
				RR.explorer.categoryConstraint += '&filcat='+encodeURIComponent(RR.explorer.constraint.filcat.join('|'));
			}
			if (typeof RR.explorer.constraint.filbr !== 'undefined' && RR.explorer.constraint.filbr.length > 0) {
				RR.explorer.categoryConstraint += '&filbr='+encodeURIComponent(RR.explorer.constraint.filbr.join('|'));
			}
			if (typeof RR.explorer.constraint.products !== 'undefined' && RR.explorer.constraint.products.length > 0) {
				RR.explorer.productConstraint += '&p='+encodeURIComponent(RR.explorer.constraint.products.join('|'));
			}
			if (typeof RR.explorer.constraint.filprmin !== 'undefined') {
				RR.explorer.categoryConstraint += '&filprmin='+encodeURIComponent(RR.explorer.constraint.filprmin);
				 filprinc = true;
			}
			if (typeof RR.explorer.constraint.filprmax !== 'undefined') {
				RR.explorer.categoryConstraint += '&filprmax='+encodeURIComponent(RR.explorer.constraint.filprmax);
				 filprinc = true;
			}
			 if (filprinc) {
				 RR.explorer.categoryConstraint += '&filprinc=true';
			 }
		 }
		 
		 RR.explorer.fetchRecs('&pt=explorer_page.matrix' + RR.explorer.categoryConstraint + RR.explorer.productConstraint);
	 },
	 thumbsDown: function(id) {
		var elem = RR.id(id);
		var index = -1;
		var itemName = $('#'+id+' .rr_itemname').html();
		if (elem) {
			// remove from thumbsUp
			index = RR.explorer.removeFrom(id, RR.explorer.thumbsUpItems, true);
			var productIndex = -1;
			for (var i = 0; i < RR.explorer.constraint.products.length; i++) {
				if (id == RR.explorer.constraint.products[i]) {
					productIndex = i;
					break;
				}
			}
			RR.explorer.constraint.products.splice(productIndex, 1);
			if (RR.explorer.thumbsUpItems.length === 0) {
				$('#rr_instructions').show();
				$('#rr_poweredby').show();
				$('#rr_yourclicks').hide();
			} else {
				//turn off the small display for the first item
				$('#rr_thumbsUp > .rr_thumbsUp:first-child > .rr_matrixItem > .rr_lessInfo').hide();
				
				//turn on the big display
				$('#rr_thumbsUp > .rr_thumbsUp:first-child > .rr_matrixItem > .rr_moreInfo').show();
				
				//a previously small item jsut moved to the top, remove it's rr_small cssclass
				$('#rr_thumbsUp > .rr_thumbsUp:first-child').removeClass("rr_Small");
				
				//we just pushed an item down the list, so reset the rr_small class
				$('#rr_thumbsUp > .rr_thumbsUp:not(div:first-child)').addClass("rr_Small");
				
				//turn off the big description on the ones that now have rr_Small and turn on the small display
				$('#rr_thumbsUp > .rr_Small > .rr_matrixItem > .rr_moreInfo').hide();
				$('#rr_thumbsUp > .rr_Small > .rr_matrixItem > .rr_lessInfo').show();
				
				$('#rr_yourclicks').show();
				
				
			}
            if (RR.COMPARE_BASE_URL) {
                myindex = jQuery.inArray(id, RR.explorer.compareItems);
                if (myindex > -1) {
                	RR.explorer.compareItems.splice(myindex, 1);
                }
            }
			RR.explorer.recalculateScores();
		}
		if (index>-1) {
			RR.jsonCallback = function(recs) {
				var matrix = RR.id('rr_matrix');
				var items = recs.placements[0].items;
				$('#rr_matrixMsg').html('Removed item named '+itemName);
			};
			RR.explorer.fetchRecs('&pt=explorer_page.thumbsDown&p='+id+'&esi='+RR.explorer.sessionId+RR.explorer.categoryConstraint);
		}
	},
	thumbsUp: function(id, clickThruUrl) {
		//unbind the tip commands
		$('div.qtip').qtip('destroy');
		// if this item is already the last one in the list then we don't need to do anything with it (TODO: though maybe we should request the recs for it?)
		if (RR.explorer.thumbsUpItems.length === 0 || id != RR.explorer.thumbsUpItems[0]) {
			var elem = RR.id(id);
			if (elem) {
				// remove from nonThumbsUp
				var indexInNonThumbsUp = RR.explorer.removeFrom(id, RR.explorer.nonThumbsUpItems, false);
				if (id != RR.explorer.thumbsUpItems[0]) {
					if (indexInNonThumbsUp === -1) {
						// remove from thumbsUp
						
						// find the index in the thumbs up array
						var indexInThumbsUp = -1;
						for (var thumbsUpIndex = 0; thumbsUpIndex < RR.explorer.thumbsUpItems.length; thumbsUpIndex++) {
							var thumbsUpItem = RR.explorer.thumbsUpItems[thumbsUpIndex];
							if (thumbsUpItem == id) {
								indexInThumbsUp = thumbsUpIndex;
								break;
							}
						}
						
						// remove the id from the product ids array
						for (var productIdIndex = 0; productIdIndex < RR.explorer.constraint.products.length; productIdIndex++) {
							var productId = RR.explorer.constraint.products[productIdIndex];
							if (productId == id) {
								RR.explorer.constraint.products.splice(productIdIndex, 1);
								break;
							}
						}
						
						if (indexInThumbsUp != -1) {
							// we have an index within thumbsup, dont need to fetch recs again, just reorder the scores
							// and relayout
							
							// TODO remove the duplicates
							
							RR.explorer.makeThumbsUpItemFirst(indexInThumbsUp);
							$(elem).insertBefore(RR.id('rr_thumbsUp').firstChild);
							
							//turn off the small display for the first item
							$('#rr_thumbsUp > .rr_thumbsUp:first-child > .rr_matrixItem > .rr_lessInfo').hide();
							
							//turn on the big display
							$('#rr_thumbsUp > .rr_thumbsUp:first-child > .rr_matrixItem > .rr_moreInfo').show();
							
							//a previously small item jsut moved to the top, remove it's rr_small cssclass
							$('#rr_thumbsUp > .rr_thumbsUp:first-child').removeClass("rr_Small");
							
							//we just pushed an item down the list, so reset the rr_small class
							$('#rr_thumbsUp > .rr_thumbsUp:not(div:first-child)').addClass("rr_Small");
							
							//turn off the big description on the ones that now have rr_Small and turn on the small display
							$('#rr_thumbsUp > .rr_Small > .rr_matrixItem > .rr_moreInfo').hide();
							$('#rr_thumbsUp > .rr_Small > .rr_matrixItem > .rr_lessInfo').show();
						
							RR.explorer.recalculateScores();
							document.getElementById('rr_hiddenClickImg').src = clickThruUrl.replace('click?','explorerclick?') + '&esi=' + RR.explorer.sessionId;
							return;
//								} else {
//									console.log('couldnt find index in thumbsup for id: ' +  id);
						}
					} else {
						$(elem).stop().addClass('rr_thumbsUp').attr('style','');
					}
					if (typeof RR.explorer.constraint.products === 'undefined') {
						RR.explorer.constraint.products = [];
					}
					RR.explorer.constraint.products.push(id);
					RR.explorer.thumbsUpItems.unshift(id);
					$('#rr_instructions').hide();
					$('#rr_poweredby').hide();
					$('#rr_yourclicks').show();
					
					$(elem).insertBefore(RR.id('rr_thumbsUp').firstChild)
					
					//turn off the small display for the first item
					$('#rr_thumbsUp > .rr_thumbsUp:first-child > .rr_matrixItem > .rr_lessInfo').hide();

					//set "rr_small" class on each item that's not the first
					$('#rr_thumbsUp > .rr_thumbsUp:not(div:first-child)').addClass("rr_Small");
					
					//turn off the big description on the ones that now have rr_Small
					$('#rr_thumbsUp > .rr_Small > .rr_matrixItem > .rr_moreInfo').hide();
					$('#rr_thumbsUp > .rr_Small > .rr_matrixItem > .rr_lessInfo').show();

					$('#'+id+' div.tip > div').remove();

					//turn on quickview if it is enabled for the first item
					if (indexInNonThumbsUp > -1) {
						if (RR.QV_ENABLED) {
							rrqvBtn('#rr_thumbsUp');
						}
					}
					
					var itemName = $('#'+id+' .rr_itemname').html();
					RR.jsonCallback = function(recs) {
						var productScoreMap = {};
						for (var i=0;i<recs.placements[0].items.length;i++) {
							var item = recs.placements[0].items[i];
							var score = recs.placements[0].maxItems-i;
							if (!RR.id(item.itemId)) {
								elem = RR.explorer.placeNewItem(item, score);
								if (elem) {
									$(document).ready(function(){$(elem).addClass('r'+id)});
								}
							}
							productScoreMap[item.itemId] = score;
						}

						if (typeof rrafterMatrixInsert == 'function') rrafterMatrixInsert();
						
						$('#rr_matrixMsg').html('Items similar to '+itemName);
						RR.explorer.addProductScores(id, productScoreMap);
						RR.explorer.recalculateScores();
					};
					// add 1x1 img to call click url
					document.getElementById('rr_hiddenClickImg').src = clickThruUrl.replace('click?','explorerclick?') + '&esi=' + RR.explorer.sessionId;

					RR.explorer.fetchRecs('&pt=explorer_page.thumbsUp&p='+id+'&esi='+RR.explorer.sessionId+RR.explorer.categoryConstraint);
				}
			}
		}
		
	},
	attribute: function(clickThruUrl){
		//alert(clickThruUrl)
		// add 1x1 img to call click url
		document.getElementById('rr_hiddenClickImg').src = clickThruUrl.replace('click?','explorerclick?') + '&esi=' + RR.explorer.sessionId;
	},
	handleFeedback: function() {
		var msg = $('#rr_feedbackMessage').val();
		document.getElementById('rr_hiddenClickImg').src = RR.explorer.COMMON.getFeedbackUrl() + '&feedbackMessage=' + msg;
		$('#rr_feedback_response').show('slow');
		$('#rr_feedback_title').hide();
		$('#rr_feedback_box').hide();
		$('#rr_feedback').hide();
		$('#rr_feedback_message').html("Thank you for your feedback.");
		setTimeout('tb_remove();', 1500);
		return false; 
	},
	cancelFeedback: function() {
		$('#rr_feedback_box').hide('slow');
	},
	compareClick: function(id) {
		var cArr = RR.explorer.compareItems;
		var i = cArr.length;
		if (i) {
			i = i;
		}else{
			i = 0;
		}
			
		if ($('#'+id+' > div > p > a').hasClass('compareLinkHidden')) {
			//checked
			$('#'+id+' > div > p > label').hide();
			$('#'+id+' > div > p > a').addClass('compareLink');
			$('#'+id+' > div > p > a').removeClass('compareLinkHidden');
			RR.explorer.compareItems[i] = id;			
		}
		else { 
			//unchecked
			//Hide link and show the lable (unchecked)
			$('#'+id+' > div > p > label').show();
			$('#'+id+' > div > p > a').addClass('compareLinkHidden');
			$('#'+id+' > div > p > a').removeClass('compareLink');
			if (RR.COMPARE_BASE_URL) {
                myindex = jQuery.inArray(id, RR.explorer.compareItems)
                if (myindex > -1) {
                	RR.explorer.compareItems.splice(myindex, 1);
                }
			}
		}
		//alert(RR.explorer.compareItems.join("-"));
	},
	compareGo: function() {
		rr_compareGo(RR.explorer.compareItems)
	},
	openFilters: function() {
		$('#rr_matrix div.tip').unbind();
		$('#rr_matrix div.tip').each(function(i) { $(this).qtip('api').destroy(); });
		$('#rr_other_filters').show();
		// get the categories for the currently selected genre and display them
		if (typeof RR.explorer.constraint.gid !== 'undefined') {
			RR.explorer.getCategories(RR.explorer.constraint.gid);
		}
		// get the brands for the currently selected genre and categories and display them
		RR.explorer.getBrands(RR.explorer.constraint.gid);
	},
	switchGenre: function(elem, gid) {
		$('ul.sf-menu li').removeClass('current');
		$(elem).addClass('current');
		RR.explorer.constraint.gid = encodeURIComponent(gid.substring(gid.indexOf('rr_gid=')+7, gid.indexOf('&rr_tg=')));
		RR.explorer.constraint.tg = gid.substring(gid.indexOf('&rr_tg=')+7, gid.length);
		RR.explorer.getCategories(RR.explorer.constraint.gid);
		RR.explorer.constraint.filcat = [];
		RR.explorer.getBrands(RR.explorer.constraint.gid);
		RR.explorer.constraint.filbr = [];
	},
	getCategories: function(gid) {
		$('.rr_categories_filter > div:not(.rr_cat_filter_control)').remove();
		if (typeof RR.explorer.beforeGetCategories !== 'undefined') RR.explorer.beforeGetCategories(); 
		var giftSee = RR.explorer.COMMON.getGiftSee();
		$.getScript('http://recs.richrelevance.com/rrserver/api/explorer/'+RR.explorer.COMMON.getApiKey()+'/categories?gid='+gid+(typeof giftSee !== 'undefined' ? '&gftc=t' : '')+'&jsoncallback=?', function() {
			if (typeof RR.explorer.categories.categories !== 'undefined') {
				$('.rr_categories_filter > div:not(.rr_cat_filter_control)').remove();
				$.each(RR.explorer.categories.categories, function(i, category) {
					var checked = false;
					if (typeof RR.explorer.constraint.filcat !== 'undefined' && RR.explorer.constraint.filcat.length > 0) {
						for (var j = 0; j < RR.explorer.constraint.filcat.length; j++) {
							if (category.extId == RR.explorer.constraint.filcat[j]) {
								checked = true;
							}
						}
					}
					addCategory(i, category, checked);
				});
				$('.rr_category_filter > input').change(function() {
					RR.explorer.constraint.filcat = [];
					$('.rr_category_filter > input:checked').each(function() {
						RR.explorer.constraint.filcat.push($(this).attr('value'));
					});
					RR.explorer.getBrands(gid);
					RR.explorer.constraint.filbr = [];
				});
			}
			if (typeof RR.explorer.afterGetCategories !== 'undefined') RR.explorer.afterGetCategories(); 
		});
	},
	getBrands: function(gid) {
		$('#rr_brands_filter_inner > div:not(.rr_br_filter_control)').remove();
		if (typeof RR.explorer.beforeGetBrands !== 'undefined') RR.explorer.beforeGetBrands(); 
		var constraint = 'gid='+gid;
		if (typeof RR.explorer.constraint.filcat !== 'undefined') {
			constraint += '&filcat='+encodeURIComponent(RR.explorer.constraint.filcat.join('|'));
		}
		var giftSee = RR.explorer.COMMON.getGiftSee();
		$.getScript('http://recs.richrelevance.com/rrserver/api/explorer/'+RR.explorer.COMMON.getApiKey()+'/brands?'+constraint+(typeof giftSee !== 'undefined' ? '&gftc=t' : '')+'&jsoncallback=?', function() {
			if (typeof RR.explorer.brands.brands !== 'undefined') {
				$('#rr_brands_filter_inner > div:not(.rr_br_filter_control)').remove();
				$.each(RR.explorer.brands.brands, function(i, brand) {
					var checked = false;
					if (typeof RR.explorer.constraint.filbr !== 'undefined' && RR.explorer.constraint.filbr.length > 0) {
						for (var j = 0; j < RR.explorer.constraint.filbr.length; j++) {
							if (brand.name == RR.explorer.constraint.filbr[j]) {
								checked = true;
							}
						}
					}
					addBrand(i, brand, checked);
				});
				$('.rr_brand_filter > input').change(function() {
					RR.explorer.constraint.filbr = [];
					$('.rr_brand_filter > input:checked').each(function() {
						RR.explorer.constraint.filbr.push($(this).attr('value'));
					});
				});
			}
			if (typeof RR.explorer.afterGetBrands !== 'undefined') RR.explorer.afterGetBrands(); 
		});
	},
	applyFilters: function() {
		RR.explorer.initialize();
	}
};
 RR.explorer.COMMON = function() {
 	// implement debug?
 	var p = {},
 	baseUrl = 'http://'+RR.u,
	_ap = function(n,v) { RR.ap(p,n,v); };
	
	p.ts=new Date().getTime();
	
	return {
		setBaseUrl: function(url) {
	 		if ('http://'+RR.au == url) {
				url = 'http://'+RR.u;
			}
			if ('https://'+RR.au == url) {
				url = 'https://'+RR.u;
			}
			baseUrl = url;
		},
		setClickthruServer: function(v) { p.cts=v; },
		setApiKey: function(v) { p.a=v; },
		setForcedTreatment: function(v) { p.ftr=v; },
		setUserId: function(v) { p.u=v; },
		setSessionId: function(v) { p.s=v; },
		forceListenMode: function() { p.flm='t'; },
		forceDisplayMode: function() { p.fdm='t'; },
		forceDevMode: function() { p.dev='t'; },
		useDummyData: function() { p.udd='t'; },
		enableJson: function() { p.je='t'; },
		addStrategy: function(v) { _ap('fs',v); },
		addPlacementType: function(v) { _ap('pt',v); },
		addItemIdToCart: function(v) { _ap('atcid',v); },
		addForcedTemplate: function(v) { _ap('ft',v); },
		addForcedPoolItem: function(v) { _ap('fp',v); },
		addCategoryHintId: function(v) { _ap('chi',v); },
		setPageType: function(v) { p.pti=v; },
		addPageArea: function(v) { _ap('pa',v); },
		setGiftSee: function () { p.gftc='t'; },
		setViewGuid: function(v) { p.vg=v; },
		setFromRichMail: function(v) { p.rm=v; },
		getApiKey: function() { return p.a; }, 
		getPageType: function() { return p.pti; },
		getUrl: function() { return RR.cs(baseUrl+'p13n_generated.js?je=t&jt=exp',p,true); },
		getFeedbackUrl: function() { return RR.cs(baseUrl+'feedback?pt=explorer',p,true); },
		getGiftSee: function() { return p.gftc; }
	};
 }();
RR.le(RR.useJsonRecsOnload);