//
//-------------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// WebSphere Commerce
//
// (c) Copyright IBM Corp. 2007
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//-------------------------------------------------------------------
//

		dojo.registerModulePath("wc", "wc");

		//AJAX request support
		dojo.require("dojo.io.*");
			
		//product quick view with tooltip widget
		dojo.require("wc.widget.ProductQuickView");
		dojo.require("wc.widget.BaseContent");
		dojo.require("wc.widget.ToolTipContent");
		
		//category menu support
		dojo.require("dojo.widget.Button");
		dojo.require("dojo.widget.Menu2");

		//range slider widget
		dojo.require("wc.widget.RangeSlider");
				
		//reload widgets when parts of the page has been re-loaded from server
		dojo.require("dojo.xml.Parse");
			
		//publish and subscribe event support
		dojo.require("dojo.event.*");

		//back, forward and bookmarking
		dojo.require("dojo.undo.browser");

		//scrollable pane
		dojo.require("wc.widget.ScrollablePane");
		dojo.require("dojo.animation.*");
		dojo.require("dojo.lfx.*");
		dojo.require("dojo.string.extras");
		dojo.require("dojo.collections.ArrayList");
		

		/**********************************************************
		* Function to create a WC product object with useful parameters for the Web 2.0 store.
		**********************************************************/	
		function WCProduct() 
		{
				this.catentryId = "";
				this.SKU = "";
				this.name = "";
				this.identifierCounter = "";
				this.shortDescription = "";
				this.longDescription = "";
				this.largeImageSrc = "";
				this.mediumImageSrc = "";
				this.detailImageSrc = "";
				this.price = "";
				this.size = new Array();
				this.flavors = new Array();
				this.productDisplayURL = "";
				this.dragSourceType = "";
				this.baseContentHTML = "";
				this.toolTipHTML = "";
				this.inStock = "";
				this.itemCatentryIds = new Array();
				this.itemPrices = new Array();
		}

	fastFinderJS={
		totalResultsMessage : "UNDEFINED",
		pagingMessage : "UNDEFINED",
		pagingMessage2 : "UNDEFINED",
		pagingMessage3 : "UNDEFINED",

		catalogEntriesResultSet : new Vector(),
		catalogEntriesByPrice : new Vector(),
		catalogEntriesByName : new Vector(),
		

		pageSize : 0 ,
		resultsPerRow : 3,
		displayCounter : 0,
		displayRowCounter : 0,
		totalProductsInCategory : "UNDEFINED",
		productIdentifierString : "catBrowse",

		catalogEntriesResultSetTotal : 0,
		catalogEntriesResultSetTotalPages : 0,
		catalogEntriesResultSetCurrentPageNumber : 0,
		displayTotal : this.pageSize,
		beginIndex : 0,
		prevIndex : null, 
		nextIndex : null,

		imagePath : "UNDEFINED",
		viewType : "image",
		storeId : "UNDEFINED",
		catalogId : "UNDEFINED",
		sizesSelected : "",
		flavorsSelected : "",
		woflavorsSelected : "",
		reVisit : "",
		
		

		/**********************************************************
		* Function to create a ProductQuickView widget using JavaScript. 
		*
		*	Parameters:
		*	productObj - the WC product object
		* identifierString - the identifier of the catalog entry element
		* imageSize - the size of the image
		* showCompare - show the compare icon in the tooltip
		* imagePath - the image path
		* viewType - "image" or "detailed" view
		* storeId - the store id
		* catalogId - the catalog id
		**********************************************************/
		createProductWidget : function(parentObject, productObj, identifierString, imageSize, showCompare, imagePath, viewType, storeId, catalogId,sizesSelected,flavorsSelected,beginIndex) 
		{
				var _id = identifierString + productObj.identifierCounter;
				var widgetHTML = ""
				var argOrderBy1=document.FastFinderForm.orderBy1.value;
				var argOrderByOperator1 = document.FastFinderForm.orderByOperator1.value;
				var argHrefParams = "&sizesSelected="+sizesSelected+"&flavorsSelected="+flavorsSelected+"&beginIndex="+beginIndex+"&pageView="+viewType+"&orderBy1="+argOrderBy1+"&orderByOperator1="+argOrderByOperator1;
				
				if(productObj.baseContentHTML == null || productObj.baseContentHTML == ""){
					
					if(productObj.mediumImageSrc == "") productObj.mediumImageSrc = imagePath + "NoImageIcon_sm.jpg";

					var _baseContentImgSrc = productObj.mediumImageSrc
					var _baseContentNamePrice = "";
					var _baseContentNameTD = "";
					var _baseContentPriceTD = "";
					var _addToCartString = "";

					if (viewType == "image") {
						_baseContentNamePrice = ""
												+"<div id='"+ _id + "Td' align='center' >\n"
												+"	<div class=\"imgWrapper\" id='"+ _id + "'>\n"
												+"		<a id='imgcatBrowse"+ _id + "' href='"+ productObj.productDisplayURL +argHrefParams+"' >\n"
												+"			<img src='"+ _baseContentImgSrc +"' alt='"+ productObj.shortDescription +"' border='0' height='120' width='150'/>\n"
												+"		</a>\n"
												+"	</div>\n"
												+"		<p class=\"gridDescription\">\n"
												+"			<a href=\"" + productObj.productDisplayURL +argHrefParams+"\">" + productObj.name + "</a>\n"
												+"		</p>\n";
	                        			for( var i = 0; i < productObj.itemPrices.length; i++ ) {
	                        				addToCartClass = "";
	                        					if( productObj.sizes[i].indexOf("10") >= 0 ) {
		                        					addToCartClass = "		<div class=\"bt_AddToCart10\">\n";
	                        					} else {
		                        					addToCartClass = "		<div class=\"bt_AddToCart7\">\n";
	                        					}

	                        				_addToCartString = ""
	                        					+ addToCartClass
												+"			<a href=\"javascript:toggleon('cartWidgetWrapper'); Add2ShopCartAjax(" + productObj.itemCatentryIds[i] + ", " + storeId + ", " + catalogId + ", -1); setToggleTimeOut();\" title=\"Add to cart\">\n"
												+			productObj.sizes[i] + " |  " + productObj.itemPrices[i]
	                        					+"				<div class=\"bt_AddToCart_AddButton\"><span>Add To Cart</span></div>\n"
	                        					+"			</a>\n"
	                        					+"		</div>\n";

	                        				_baseContentNamePrice = _baseContentNamePrice + _addToCartString;
	                        			}
						_baseContentNamePrice = _baseContentNamePrice 
												+"</div>\n";
					} 
					else if (viewType == "detailed") 
					{
						_baseContentNamePrice = ""
											
											+"	<div class=\"listItem\"><div id='"+ _id + "' class=\"listImage\">\n"
											+"		<a id='imgcatBrowse"+ _id + "' href='"+ productObj.productDisplayURL +argHrefParams+"' >\n"
											+"			<img src='"+ _baseContentImgSrc +"' alt='"+ productObj.shortDescription +"' border='0' height='120' width='150'/>\n"
											+"		</a>\n"
											+"	</div>\n"
											+"	<div class=\"listDescription\" id='"+ _id +"NameTd'>\n"
											+"		<a href=\"" + productObj.productDisplayURL +argHrefParams+"\"><strong>" + productObj.name + "</strong></a>\n"
											+"		<p>\n"
											+"		" + productObj.shortDescription + "\n"
											+"		</p>\n"
											+"	</div>\n"
											+"		<div class=\"listInfo\">\n"
	                        		for( var i = 0; i < productObj.itemPrices.length; i++ ) {
	                        				addToCartClass = "";
	                        					if( productObj.sizes[i].indexOf("10") >= 0 ) {
		                        					addToCartClass = "		<div class=\"bt_AddToCart10\">\n";
	                        					} else {
		                        					addToCartClass = "		<div class=\"bt_AddToCart7\">\n";
	                        					}

	                        				_addToCartString = ""
	                        					+ addToCartClass
												+"			<a href=\"javascript:toggleon('cartWidgetWrapper'); Add2ShopCartAjax(" + productObj.itemCatentryIds[i] + ", " + storeId + ", " + catalogId + ", -1); setToggleTimeOut();\" title=\"Add to cart\">\n"
												+			productObj.sizes[i] + " |  " + productObj.itemPrices[i]
	                        					+"				<div class=\"bt_AddToCart_AddButton\"><span>Add To Cart</span></div>\n"
	                        					+"			</a>\n"
	                        					+"		</div>\n";
	                        				_baseContentNamePrice = _baseContentNamePrice + _addToCartString;
	                        			}
						_baseContentNamePrice = _baseContentNamePrice 
											
											+"		</div>\n"
											+"	</div>\n";
										
					}

					widgetHTML = _baseContentNamePrice;
				}else{
					widgetHTML = productObj.baseContentHTML;
				}
				var div = document.createElement("div");
				parentObject.appendChild(div);
								
				// create the ProductQuickView
				var productQuickViewWidget = dojo.widget.createWidget("ProductQuickView", {
																							id: "productQuickView" + productObj.identifierCounter,
																							defaultContent: false,
																							identifier: _id
																							}, div);

				var topDiv = document.createElement("div");
				productQuickViewWidget.domNode.appendChild(topDiv);

				var baseContentWidget = dojo.widget.createWidget("BaseContent", {
																					id: "productQuickViewBase" + productObj.identifierCounter,
																					dragSourceId: _id,
																					dragSourceType: productObj.dragSourceType,
																					catentryId: productObj.catentryId,
																					userInnerHtml: widgetHTML
																					}, topDiv);
				
				var tooltipDiv = this.createProductToolTipWidget(productQuickViewWidget.domNode, productObj, identifierString, showCompare, imagePath, storeId, catalogId);
		},

		/**********************************************************
		* Function to create a product tool tip.
		**********************************************************/
		createProductToolTipWidget : function(parentObject, productObj, identifierString, showCompare, imagePath, storeId, catalogId) 
		{
				var _id = identifierString + productObj.identifierCounter;
				var widgetHTML = "";
				var _addToCartString = "";

				if(productObj.toolTipHTML == null || productObj.toolTipHTML == ""){
					var _productToolTipCompareLink = ""
					if (showCompare) {
						_productToolTipCompareLink = ""
													+"	<a id='comparelink"+ productObj.identifierCounter + "' href='javascript: Add2CompareAjax(\"" + productObj.catentryId + "\");'  >\n"
													+"		<img src='"+ imagePath  +"compare.gif' alt='compare' border='0' className='popup_iconimages' class='popup_iconimages' />\n"
													+"	</a>\n";
					}

					widgetHTML = ""	
									+"			<div id=\"productQuickView\">\n"
									+"				<div class=\"productInfoBox\">\n"
									+"				<a href=\"" + productObj.productDisplayURL +"\" id=\"productName\">" + productObj.name + "</a><br>\n"
									+"				<p class=\"productInfo\" id=\"productInfo\">" + productObj.longDescription +"</p>\n";
	                        			for( var i = 0; i < productObj.itemPrices.length; i++ ) {
	                        				addToCartClass = "";
	                        					if( productObj.sizes[i].indexOf("10") >= 0 ) {
		                        					addToCartClass = "		<div class=\"bt_AddToCart10\">\n";
	                        					} else {
		                        					addToCartClass = "		<div class=\"bt_AddToCart7\">\n";
	                        					}

	                        				_addToCartString = ""
	                        					+ addToCartClass
												+"			<a href=\"javascript:toggleon('cartWidgetWrapper'); Add2ShopCartAjax(" + productObj.itemCatentryIds[i] + ", " + storeId + ", " + catalogId + ", -1); setToggleTimeOut();\" title=\"Add to cart\">\n"
												+			productObj.sizes[i] + " |  " + productObj.itemPrices[i]
	                        					+"				<div class=\"bt_AddToCart_AddButton\"><span>Add To Cart</span></div>\n"
	                        					+"			</a>\n"
	                        					+"		</div>\n";
	                        				widgetHTML = widgetHTML + _addToCartString;
	                        			}
					widgetHTML = widgetHTML 
									+"				</div>\n"
									+"				<div><img class=\"productHopUpHeroImage\" alt=\"" + productObj.name + "\" src=\"" + productObj.largeImageSrc + "\"/>\n"
									+"				<img class=\"productHopUpInsetImage\" alt=\"" + productObj.name + "\" src=\"" + productObj.detailImageSrc + "\" width='210px' height='168px'></div>"
									+"			</div>\n";

				}else{
					widgetHTML = productObj.toolTipHTML;
				}

				var div = document.createElement("div");
				parentObject.appendChild(div);
				var toolTipContentWidget = dojo.widget.createWidget("ToolTipContent", {
																					id: "productToolTip" + productObj.identifierCounter,
																					connectId: _id,
																					toggleDuration: "250",
																					userInnerHtml:widgetHTML
																					}, div);
		},


		addElementToVector : function(targetVector, catentryId, SKU, name, identifierCounter, shortDescription, longDescription, largeImageSrc, mediumImageSrc, 
									detailImageSrc, price, displayPrice, productDisplayURL, dragSourceType, flavorsArray, sizesArray, baseContentHTML, toolTipHTML, inStock, itemPricesArray, itemCatentryIdsArray){
			
			var wcProduct = new WCProduct();
			wcProduct.catentryId = catentryId;
			wcProduct.SKU = SKU;
			wcProduct.name = name;
			wcProduct.identifierCounter = identifierCounter;
			wcProduct.shortDescription = shortDescription;
			wcProduct.longDescription = longDescription;
			wcProduct.largeImageSrc = largeImageSrc;
			wcProduct.mediumImageSrc = mediumImageSrc;
			wcProduct.detailImageSrc = detailImageSrc;			
			wcProduct.price = price;
			wcProduct.displayPrice = displayPrice;
			wcProduct.productDisplayURL = productDisplayURL;
			wcProduct.dragSourceType = dragSourceType;
			wcProduct.flavors = flavorsArray;
			wcProduct.sizes = sizesArray;			
			wcProduct.baseContentHTML = baseContentHTML;
			wcProduct.toolTipHTML = toolTipHTML;
			wcProduct.inStock = inStock;
			wcProduct.itemCatentryIds = itemCatentryIdsArray;
			wcProduct.itemPrices = itemPricesArray;

			targetVector.addElement(wcProduct);
		},

		
		showResults : function(filterAction) {
			this.viewType = document.FastFinderForm.pageView.value;
			this.sizesSelected = document.FastFinderForm.sizesSelected.value;
			this.flavorsSelected = document.FastFinderForm.flavorsSelected.value;			
			this.woflavorsSelected = document.FastFinderForm.woflavorsSelected.value;			
			this.reVisit = document.FastFinderForm.reVisit.value;
			if (document.FastFinderForm.pageView.value =="image") {
				this.pageSize = 12;
			} else {
				this.pageSize = 12;				
			}

			cursor_wait();
			//destroy only catalog browsing widgets
			dojo.lang.forEach(dojo.widget.byType("ProductQuickView"), function(widget) {
				tempStr = widget.identifier;
				tempStr = tempStr.substring(0,9);
				if (tempStr == this.productIdentifierString) {
					widget.destroy();
				}
			});
			
			//destroy all HTML in the results division
			//initialize global variables
			var productObj = null;
				
			var fastFinderResultsDiv = document.getElementById("fastFinderResults");
			for (j=0; j<fastFinderResultsDiv.childNodes.length; j++) {
				fastFinderResultsDiv.removeChild(fastFinderResultsDiv.childNodes[j]);
			}
			this.displayCounter = 0;
			this.displayRowCounter = 0;
			

				this.generateResultSet(filterAction);
				this.showTotalResultsMessage();
				this.showPagingMessage();
				this.showPagingMessage2();
				this.showPagingMessage3();
				
			if (this.catalogEntriesResultSetTotal == 0) {			
				showErrorMessage("","noResults");
			} else {
				hideErrorMessage("","noResults","");
			}

			
			//create new product quick view HTML for the new result set and display them
			var lasttr1= null;
			
			for (i=parseInt(beginIndex); i<(parseInt(beginIndex) + parseInt(this.displayTotal)); i++) {
				
				this.displayCounter++;
				productObj = this.catalogEntriesResultSet.elementAt(i);
	
				if (this.viewType == "image") {
					var td1 = document.createElement("li");
					td1.setAttribute("id", "browseCatEntry"+i);
					if (((this.displayCounter-1) % this.resultsPerRow) == 0 ) {
						this.displayRowCounter++;
						
						var tr1 = document.createElement("ul");
						tr1.setAttribute("id", "displayRow"+this.displayRowCounter);
					} else {
						var tr1 = document.getElementById("displayRow"+this.displayRowCounter);
					}
				} else if (this.viewType == "detailed") {
					var td1 = document.createElement("div");
					td1.setAttribute("id", "browseCatEntry"+i);
					this.displayRowCounter++;
					var tr1 = document.createElement("div");
					tr1.setAttribute("id", "displayRow"+this.displayRowCounter);
				}
				lasttr1 = tr1
				
				
				tr1.appendChild(td1);
				
				if (i%this.pageSize == 0) {
					var table1 = document.createElement("div");
					if (this.viewType == "image") 
						table1.setAttribute("id", "gridViewContainer");
					else if (this.viewType == "detailed") 
						table1.setAttribute("id", "listViewContainer");
				
					table1.appendChild(tr1);
					fastFinderResultsDiv.appendChild(table1);
				} else {
					if (this.viewType == "image")
						var tbody1 = document.getElementById("gridViewContainer");
					else if (this.viewType == "detailed") 
						var tbody1 = document.getElementById("listViewContainer");
					tbody1.appendChild(tr1);
				}
				if (productObj != null) {
					this.createProductWidget(td1,productObj, this.productIdentifierString, "medium", false, this.imagePath, this.viewType, this.storeId, this.catalogId,this.sizesSelected,this.flavorsSelected,beginIndex);
				}
			}
			
			if (lasttr1 !=null) {
				if (this.viewType == "image")
						lasttr1.setAttribute("class","last");
			}
			
			
			// let Dojo parse the whole results division to create the widgets from HTML


			//Parsing is slowing down the operation and with the modified code we don't need it, so commented..
			//var testObj = new dojo.xml.Parse();
			//var testObjects = testObj.parseElement(document.getElementById("fastFinderResults"));
			//var testParse = dojo.widget.getParser();
			//testParse.createComponents(testObjects);

			cursor_clear();
			
			//Save in History
			//var historyObject = new HistoryTracker(document.getElementById('fastFinder_div').innerHTML, 'fastFinder_div');
			//dojo.undo.browser.addToHistory(historyObject);
		},
		
		//
		// Generate the result set based on user input. Set the helper global javascript variables.
		//
		generateResultSet : function(filterAction) {
			
			if (document.FastFinderForm.initialState.value == "false") {
				
				var tempList = null;
				if (filterAction != "beginIndex" && filterAction != "view") {
					
					beginIndex = document.FastFinderForm.beginIndex.value;					
					// re-build the result set based on criterias selected by user
					this.catalogEntriesResultSet = new Vector();
					//this.catalogEntriesResultSet.removeAllElements();
					
					// 1. Get the initial sorted list by price or by size
					if (document.FastFinderForm.orderBy1.value == "OfferPricePrice") {
							tempList = this.catalogEntriesByPrice;
					} else {
							tempList = this.catalogEntriesByName;
					}
					
					// 2. Eliminate entries based on selected criterias
					var minPrice = parseFloat(document.FastFinderForm.minPrice.value);
					var maxPrice = parseFloat(document.FastFinderForm.maxPrice.value);
					
					var sizes = new Vector();					
					var diffSizes = document.SizeNamesForm.elements;
					
					if (this.reVisit != "true") {
						this.flavorsSelected = "";
						this.woflavorsSelected = "";
						this.sizesSelected = "";
					}
					
					for (i=0; i<diffSizes.length; i++) {
						if (diffSizes[i].checked) {		
							sizes.addElement(diffSizes[i].value);
							if (this.reVisit != "true") {
								this.sizesSelected += diffSizes[i].value;								
							}
							
						}
					}
					
					var flavorNames = new Vector();
					var woflavorNames = new Vector();
					var flavorsElements = document.FlavorsNamesForm.elements;
	
					for (i=0; i<flavorsElements.length; i++) {
						if ( flavorsElements[i].name.indexOf("flavorName") == 0 && flavorsElements[i].checked) {
							flavorNames.addElement(flavorsElements[i].value);
							if (this.reVisit != "true") {
								this.flavorsSelected += "|"+flavorsElements[i].value;
							}
						}
						if ( flavorsElements[i].name.indexOf("woflavorName") == 0 && flavorsElements[i].checked) {
							woflavorNames.addElement(flavorsElements[i].value);
							if (this.reVisit != "true") {
								this.woflavorsSelected += "|"+flavorsElements[i].value;
							}
						}
					}	
					
					this.flavorsSelected += "|"	
					this.woflavorsSelected += "|"					
					
					//Push updated sizes back to form.
					document.FastFinderForm.sizesSelected.value = this.sizesSelected;
					document.FastFinderForm.flavorsSelected.value = this.flavorsSelected;
					document.FastFinderForm.woflavorsSelected.value = this.woflavorsSelected;
			 		if (document.FastFinderForm.orderByOperator1.value == "descending") {
						for (i=tempList.size()-1; i>-1; i--) {
							var hasPrice = false;
							var hasSize = false;
							var hasFlavor = false;
							//check price
							var productObjNew = tempList.elementAt(i);
							
							if (productObjNew.price >= minPrice && productObjNew.price <= maxPrice && productObjNew.price > 0.00) {
								hasPrice = true;
							}
							
							//check size and features to display
							for (f=0; f<productObjNew.sizes.length; f++) {
								if (this.reVisit =="true") {
									
									if (this.sizesSelected == "" || this.sizesSelected.indexOf(productObjNew.sizes[f]) != -1) {
										hasSize = true;
										break;
									}
								} else if (sizes.contains(productObjNew.sizes[f]) || this.sizesSelected == "") {
									hasSize = true;
									break;
								}
							}
							//Since gift cards have no attributes.  
							if (productObjNew.sizes.length == 0) {
								hasSize = true;
							}
								
						    if (flavorNames.size() != 0) {
						    	for (f=0; f<flavorNames.size(); f++) {
						    		for (p=0; p<productObjNew.flavors.length; p++) {
						    			if (productObjNew.flavors[p] == flavorNames.elementAt(f)) {							    			
						    				hasFlavor = true;
						    				break;
						    			}else{
						    				hasFlavor = false;
						    			}
						    		}							    
						    		if (!hasFlavor) break;
						    	}
						    } else {
						    	hasFlavor = true;
						    } 

						    if (hasFlavor && woflavorNames.size() != 0) {
						    	for (f=0; f<woflavorNames.size(); f++) {
						    		for (p=0; p<productObjNew.flavors.length; p++) {							    	
						    			if (productObjNew.flavors[p] == woflavorNames.elementAt(f)) {							    			
						    				hasFlavor = false;
						    				break;
						    			}else{
						    				hasFlavor = true;
						    			}
						    		}							    
						    		if (!hasFlavor) break;
						    	}
						    }
						    
						    //Since gift cards have no attributes.
						    if (productObjNew.flavors.length == 0) {
								if (flavorNames.size() != 0) { 
									hasFlavor = false;
								} else {
						    	hasFlavor = true;
								}
						    }
						    													
							if(hasPrice && hasFlavor && hasSize) {
								this.catalogEntriesResultSet.addElement(productObjNew);
							}	
									
						}
					} else {				
						for (i=0; i<tempList.size(); i++) {
							var hasPrice = false;
							var hasSize = false;
							var hasFlavor = false;
							//check price
							var productObjNew = tempList.elementAt(i);
							if (productObjNew.price >= minPrice && productObjNew.price <= maxPrice && productObjNew.price > 0.00) {
								hasPrice = true;
							}
								
							//check size and features to display
							for (f=0; f<productObjNew.sizes.length; f++) {
								if (this.reVisit =="true") {										
									if (this.sizesSelected == "" || this.sizesSelected.indexOf(productObjNew.sizes[f]) != -1) {
										hasSize = true;
										break;
									}
								} else if (sizes.contains(productObjNew.sizes[f])|| this.sizesSelected == "") {
									hasSize = true;
									break;
								}
							}
							//Since gift cards have no attributes.
							if (productObjNew.sizes.length == 0) {
								hasSize = true;
							}

						    if (flavorNames.size() != 0) {
						    	for (f=0; f<flavorNames.size(); f++) {
						    		for (p=0; p<productObjNew.flavors.length; p++) {							    	
						    			if (productObjNew.flavors[p] == flavorNames.elementAt(f)) {							    			
						    				hasFlavor = true;
						    				break;
						    			}else{
						    				hasFlavor = false;
						    			}
						    		}							    
						    		if (!hasFlavor) break;
						    	}
						    } else {
						    	hasFlavor = true;
						    }

						    if (hasFlavor && woflavorNames.size() != 0) {
						    	for (f=0; f<woflavorNames.size(); f++) {
						    		for (p=0; p<productObjNew.flavors.length; p++) {							    	
						    			if (productObjNew.flavors[p] == woflavorNames.elementAt(f)) {							    			
						    				hasFlavor = false;
						    				break;
						    			}else{
						    				hasFlavor = true;
						    			}
						    		}							    
						    		if (!hasFlavor) break;
						    	}
						    }

						    //Since gift cards have no attributes.
						    if (productObjNew.flavors.length == 0) {
								if (flavorNames.size() != 0) { 
									hasFlavor = false;
								} else {
						    	hasFlavor = true;
								}
						    }
									
							if (hasPrice && hasFlavor && hasSize) {										
								this.catalogEntriesResultSet.addElement(productObjNew);
							}						
						}
					}
				}
			} else {
				this.catalogEntriesResultSet = new Vector();
				
				for (k=0; k<this.catalogEntriesByName.size(); k++) {
					var productObjNew = this.catalogEntriesByName.elementAt(k);
//					if (productObjNew.price > 0.00) {
						this.catalogEntriesResultSet.addElement(productObjNew);
//					}
				}
                            
				var viewsTR = document.getElementById("viewsTR");
				var viewTypeTD2 = document.getElementById("viewTypeTD2");
				var viewTypeTD1 = document.getElementById("viewTypeTD1");
				if(viewsTR != null && viewTypeTD2 != null && viewTypeTD1 != null){
					viewsTR.removeChild(viewTypeTD2);
				}
			}
			
			// 3. Set all totals based on current result set and beginIndex
			this.catalogEntriesResultSetTotal = this.catalogEntriesResultSet.size();
			this.catalogEntriesResultSetTotalPages = Math.ceil(this.catalogEntriesResultSetTotal/this.pageSize);
			this.catalogEntriesResultSetCurrentPageNumber = Math.floor(beginIndex/this.pageSize) + 1;
			if (this.catalogEntriesResultSetTotal < (this.catalogEntriesResultSetCurrentPageNumber*this.pageSize)) {
				this.displayTotal = (parseInt(this.catalogEntriesResultSetTotal)-parseInt(beginIndex));
			} else {
				this.displayTotal = this.pageSize;
			}
			
			if (beginIndex == 0) {
				prevIndex = 0;
			} else {
				prevIndex = parseInt(beginIndex)-parseInt(this.pageSize);
			}
			if ( (parseInt(beginIndex)+parseInt(this.displayTotal)) >= parseInt(this.catalogEntriesResultSetTotal)) {
				nextIndex = beginIndex;
			} else {
				nextIndex = parseInt(beginIndex)+parseInt(this.displayTotal);
			}
			
		},
	
		showTotalResultsMessage : function() {
			var resultsTD = document.getElementById("totalResultsMessageDisplay");
			
			if(resultsTD != null){
				var text = this.totalResultsMessage;
				text = text.replace(/%0/, this.catalogEntriesResultSetTotal);
				text = text.replace(/%1/, this.totalProductsInCategory);
				var textNode = document.createTextNode(text);
				
				if (resultsTD.childNodes.length == 1) {
					resultsTD.removeChild(resultsTD.firstChild);
				}
				resultsTD.appendChild(textNode);
			}else{
				dojo.debug("totalResultsMessageDisplay"+" element is missing");
			}
		},
		
		showPagingMessage : function() {
			var resultsTDTop = document.getElementById("pagingMessageDisplayTop");
			var text = this.pagingMessage;
			
			text = text.replace(/%0/, this.catalogEntriesResultSetTotal);
			if (this.catalogEntriesResultSetTotal == "0") {
				text = text.replace(/%1/, "0");
			} else {
				text = text.replace(/%1/, parseInt(beginIndex)+1);
			}
			
			text = text.replace(/%2/, parseInt(beginIndex)+parseInt(this.displayTotal));
			text = text.replace(/%3/, this.catalogEntriesResultSetTotal);
			
			resultsTDTop.innerHTML = text;
		},

		showPagingMessage2 : function() {
			var resultsTDTop = document.getElementById("pagingMessage2DisplayTop");
			var resultsTDBottom = document.getElementById("pagingMessage2DisplayBottom");
		  	var text ="";
		  	var currPage = parseInt(beginIndex)/parseInt(this.pageSize) + 1;
  	
		  	if (currPage == 1) {
		  		document.getElementById("prevLink1").style.display = "none";
		  		document.getElementById("prevLink2").style.display = "none";
		  	} else {
		  		document.getElementById("prevLink1").style.display = "inline";
		  		document.getElementById("prevLink2").style.display = "inline";	  	
		  	}
		  	
		  	for (var j=1; j<this.catalogEntriesResultSetTotalPages+1; j++) {
		  		if (j==currPage) {
		  			text= text+j+" ";
		  		}else{
		  			text= text+"<a href='javascript: filterWithSelectedIndex(\"" + j +"\")'>" + j +"</a> ";
		  		}
		  	}
		  	
		  	if ((parseInt(beginIndex) + parseInt(this.pageSize)) >= parseInt(this.catalogEntriesResultSetTotal)) {
		  		document.getElementById("nextLink1").style.display = "none";
		  		document.getElementById("nextLink2").style.display = "none";
		  	} else {
		  		document.getElementById("nextLink1").style.display = "inline";
		  		document.getElementById("nextLink2").style.display = "inline";
		  	}
		  	
		  	resultsTDTop.innerHTML = text;
		  	resultsTDBottom.innerHTML = text;
		},

		showPagingMessage3 : function() {
			var resultsTDBottom = document.getElementById("pagingMessageDisplayBottom");
			var text = this.pagingMessage3;
			text = text.replace(/%0/, this.catalogEntriesResultSetTotal);
			if (this.catalogEntriesResultSetTotal == "0") {
				text = text.replace(/%1/, "0");
			} else {
				text = text.replace(/%1/, parseInt(beginIndex)+1);
			}
			text = text.replace(/%2/, parseInt(beginIndex)+parseInt(this.displayTotal));
			text = text.replace(/%3/, this.catalogEntriesResultSetTotal);
			resultsTDBottom.innerHTML = text;
		},
		
		filterResultsWithPrice : function(_this){
			values = _this.getCurrentValues();
			this.filterResultsWithPriceRange(values.upper, values.lower);
		},

		filterResultsWithPriceRange : function(upper, lower){
			document.FastFinderForm.maxPrice.value = upper;
			document.FastFinderForm.minPrice.value = lower;
			document.FastFinderForm.initialState.value = "false";
			
			this.showResults("price");
		},

		filterResultsWithView : function(view){
			document.FastFinderForm.pageView.value = view;
			this.viewType = view;
			document.FastFinderForm.initialState.value = "false";
					
			var viewsdiv = document.getElementById("viewsdiv");
			
			if (this.viewType == "image") {
				viewsdiv.innerHTML = "<p><strong>View as:</strong>  <strong>Grid</strong>  |  <a href=\"javascript: filterWithView('detailed');\" title=\"List\">List</a></p>";
			} else if (this.viewType == "detailed") {
				viewsdiv.innerHTML = "<p><strong>View as:</strong>  <a href=\"javascript: filterWithView('image');\" title=\"Grid\">Grid</a>  |  <strong>List</strong></p>";
			}
			
			this.showResults("view");
		},

		filterResultsWithPrevIndex : function(){
			document.FastFinderForm.beginIndex.value = prevIndex;
			beginIndex = prevIndex;
			document.FastFinderForm.initialState.value = "false";
			document.FastFinderForm.reVisit.value = "false";
			this.showResults("beginIndex");
		},

		filterResultsWithNextIndex : function(){
			document.FastFinderForm.beginIndex.value = nextIndex;
			beginIndex = nextIndex;
			document.FastFinderForm.initialState.value = "false";
			document.FastFinderForm.reVisit.value = "false";
			
			this.showResults("beginIndex");
		},
		filterResultsWithSelectedIndex : function(argIndex){
			
			var x = (argIndex-1)*this.pageSize;
			document.FastFinderForm.beginIndex.value = x;
			beginIndex = x;
			document.FastFinderForm.initialState.value = "false";
			document.FastFinderForm.reVisit.value = "false";
			this.showResults("beginIndex");
		},
		filterResultsWithOrderBy : function(orderBy){
			if (orderBy == "OfferPricePriceLH") {
				document.FastFinderForm.orderBy1.value = "OfferPricePrice";
				document.FastFinderForm.orderByOperator1.value = "ascending";
			} else if (orderBy == "OfferPricePriceHL") {
				document.FastFinderForm.orderBy1.value = "OfferPricePrice";
				document.FastFinderForm.orderByOperator1.value = "descending";
			} else if (orderBy == "CatEntDescNameAZ") {
				document.FastFinderForm.orderBy1.value = "CatEntDescName";
				document.FastFinderForm.orderByOperator1.value = "ascending";
			} else if (orderBy == "CatEntDescNameZA") {
				document.FastFinderForm.orderBy1.value = "CatEntDescName";
				document.FastFinderForm.orderByOperator1.value = "descending";
			}	
			document.FastFinderForm.initialState.value = "false";
			document.FastFinderForm.reVisit.value = "false";
			document.FastFinderForm.beginIndex.value = 0;
			beginIndex = 0;
			this.showResults("orderBy");
		},

		filterResultsWithSizes : function(){
			document.FastFinderForm.initialState.value = "false";
			document.FastFinderForm.reVisit.value = "false";
			document.FastFinderForm.beginIndex.value = 0;
			this.showResults("size");
		},

		filterResultsWithFlavors : function(){
			document.FastFinderForm.initialState.value = "false";
			document.FastFinderForm.reVisit.value = "false";
			document.FastFinderForm.beginIndex.value = 0;
			this.showResults("flavors");
		},


		add2History : function(actionArray, formArray, url){
			//each entry in the history stack need have unique value. so we need attach a timestamp after each url.
			if(url == null || url =="")
				url = "identifier=" + (new Date()).getTime();

			var historyObject = new fastFinderJS.HistoryTracker(actionArray, formArray, url);
			dojo.undo.browser.addToHistory(historyObject);	
		},

		
		HistoryTracker:function(actionArray, formArray, changeUrl){
			// summary: History state object for history tracking
			// description:History state object for history tracking
			// workAreaModeValue: String
			//		the html to be displayed
			// elementId: String
			//		the name of the DOM object
			// changeUrl: String
			//		the url for the current state of this page
			this.actionArray = null;
			this.formArray = null;
			
			this.actionArray = actionArray;
			this.formArray = formArray;

			//TODO: commenting this out breaks FF 1.5. Others? Can't seem to find iframe id/name?
			this.changeUrl =  changeUrl;
		},

		processBookmarkURL : function(){
		// summary: This function is for handling bookmarked urls
		// Description: If there is bookmark information in the url, extract the url after #. 
		//              update context for MyAccountCenterLinkDisplay_Context with the bookmarked url.
					 
			var bookmarkId = location.hash;	
			if(bookmarkId){					        
				bookmarkId = bookmarkId.substring(1, bookmarkId.length);
			}   
			if(bookmarkId){
				//to do the best is to make several var for the urls
				//and then each time add to history, just add in the workareamode
				//later have a function called sth, it will say if this is the mode, then url = this
				//if that mode, url = that
				//and then call load context from url.
				//the benifit of this is that even this is page is load from bookmark id, 
				//we still can have the correct mode for it.
			   
					var indexOfIdentifier = bookmarkId.indexOf("identifier", 0);
					if ( indexOfIdentifier >= 0) {
						var realUrl = bookmarkId.substring(0, indexOfIdentifier - 1);
				}
			}

			if(bookmarkId == null || bookmarkId == ""){
				//Do something here
			}
		},

		
		goBack:function(){
		// summary: this function belong to HistoryTracking for receiving Back notifications
		// description: this function belong to HistoryTracking for receiving Back notifications	
			if(this.formArray != null){
				//Load the forms
				for(formIndex in this.formArray){
					var formObject = this.formArray[formIndex];
					document[formObject.form][formObject.formElementName][formObject.formElementProperty] = formObject.formElementPropertyValue;
				}
			}

			if(this.actionArray != null){
				//Call all the functions
				for(actionIndex in this.actionArray){
					var actionObject = this.actionArray[actionIndex];
					var func = actionObject.action;
					func.apply(actionObject.actionNameSpace, actionObject.actionParameter);
				}
			}
		},
			
		goForward:function(){
		// summary: this function belong to HistoryTracking for receiving forward notifications
		// description:this function belong to HistoryTracking for receiving forward notifications	
			if(this.formArray != null){
				//Load the forms
				for(formIndex in this.formArray){
					var formObject = this.formArray[formIndex];

					document[formObject.form][formObject.formElementName][formObject.formElementProperty] = formObject.formElementPropertyValue;
				}
			}

			if(this.actionArray != null){
				//Call all the functions
				for(actionIndex in this.actionArray){
					var actionObject = this.actionArray[actionIndex];
					var func = actionObject.action;
					func.apply(actionObject.actionNameSpace, actionObject.actionParameter);
				}
			}
		},
			

		initFastFinderHistory : function(){
			//each entry in the history stack need have unique hashcode value. so we need attach a timestamp after each url.
			var params = [];
			var actionArray = [];
			var formArray = [];
			var url = "identifier=" + (new Date()).getTime();

			actionArray = fastFinderJS.addAction(actionArray, fastFinderJS.showResults, fastFinderJS, params);

			formArray = fastFinderJS.getFormArray(formArray, "FastFinderForm");
			formArray = fastFinderJS.getFormArray(formArray, "SizeNamesForm");
			formArray = fastFinderJS.getFormArray(formArray, "FlavorsNamesForm");
			formArray = fastFinderJS.getFormArray(formArray, "SortResultForm");

			var historyObject = new fastFinderJS.HistoryTracker(actionArray, formArray, url);
			dojo.undo.browser.setInitialState(historyObject);
		},

		
		addAction : function (actionArray, newAction, newActionNameSpace, newActionParameter){
			var actionObject = new Object();
			actionObject["action"] = newAction;
			actionObject["actionNameSpace"] = newActionNameSpace;
			actionObject["actionParameter"] = newActionParameter;
			actionArray.push(actionObject);

			return actionArray;
		},

		addForm : function (formArray, newFormName, newElementName, newElementProperty, newElementPropertyValue){
			var formObject = new Object();
			formObject["form"] = newFormName;
			formObject["formElementName"] = newElementName;
			formObject["formElementProperty"] = newElementProperty;
			formObject["formElementPropertyValue"] = newElementPropertyValue;

			formArray.push(formObject);
			return formArray;
		},

		getFormArray : function(formArray, formName){
			if(!formArray)
				formArray = [];

			var formNode = document.forms[formName];
			
			for(var i = 0; i < formNode.elements.length; i++){
				var element = formNode.elements[i];
				if(!element || element.tagName.toLowerCase() == "fieldset") { continue; }
				
				var name = element.name;
				var type = element.type.toLowerCase();

				if(type == "select-multiple"){
					for(var j = 0; j < element.options.length; j++){
						this.addForm(formArray, formName, name, "selectedIndex", element.selectedIndex);
					}
				}else if(dojo.lang.inArray(["radio", "checkbox"], type)){
					this.addForm(formArray, formName, name, "checked", element.checked);
				}else{			
					this.addForm(formArray, formName, name, "value", element.value);
				}
			}
			return formArray;
		}
	}
		

	fastFinderJS.HistoryTracker.prototype.back		=	fastFinderJS.goBack;
	fastFinderJS.HistoryTracker.prototype.forward	=	fastFinderJS.goForward;
	
	function onLoad(){
		fastFinderJS.initFastFinderHistory();
		fastFinderJS.showResults();
	}

	dojo.addOnLoad(onLoad);

