// set up Argos Product Comparison namespace
if (!argos) var argos = {};
if (!argos.page) argos.page = {};

argos.page.refineResults = {

	// Pre-selects the refinements based on the r_ parameters in the URL
	resetValues : function() {
	
		var refinements = new Array();

		if (window.location.pathname.indexOf("static") == 1) {
			// The URL we are dealing with has been SEO encoded as its pathname begins with static
			
			// Remove the .htm at the end if present
			var path = window.location.pathname;
			if (path.substring(window.location.pathname.length - 4) == ".htm") {
				path = path.substring(0, window.location.pathname.length - 4);
			}
	
			var parameters = path.split("/");
			
			for (var i = parameters.length - 1; i > 0; i = i - 2) {
				if (parameters[i - 1].indexOf("r_") == 0) {
					refinements[refinements.length] = parameters[i - 1] + "=" + parameters[i];
				}
			}

		} else {
			// The URL we are dealing with hasn't been SEO encoded

			// + 1 to remove the ?
			var parameterStart = window.location.href.indexOf(window.location.pathname) + window.location.pathname.length + 1;
	
			var parameters = window.location.href.substring(parameterStart).split("&");
			
			for (var i = 0; i < parameters.length; i++) {
				
				if (parameters[i].indexOf("r_") == 0) {
					refinements[refinements.length] = parameters[i];
					
				}
			}

		}
		
		var refineResultsForm =  document.getElementById("refineform");	

		for(var i=0;i<refineResultsForm.elements.length; i++) {	
			var element = refineResultsForm.elements[i];

			// For piece of mind reset the values to their unselected state
			if (element.type == 'select-one') {
				element.value = '';
			} else if (element.type == 'checkbox') {
				element.checked = false				
			} else if (element.type == 'radio') {
				element.checked = false	;
				
				if (element.value == '') {
					element.checked = true;
				}
			}

			// Now update the refinements if they are in the URL
			if (element.name.indexOf("r_") == 0) {

				for (var j = 0; j < refinements.length; j++) {
					
					var param = refinements[j].split("=");
					
					// Basically if the parameter begins with this refinement
					if (param.length == 2) {

						// replace the + with space and then decode the parameter value

						var paramValue = argos.comms.url.decode(param[1].replace(new RegExp(/\+/ig), " "));
						var pipeIndex = paramValue.indexOf("|");
						var value = paramValue.substring(pipeIndex);
						
						// start the string parsed from the 2nd character as the name is preceded by 'r_'
						var thisHierarchyName = parseInt(element.name.substring(2));					

						if (element.type == 'select-one') {
							
							if (param[1].length > 0) {
							
							
								// start the string parsed from the 2nd character as the name is preceded by 'r_'
								var refinementCount = parseInt(param[0].substring(2));
								
								if (refinementCount == thisHierarchyName) {

									for (var opt = 0; opt < element.options.length; opt++) {
	
										var elemPipeIndex = element.options[opt].value.indexOf("|");
										var elemValue = element.options[opt].value.substring(elemPipeIndex);
	
										if (elemValue.indexOf(value) == 0) {
											
											element.options[opt].selected = true;
											
											if ($(element).hasClass("hierarchyselect")) {
											
												var hierarchyNodes = $("form#refineform select.hierarchyselect");
												
												for (var node = 0; node < hierarchyNodes.length; node++) {
													
													var hierarchyName = parseInt(hierarchyNodes[node].name.substring(2));
	
													// Only update the hierarchy node if it is before this hierarchy node and it doesn't already
													// have a value selected for it
													if (thisHierarchyName > hierarchyName && hierarchyNodes[node].options[0].selected) {
														// Set the second element of the hierarchy node ('All') to true.
														hierarchyNodes[node].options[1].selected = true;
														$(hierarchyNodes[node]).change();
													}
												}										
												
												// Need to set the selected value again as it has been updated in the changes above
												element.options[opt].selected = true;
												$(element).change();	
											} 
										} 
									}
								}
							}

						} else if (element.type == 'checkbox' || (element.type == 'radio' )) {
							
							var tickElemPipeIndex = element.value.indexOf("|");
							var tickElemValue = element.value.substring(tickElemPipeIndex);
							
							if (value.length > 0) {
							
							if (tickElemValue.indexOf(value) == 0) {
								element.checked = true;
								}

							} else if (value.length == 0 && tickElemValue == 0) {
								element.checked = true;
							}
						}
												
					}
				}
			}
		}		
	},

	// get refinements on the for - called from updateMatchingResults
	getRefinementsFromForm : function() {
		var refineResultsForm =  document.getElementById("refineform");
		
		var refinements ='';
		for(var i = 0; i < refineResultsForm.elements.length; i++) {
			if (refineResultsForm.elements[i].value != ''){

				var refinement = '';
				
				// checkboxes are handled differently
				if (refineResultsForm.elements[i].type == 'checkbox'){
					// only add the ones that are selected
					if (refineResultsForm.elements[i].checked){
						refinement = refineResultsForm.elements[i].name + "=" + refineResultsForm.elements[i].value;
					}
				} else if (refineResultsForm.elements[i].type == 'radio'){
					// only add the ones that are selected
					if (refineResultsForm.elements[i].checked){
						
						refinement = refineResultsForm.elements[i].name + "=" + refineResultsForm.elements[i].value;
						
					}
				} else {
					refinement = refineResultsForm.elements[i].name + "=" + refineResultsForm.elements[i].value;
				}
				
				if (refinement != ''){
					if (i == 0){
						refinements = refinement;
					} else {
						refinements = refinements + "&" + refinement;
					}
				}
			}
		}
		
		return refinements;
	},
	
	// calls AJAX methods to dynamically update the results count
	//
	// The updateHierachy parameter is a boolean value used to determine whether we update the hierarchical refinements
	updateMatchingResults : function(onlyDisabled) {
	
		var matchingresults = document.getElementById("matchingresults");
		
		var itemTotal = document.getElementById("itemTotal");
		
		var isRefinements =  argos.page.refineResults.controlSubmit();		
		

		if (isRefinements){
			// if there are refinements then submit AJAX function that retrieves the number of results			
			var XHR = $.ajax({
				// url of backend resource
				// add the refinements to the url
				url : "/webapp/wcs/stores/servlet/UpdateCount" ,
				type : "post",
				dataType: "json",
				data:argos.page.refineResults.getRefinementsFromForm(),
				success : function( json ) {
					var matchingresults = document.getElementById("matchingresults");
					var itemTotal = document.getElementById("itemTotal");

					matchingresults.innerHTML = json.resultsFound;			
								
					if (json.resultsFound < 1 || json.resultsFound == itemTotal.value){
						// if there are no matching results OR the filters selected have made no difference to the number of results,
						// then disable the go button
						argos.page.refineResults.disableSubmit();
					} else {
						argos.page.refineResults.enableSubmit();
					}
				
					argos.page.refineResults.updateHierarchy(json, $("form#refineform select.hierarchyselect"), onlyDisabled);
				},
				
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					//ignore
				}
			});
		} else {
			// if all refinements are unselected then set number of results back to original count
			matchingresults.innerHTML = itemTotal.value;
		}
	},
	
	// Updates the hierarchical refinements values
	//
	// The json parameter contains each of the values for a given refinement
	// The hierarchyNodes parameter is the set of hierarchical elements displayed
	updateHierarchy : function(json, hierarchyNodes, onlyDisabled) {
	
		var refineResultsForm =  document.getElementById("refineform");
		
		var refinements ='';
		for(var i = 0; i < refineResultsForm.elements.length; i++) {
			
			if (refineResultsForm.elements[i].id != ''){
			
				var id = refineResultsForm.elements[i].id;
				var refinementOptions = json[id];
				
				var isHierarchyNode = false;
				
				if (hierarchyNodes != undefined) {
					for (var j = 0; j < hierarchyNodes.length; j++) {
						if (id == $(hierarchyNodes[j]).attr("id")) {
							isHierarchyNode = true;					
						}
					}				
				}
				
				if (isHierarchyNode && (refinementOptions != null || refineResultsForm.elements[i].value == '')) {
				
					var refinementElem = document.getElementById(id);
					
					if( !(onlyDisabled && $(refinementElem).attr("disabled") != true) || refinementElem.value == '') {
					
						if (refinementElem.options != undefined) {
							// Remove all the old refinements apart from the default '--select--' option and the 'All' option
							while(refinementElem.options.length > 2) {
								refinementElem.remove(2);
							}
						}
						
						if (refinementOptions != null) {
						
							for (var j = 0; j < refinementOptions[0].length; j++) {
								var objOption = document.createElement("option");

								//Nasty hack 1. For FF & safari 1.
								if(argos.comms.url.encode(refinementOptions[0][j]).indexOf("%EF%BF%BD")!=-1){
									var str = argos.comms.url.encode(refinementOptions[0][j]).replace(/%EF%BF%BD/g,"£");
									refinementOptions[0][j] = str.replace(/%20/g," ");;
								}

								//Nasty hack 1. For FF & safari	2.							
								if(argos.comms.url.encode(refinementOptions[0][j]).indexOf("%26pound")!=-1){
									var str = argos.comms.url.encode(refinementOptions[0][j]).replace(/%26pound/g,"£");
//									alert("mid " +str);
									refinementOptions[0][j] = str.replace(/%20/g," ");;
//									alert("emd " + refinementOptions[0][j]);
								}
								
								//Nasty hack 2. For IE
								if(argos.comms.url.encode(refinementOptions[0][j]).indexOf("%EF%BF%BF")!=-1){
									var str = argos.comms.url.encode(refinementOptions[0][j]).replace(/%EF%BF%BF/g,"£");
									refinementOptions[0][j] = str.replace(/%20/g," ");;
								}								
																	
								objOption.text = refinementOptions[0][j];
								objOption.value = refinementOptions[1][j];
								
								
								if(document.all && !window.opera) {
									refinementElem.add(objOption);
								} else {
									refinementElem.add(objOption, null);
								}

							}
						}
					}
				}
			}
		}
		
		if (hierarchyNodes != null) {

			var refinementUndefined = false;
			
			for (var z = 0; z < hierarchyNodes.length; z++) {
			
				if (refinementUndefined) {
					$(hierarchyNodes[z]).attr("disabled", true);
					$(hierarchyNodes[z]).val('');			
				} else {
					
					// If no refinements are available, only the '--select--' and 'All' options will be shown and so we disable it			
					if (hierarchyNodes[z].options.length > 2) {
						$(hierarchyNodes[z]).attr("disabled", false);
						
						refinementUndefined = (hierarchyNodes[z].value == '');
						
					} else {
						$(hierarchyNodes[z]).attr("disabled", true);
						refinementUndefined = true;
					}
				}
			}
		}
		
		return refinements;	
	},
	
	enableSubmit : function() {
		var refinementbutton = document.getElementById("refinementbutton");
		refinementbutton.disabled = false;
		refinementbutton.className = "";					
	},
	
	disableSubmit : function() {
		var refinementbutton = document.getElementById("refinementbutton");	
		refinementbutton.disabled = true;
		refinementbutton.className = "disabled";	
	},
	
	// add functions to the form elements
	updateFormActions : function(functionObject) {
	
		var refineResultsForm =  document.getElementById("refineform");	
		for(var i=0;i<refineResultsForm.elements.length; i++) {	
					
			// add functionality to checkboxes and dropdowns
			if (refineResultsForm.elements[i].type == 'checkbox'){
				refineResultsForm.elements[i].onclick = functionObject; 
			} else if (refineResultsForm.elements[i].type == 'select-one'){
				$(refineResultsForm.elements[i]).bind('change', functionObject);
			} else if (refineResultsForm.elements[i].type == 'radio'){
				refineResultsForm.elements[i].onclick = functionObject;
			}
		}
		
	},
	
	setSelectState : function(selectNodes) {

		//reset all selects to default value
		$(selectNodes).val("");
		
		for(var i = 0; i<selectNodes.length; i++) {
			new CurrentSelect(selectNodes[i], i);
			
		}
		
		function CurrentSelect(node, index) {

			$(node).unbind(); // Ensure that no other events are bound to the change event
			$(node).bind('change', selectChange);
			
			// disable all selects after first
			if(index>0) {
				$(node).attr("disabled", true);
			}	
		
			function selectChange() {
	
				var nextIndex = index+1;
				var value = this.value;
				
				// We want to reset the values of all nodes after the changed one
				// and enable only the next node (disabling all remaining nodes).				
				for(var j = 0; j < selectNodes.length; j++) {
		
					if ( j > index) {
						$(selectNodes[j]).val('');
						
											
						if ( j == nextIndex && value != '' ) {
							$(selectNodes[j]).attr("disabled", false);
						} else {
							$(selectNodes[j]).attr("disabled", true);
						}
					}
				}
				
				// Need to update the matching results after we have updated the hierarchy refinement values
				argos.page.refineResults.updateMatchingResults( value != '' );
				
			}
		}
	},
	
	// called when updateMatchingResults (that uses AJAX) is turned on
	enableRefinementCount : function() {
		// add 'Count' functionality to form elements
		
		argos.page.refineResults.updateFormActions(function() { argos.page.refineResults.updateMatchingResults(true) });
	},
	
	// called when updateMatchingResults (that uses AJAX) is turned off
	enableFormCheck : function() {	
		// control the submit button from the form elements
		argos.page.refineResults.updateFormActions(function() { argos.page.refineResults.controlSubmit() });
	},	
	
	// if something is selected then allow the form to be sumbitted
	controlSubmit : function() {
		
		var refineResultsForm =  document.getElementById("refineform");	
		// disable submit by default
		argos.page.refineResults.disableSubmit();
		for(var i=0;i<refineResultsForm.elements.length; i++) {	
			var element = refineResultsForm.elements[i];
								
			if (element.type == 'select-one' && element.value!= null && element.value != ''){
				// select box has values, allow submit and break out loop				
				argos.page.refineResults.enableSubmit();				
				return true;
			} else if ((element.type == 'checkbox' || element.type == 'radio') && element.checked){
				// a checkbox is checked, allow submit and break out loop								
				argos.page.refineResults.enableSubmit();
				return true;				
			}
		}
	},	
		
	// setListClasses function
	//
	// Loops through the UL elements inside a specified
	// container (divName), and through each LI within 
	// those ULs, ignoring a specified number of ULs
	// from the beginning (ignoreFirst).  Checks if a
	// list has more than a specified number of entries
	// to always be shown (listInitial), and hides the
	// rest appropriately.  Finally, the script assigns
	// an onclick action to the last list item if there
	// are hidden entries.	
	setListClasses : function(divName, ignoreFirst, listInitial) {
	
		var expandedRefinements = argos.page.refineResults.getExpandedRefinements();
	
		var leftCol = document.getElementById(divName);		
		var uls = leftCol.getElementsByTagName('ul');
		
		for (var x = ignoreFirst; x < uls.length; x++) {
			
			var refinementName = argos.page.refineResults.getRefinementName(uls[x].id);
			var isExpanded = argos.page.refineResults.isRefinementExpanded(refinementName, expandedRefinements);
			
			var lis = uls[x].getElementsByTagName('li');
			
			for (var y = 0; y < lis.length; y++) {
				if (y < listInitial || isExpanded) {
					lis[y].className = 'first4';
				}
				else if (y >= listInitial) {
					lis[y].className = 'therest';
					lis[y].style.display = 'none';
					
				}
			}
			if (listInitial < lis.length && !isExpanded) {
				var showMore = document.createElement('li');
				var showMorePlus = document.createTextNode('+ ');
				var showMoreSpan = document.createElement('span');
				var showMoreText = document.createTextNode('Show me more');
				showMore.appendChild(showMorePlus);
				showMoreSpan.appendChild(showMoreText);
				showMore.appendChild(showMoreSpan);
				showMore.className = 'showmore';
				showMoreSpan.onclick = function() { argos.page.refineResults.showHide(this.parentNode); }
				showMoreSpan.onfocus = function() { argos.page.refineResults.showHide(this.parentNode); }
				uls[x].appendChild(showMore);
			}
		}
	},
	
	// This function differs from the above setListClasses in the fact that it is only used in browse
	// and also caters for the differences when finder refinements have been enabled
	//
	// divName : The name of the div that contains the UL elements to update
	// ignoreFirst : The number of UL elements to ignore before making any updates at all
	// listInitial : The number of LI elements within each UL to display before cropping 
	// finderRefinementsEnabled : Whether the refinements displayed are defined as part of the finder finder 
	setListClassesBrowse : function(divName, ignoreFirst, listInitial, finderRefinementsEnabled) {
	
		var expandedRefinements = argos.page.refineResults.getExpandedRefinements();
	
		var leftCol = document.getElementById(divName);		
		var uls = leftCol.getElementsByTagName('ul');
		
		var startX = ignoreFirst;
		
		// If finder refinements have been enabled and the first UL isn't the Type List (linking to L4) 
		// then apply the updates to all the UL elements
		if (finderRefinementsEnabled && uls.length > 0 && !$(uls[0]).hasClass('bytypelist')) {
			startX = 0;
		}
		
		for (var x = startX; x < uls.length; x++) {
		
			var refinementName = argos.page.refineResults.getRefinementName(uls[x].id); 
			var isExpanded = argos.page.refineResults.isRefinementExpanded(refinementName, expandedRefinements);
			
			var lis = uls[x].getElementsByTagName('li');
			
			var showInitial = listInitial;
			
			if (finderRefinementsEnabled && $(uls[x]).hasClass('bycheckbox') ) {
			
				// If we are working with a set of finder refinements and the UL element has a class
				// of bycheckbox we need to change the showInitial value based on the cropAfterXRefinements
				// section of the UL id
				var cropAfterXRefinements = uls[x].id.substring(uls[x].id.lastIndexOf("_") + 1);
				
				if (cropAfterXRefinements.length == 0) {
					cropAfterXRefinements = lis.length;
				} else {
					cropAfterXRefinements = Number(cropAfterXRefinements);
				}
				
				showInitial = cropAfterXRefinements;
			}
			
			var addShowMeMore = false;
			
			for (var y = 0; y < lis.length; y++) {
				if (y < showInitial || isExpanded || (showInitial + 1 == lis.length) ) {
					lis[y].className = 'first4';
				}
				else if (y >= showInitial) {
					lis[y].className = 'therest';
					lis[y].style.display = 'none';
					addShowMeMore = true;
				}
			}
//			if (showInitial < lis.length && !isExpanded) {
			if (addShowMeMore) {
				var showMore = document.createElement('li');
				var showMorePlus = document.createTextNode('+ ');
				var showMoreSpan = document.createElement('span');
				var showMoreText = document.createTextNode('Show me more');
				showMore.appendChild(showMorePlus);
				showMoreSpan.appendChild(showMoreText);
				showMore.appendChild(showMoreSpan);
				showMore.className = 'showmore';
				showMoreSpan.onclick = function() { argos.page.refineResults.showHide(this.parentNode); }
				showMoreSpan.onfocus = function() { argos.page.refineResults.showHide(this.parentNode); }
				uls[x].appendChild(showMore);
			}
		}
	},
	
	// showHide function
	// Shows any hidden list items and hides link clicked
	showHide : function(targetLink) {
	
		var target = targetLink.parentNode;
		var list = target.getElementsByTagName('li');
		for (var i = 0; i < list.length; i++) {
	    	if(list[i].className == 'therest' && list[i].style.display == 'none') {
	      		list[i].style.display = 'block';
	        }
			if (list[i].className == 'showmore'){
				target.removeChild(targetLink);
			}
		}

		argos.page.refineResults.setShowHideCookie(target);
	},
	
	// setShowHideCookie function
	// Adds the target to the 'ExpandedRefinements' for the refinementCategory the user is in
	setShowHideCookie : function(target) {
		var refinementCategory = "";
		
		// Find the hidden elements in the form (the parent of the ul)
		var hiddenElements = $(":hidden", target.parentNode);
		
		for (var i = 0; i < hiddenElements.length && refinementCategory.length < 1; i++) {
			if (hiddenElements[i].name == "refinementCategory") {
				refinementCategory = hiddenElements[i].value;
			}
		}		

		if (refinementCategory.length < 1) {
			// We are not in a refinement category so don't set the cookie
			return;
		}
		
		
		var refinementCookie = argos.page.getCookie("Refinements");
		
		var expandedRefinements = "expanded:" + refinementCategory + "|";
		
		if (refinementCookie != null) {
		
			refinementCookie = argos.comms.url.decode(refinementCookie);
			
			var values = refinementCookie.split(";");
			
			for (var i = 0; i < values.length; i++) {
				
				if (values[i].indexOf("expanded:") == 0) {
				
					var category = values[i].substring("expanded:".length, values[i].indexOf("|"));
			
					if (category == refinementCategory) {
						expandedRefinements = values[i];
					}				

				}				
			}		
		}
		
		var refinement = argos.page.refineResults.getRefinementName(target.id);

		if (expandedRefinements.indexOf(refinement) < 0) {
			expandedRefinements += refinement + "|";
			
			var newCookieValue = "";
			
			if (refinementCookie == null) {
				newCookieValue = expandedRefinements;
			} else {
				
				var values = refinementCookie.split(";");
				
				// Add all the other refinement attributes to the cookie except 
				// the expanded attribute which gets added after with its new value
				for (var i = 0; i < values.length; i++) {
					if (values[i].indexOf("expanded:") != 0) {
						newCookieValue += values[i] + ";";
					}
				}
				
				newCookieValue += expandedRefinements;
				
			}
			
			argos.page.setCookie("Refinements", argos.comms.url.encode(newCookieValue));			
		}
	},
	
	// getExpandedRefinements function
	// Gets the names of the refinements the user has expanded for this refinementCategory
	getExpandedRefinements : function() {
	
		var refineResultsForm = document.getElementById("refineform");
		var refinementCategory = "";
		
		// Find the hidden elements in the form (the parent of the ul)
		var hiddenElements = $(":hidden", refineResultsForm);
		
		for (var i = 0; i < hiddenElements.length && refinementCategory.length < 1; i++) {
		
			if (hiddenElements[i].name == "refinementCategory") {
				refinementCategory = hiddenElements[i].value;
			}
		}		

		if (refinementCategory.length < 1) {
			// We are not in a refinement category so don't set the cookie
			return;
		}
		
		var refinementCookie = argos.page.getCookie("Refinements");
		
		var expandedRefinements = new Array();
		
		if (refinementCookie != null) {
		
			refinementCookie = argos.comms.url.decode(refinementCookie);
			
			var values = refinementCookie.split(";");
			
			for (var i = 0; i < values.length; i++) {
				
				if (values[i].indexOf("expanded:") == 0) {
				
					var category = values[i].substring("expanded:".length, values[i].indexOf("|"));
			
					if (category == refinementCategory) {
						
						var expandedValue = values[i].substring(values[i].indexOf("|") + 1);
			
	 					expandedRefinements = expandedValue.split("|");
					}				

				}				
			}		
		}
		
		return expandedRefinements;
	},
	
	// isRefinementExpanded function
	// Determines where or not the refinementName is an expanded refinement based on the list of expandedRefinements passed in
	isRefinementExpanded : function(refinementName, expandedRefinements) {
	
		var isExpanded = false;
		
		if (refinementName != null && expandedRefinements != null) {
			for (var i = 0; (i < expandedRefinements.length && !isExpanded); i++) {
				isExpanded = (expandedRefinements[i] == refinementName);
			}		
		}
		
		return isExpanded;
	},
	
	listConverter : function(jsonObj, divName) {
	
		if (jsonObj != null && jsonObj.refinementsEnabled) {
		
			
			var refinementForm = document.getElementById(divName);
			
			// Find the hidden elements in the form (the parent of the ul)
			var hiddenElements = $("input:hidden", refinementForm);
			// Find the action div to append after the refinements
			var actionDiv = $(refinementForm).find("div.action");
		
			$(refinementForm).html("");
			
			// Append all the hidden elements first
			for (var i = 0; i < hiddenElements.length; i++) {
						
				if (hiddenElements[i].name == 'customRefinementTypeCount') {
					$(refinementForm).append('<input type="hidden" value="' + jsonObj.refinements.length + '" name="customRefinementTypeCount"/>');
				} else if (hiddenElements[i].name == 'firstFinderRefinementOption') {
					$(refinementForm).append('<input type="hidden" value="' + jsonObj.firstFinderRefinementOption + '" name="firstFinderRefinementOption"/>');
				} else {
				$(refinementForm).append(hiddenElements[i]);
			}
			}
			
			var refinementValue = 0;
			
			for (var ref = 0; ref < jsonObj.refinements.length; ref++) {
			
				var refinement = jsonObj.refinements[ref];
					
				if (refinement != null && refinement != undefined && refinement.displayType != undefined) {
						
					refinementValue = refinementValue + 1;
					var inputName = 'r_' + argos.page.refineResults.padDigits(refinementValue, 3);
					
					var refinementsBeforeCropped = "";
						
					if (refinement.refinementsBeforeCropped != undefined) {
						refinementsBeforeCropped = refinement.refinementsBeforeCropped;
					}
					
					var jargonBusterTag = '';
					
					// Then apply any jargon buster text if it exists
					if (refinement.jargonBusterText != undefined) {
	
						jargonBusterTag = '<div class="tooltipflag" >';
						jargonBusterTag += '<img rel="tooltip_' + refinement.refineOptionId + '" src="/wcsstore/argos/en_US/images/icon_info.gif"  />';
						jargonBusterTag +='<div class="jargonBusterTooltip" id="tooltip_' + refinement.refineOptionId + '">'
						jargonBusterTag += '<div class="top"></div>'
						jargonBusterTag += '<div class="main">' + refinement.jargonBusterText + '</div>'
						jargonBusterTag += '</div>';
					
					}
					
					// We apply  header first (with jargon buster if needed)
					// If the refinement is a dropdown then we must create a label in the header otherwise it is created further down
					if (refinement.displayType == "REFINEMENT_SELECT_" || refinement.displayType == "REFINEMENT_HIERARCHY_") {
						$(refinementForm).append('<h4><label for="'+ refinement.refineOptionId + '">' + refinement.displayName + '</label>' + jargonBusterTag + '</h4>');				
					} else {
						$(refinementForm).append('<h4>' + refinement.displayName + jargonBusterTag + '</h4>');
					}


					// Now create the UL
					var ul = '<ul id="' + refinement.refineOptionId + '_' + refinementValue + '_' + refinementsBeforeCropped;

					ul += '" class="';
						
					if (refinement.displayType == "REFINEMENT_RADIO_") {

						ul += 'byradio">';
						
						if (refinement.refinementOptions.length > 0) {
							ul += '<li><input class="checkable" id="' + refinement.refineOptionId + '_Any" type="radio" name="' + inputName + '" value="" checked/><label class="refinementlabel" for ="' + refinement.refineOptionId + '_Any">Any</label></li>';
						}
						
						for (var j = 0; j < refinement.refinementOptions.length; j++) {	
							var refinementOption = refinement.refinementOptions[j];
							ul += '<li><input class="checkable" id="' + refinementOption.id + '" type="radio" name="' + inputName + '" value="' + refinementOption.option +'" /><label class="refinementlabel" for ="' + refinementOption.id + '">' + refinementOption.value + '</label></li>';
						}							
						
					} else if (refinement.displayType == "REFINEMENT_CHECKBOX_") {

						ul += 'bycheckbox">';
						
						for (var j = 0; j < refinement.refinementOptions.length; j++) {	
							var refinementOption = refinement.refinementOptions[j];
								
							ul += '<li><input class="checkable" id="' + refinementOption.id + '" type="checkbox" name="' + inputName + '" value="' + refinementOption.option +'" /><label class="refinementlabel" for ="' + refinementOption.id + '">' + refinementOption.value + '</label></li>';
								
							if (j < refinement.refinementOptions.length - 1) {
								refinementValue = refinementValue + 1;
								inputName = 'r_' + argos.page.refineResults.padDigits(refinementValue, 3);
							}
						}
							
					} else if (refinement.displayType == "REFINEMENT_LINK_") {

						ul += 'byattribute">';
					
						for (var j = 0; j < refinement.refinementOptions.length; j++) {	
							var refinementOption = refinement.refinementOptions[j];
							
							ul += '<li><a href="' + refinementOption.option + '">' + refinementOption.value + '</a><span>(' + refinementOption.count + ')</span></li>';
						}
	
					} else if (refinement.displayType == "REFINEMENT_SELECT_" || refinement.displayType == "REFINEMENT_HIERARCHY_") {
						
						ul += 'bydropdown">';
			           		
		           		if (refinement.displayType == "REFINEMENT_HIERARCHY_") {
							ul += '<li><select id="' + refinement.refineOptionId + '" class="hierarchyselect" name="' + inputName + '">';
						} else {
							ul += '<li><select id="' + refinement.refineOptionId + '" name="' + inputName + '">';
						}
		           		
		           		ul += '<option value="">' + refinement.unselectedAttribute + '</option>';
							
						if (refinement.displayType == "REFINEMENT_HIERARCHY_") {
							ul += '<option value="All">All</option>';	
						}
							
						for (var j = 0; j < refinement.refinementOptions.length; j++) {
							var refinementOption = refinement.refinementOptions[j];
							ul += '<option value="' + refinementOption.option + '">' + refinementOption.value + '</option>';	
						}

						ul += '</select></li>';
					}
						
					// Close the UL and append it to the form
					ul += '</ul>';
					$(refinementForm).append(ul);
				
				}
			
							
				
			}
			
			// Append the action div below the finders
			$(refinementForm).append(actionDiv);
			
			// ensure the count and Show button is displayed if necessary
			if (jsonObj.refinementCountEnabled) {
				$("#refineform div.action div.refinementresults").show();

				// handling enabled/disabled select box states							
				argos.page.refineResults.setSelectState($("form#refineform select.hierarchyselect"));
				argos.page.refineResults.resetValues();
				argos.page.refineResults.enableRefinementCount(); // in browse.js
			} else {
				argos.page.refineResults.enableFormCheck();
			}
	
			$("#refineform div.action").show();
			
			var targetTooltip, tooltipX, tooltipY, refineFormX, refineFormY;
			
			
			$("div.tooltipflag img").hover(
				function() {
			
					targetTooltip = $(this).attr("rel");
					$("#"+targetTooltip).bgiframe();
					$("#"+targetTooltip).show();
					
					if($.browser.msie && parseInt($.browser.version) == 6) {
						//based on height of parent h4 
						var ie6PosFix = $(this).parent().parent().height();
						$("#"+targetTooltip).css("bottom", ie6PosFix);			
					}
				},
				function() {
					$("#"+targetTooltip).hide();
				}
			);
		
			argos.page.refineResults.disableSubmit();
		}
	},

	padDigits : function(n, totalDigits) { 
		n = n.toString(); 
		var pd = ''; 
		if (totalDigits > n.length) { 
			for (i=0; i < (totalDigits-n.length); i++) { 
			    pd += '0'; 
			} 
		} 
		return pd + n.toString(); 
	},
	
	getRefinementName : function(refinementId) {
		// The ID of a refinement is made up using the following - refinementName_refinementSequence_cropAfterXRefinements
		// But the refinementName can contain _ themselves so need to work backwords removing the the last 2 _ from the id
		var refinementName = refinementId.substring(0, refinementId.lastIndexOf("_"));
		refinementName = refinementName.substring(0, refinementName.lastIndexOf("_"));
		
		return refinementName;
	},
	
	//PPK's find element position
	getPageX : function(obj) {
		var curleft = 0;
		if (obj.offsetParent) {
			while (obj.offsetParent) {curleft += obj.offsetLeft;obj = obj.offsetParent;}
		}
		else if (obj.x) curleft += obj.x;
		return curleft;
	},

	getPageY : function(obj) {
		var curtop = 0;
		if (obj.offsetParent) {
			while (obj.offsetParent) {curtop += obj.offsetTop;obj = obj.offsetParent;}
		}
		else if (obj.y) curtop += obj.y;
		return curtop;
	},
	
	setPageX : function(elem, pos) {
		elem.style.left = pos + "px";
	},

	setPageY : function(elem, pos) {
		elem.style.top = pos + "px";
	}
}