//
//-------------------------------------------------------------------
// 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");
		
		
		var beginIndex = 0;
		var prevIndex = null; 
		var nextIndex = null;


		/**********************************************************
		* 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.smallImageSrc = "";
				this.mediumImageSrc = "";
				this.price = "";
				this.brand = "";
				this.features = new Array();
				this.productDisplayURL = "";
				this.dragSourceType = "";
				this.baseContentHTML = "";
				this.toolTipHTML = "";
			this.category = "search";
		}

	fastFinderJS={
		totalResultsMessage : "UNDEFINED",
		pagingMessage : "UNDEFINED",
		pagingMessage2 : "UNDEFINED",

		catalogEntriesResultSet : new Vector(),
		catalogEntriesByPrice : new Vector(),
		catalogEntriesByBrand : new Vector(),

		pageSize : 12,
		resultsPerRow : 4,
		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",
		
		

		/**********************************************************
		* 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) 
		{
				var _id = identifierString + productObj.identifierCounter;
				var widgetHTML = ""
				
				if(productObj.baseContentHTML == null || productObj.baseContentHTML == ""){
					
					//alert("productObj.smallImageSrc:" + productObj.smallImageSrc + "\nproductObj.mediumImageSrc:" + productObj.mediumImageSrc + "\nimagePath:" + imagePath);
					if(productObj.smallImageSrc == "") productObj.smallImageSrc = imagePath + "NoImageIcon_sm45.jpg";
					if(productObj.mediumImageSrc == "") productObj.mediumImageSrc = imagePath + "NoImageIcon_sm.jpg";

					var _baseContentImgSrc = (viewType == "image")? productObj.mediumImageSrc : productObj.smallImageSrc;
					var _baseContentNamePrice = "";
					var _baseContentNameTD = "";
					var _baseContentPriceTD = "";

					if (viewType == "image") {
						_baseContentNamePrice = ""
												+"<td id='"+ _id + "Td' align='center' >\n"
												+"	<div id='"+ _id + "' align='center' >\n"
												+"		<a id='imgcatBrowse"+ _id + "' href='"+ productObj.productDisplayURL +"' >\n"
												+"			<img src='"+ _baseContentImgSrc +"' alt='"+ productObj.shortDescription +"' border='0' />\n"
												+"		</a>\n"
												+"	</div>\n"
												+"	<div id='" + _id + "NamePriceDiv' style='padding-top:4px;'>\n"
												+"		" + productObj.name + "\n"
												+"		<br/>\n"
												+"		" + productObj.displayPrice + "\n"
												+"	</div>\n"
												+"</td>\n";
					} 
					else if (viewType == "detailed") 
					{
						_baseContentNamePrice = ""
											+"	<td id='"+ _id + "Td' align='left' width='10%'>\n"
											+"		<div id='"+ _id + "' align='left' >\n"
											+"			<a id='imgcatBrowse"+ _id + "' href='"+ productObj.productDisplayURL +"' >\n"
											+"				<img src='"+ _baseContentImgSrc +"' alt='"+ productObj.shortDescription +"' border='0' />\n"
											+"			</a>\n"
											+"		</div>\n"
											+"	</td>\n"
											+"	<td id='"+ _id +"NameTd'>\n"
											+"		" + productObj.name + "\n"
											+"		<br/>\n"
											+"		" + productObj.shortDescription + "\n"
											+"	</td>\n"
											+"	<td id='"+ _id +"PriceTd' align='right'>\n"
											+"		" + productObj.displayPrice + "\n"
											+"	</td>\n";
					}

					widgetHTML = ""	
									+"			<table width='100%'>\n"
									+"				<tbody id='"+ _id + "Table' >\n"
									+"					<tr id='"+ _id + "Tr' >\n"
									+"						" + _baseContentNamePrice
									+"					</tr>\n"
									+"				</tbody>\n"
									+"			</table>\n";
				}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 = "";

				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>\n"
									+"				<div id='tooltipHeaderDiv"+ productObj.identifierCounter +"' className='popup_header' class='popup_header' >\n"
									+"					<div id='tooltipHeaderNameDiv"+ productObj.identifierCounter +"' className='popup_headerTitle' class='popup_headerTitle' >\n"
									+"						Product Details"
									+"					</div>\n"
									+"				</div>\n"

									+"				<div id='tooltipContentDiv"+ productObj.identifierCounter +"' className='popup_content' class='popup_content' >\n"
									+"					<table border='0' width='285'>\n"
									+"						<tbody id='"+ _id + "TTTable' >\n"
									+"							<tr id='"+ _id + "TTTr' >\n"
									+"								<td id='"+ _id + "TTTd' align='center' valign='top' width='90' style='padding-top:4px;padding-left:10px;'>\n"
									+"									<a id='imgcatBrowse"+ productObj.identifierCounter + "' href='"+ productObj.productDisplayURL +"' >\n"
									+"										<img src='"+ productObj.mediumImageSrc +"' alt='"+ productObj.shortDescription +"' border='0' className='popup_iconimages' class='popup_iconimages' style='margin-bottom:3px;' />\n"
									+"									</a>\n"
									+"									<br/>\n"
									+"									<a id='cartlink"+ productObj.identifierCounter + "' href='javascript: Add2ShopCartAjax(\"" + productObj.catentryId + "\");'  >\n"
									+"										<img src='"+ imagePath  +"quickcart.gif' alt='add to cart' border='0' className='popup_iconimages' class='popup_iconimages' />\n"
									+"									</a>\n"
									+"									<a id='listlink"+ productObj.identifierCounter + "' href='javascript: Add2WishListAjax(\"" + productObj.catentryId + "\");'  >\n"
									+"										<img src='"+ imagePath  +"wishlist.gif' alt='add to list' border='0' className='popup_iconimages' class='popup_iconimages' />\n"
									+"									</a>\n"
									+"									" + _productToolTipCompareLink
									+"								</td>\n"

									+"								<td id='"+ _id + "TTTd2' valign='top' style='padding-top:5px;padding-left:0px;'>\n"
									+"									<div id='"+ _id + "NameDiv' className='popup_productname' class='popup_productname' >\n"
									+"										" + productObj.name +"\n"
									+"									</div>\n"
									+"									<div id='"+ _id + "PriceDiv' className='popup_productprice' class='popup_productprice' >\n"
									+"										" + productObj.displayPrice +"\n"
									+"									</div>\n"
									+"									<div id='"+ _id + "SDescDiv' className='popup_productother' class='popup_productother' >\n"
									+"										" + productObj.shortDescription +"\n"
									+"									</div>\n"
									+"									<input id='formParamsCatEntryId_"+ _id +"' name='formParamsCatEntryId_"+ _id +"' type='hidden' value='"+ productObj.catentryId +"' />"
									+"								</td>\n"
									+"							</tr>\n"
									+"						</tbody>\n"
									+"					</table>\n"
									+"				</div>\n"

									+"				<div id='tooltipFooterDiv"+ productObj.identifierCounter +"' className='popup_footer' class='popup_footer' >\n"
									+"				</div>\n"
									+"			</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);
			toolTipContentWidget.productObj = productObj;
		},


		addElementToVector : function(targetVector, catentryId, SKU, name, identifierCounter, shortDescription, smallImageSrc, mediumImageSrc, 
									price, displayPrice, brand, productDisplayURL, dragSourceType, featuresArray, baseContentHTML, toolTipHTML){
			
			var wcProduct = new WCProduct();
			wcProduct.catentryId = catentryId;
			wcProduct.SKU = SKU;
			wcProduct.name = name;
			wcProduct.identifierCounter = identifierCounter;
			wcProduct.shortDescription = shortDescription;
			wcProduct.smallImageSrc = smallImageSrc;
			wcProduct.mediumImageSrc = mediumImageSrc;
			wcProduct.price = price;
			wcProduct.displayPrice = displayPrice;
			wcProduct.brand = brand;
			wcProduct.productDisplayURL = productDisplayURL;
			wcProduct.dragSourceType = dragSourceType;
			wcProduct.features = featuresArray;
			
			wcProduct.baseContentHTML = baseContentHTML;
			wcProduct.toolTipHTML = toolTipHTML;

			targetVector.addElement(wcProduct);
		},

		
		showResults : function(filterAction) {
			this.viewType = document.FastFinderForm.pageView.value;
			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();
			
			//create new product quick view HTML for the new result set and display them
			for (i=beginIndex; i<(beginIndex + this.displayTotal); i++) {
				this.displayCounter++;
				productObj = this.catalogEntriesResultSet.elementAt(i);
	
				var td1 = document.createElement("td");
				td1.setAttribute("id", "browseCatEntry"+i);
		
				if (this.viewType == "image") {
					if (((this.displayCounter-1) % this.resultsPerRow) == 0 ) {
						this.displayRowCounter++;
						
						var tr1 = document.createElement("tr");
						tr1.setAttribute("id", "displayRow"+this.displayRowCounter);
					} else {
						var tr1 = document.getElementById("displayRow"+this.displayRowCounter);
					}
				} else if (this.viewType == "detailed") {
					this.displayRowCounter++;
					var tr1 = document.createElement("tr");
					tr1.setAttribute("id", "displayRow"+this.displayRowCounter);
				}
				tr1.appendChild(td1);
				
				if (i%this.pageSize == 0) {
					var table1 = document.createElement("table");
					table1.setAttribute("width", "100%");
					
					var tbody1 = document.createElement("tbody");
					tbody1.setAttribute("id", "displayItemsTable");
					
					table1.appendChild(tbody1);
					tbody1.appendChild(tr1);
					fastFinderResultsDiv.appendChild(table1);
				} else {
					var tbody1 = document.getElementById("displayItemsTable");
					tbody1.appendChild(tr1);
				}

				this.createProductWidget(td1,productObj, this.productIdentifierString, "medium", false, this.imagePath, this.viewType, this.storeId, this.catalogId);
			}
			
			// 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 = 0;
					// 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 brand 
					if (document.FastFinderForm.orderBy1.value == "OfferPricePrice") {
						tempList = this.catalogEntriesByPrice;
					} else {
						tempList = this.catalogEntriesByBrand;
					}
					
					// 2. Eliminate entries based on selected criterias
					var minPrice = parseFloat(document.FastFinderForm.minPrice.value);
					var maxPrice = parseFloat(document.FastFinderForm.maxPrice.value);
					
					var brands = new Vector();
					//brands.removeAllElements();
					var manufacturerNames = document.BrandsForm.elements;
					for (i=0; i<manufacturerNames.length; i++) {
						if (manufacturerNames[i].checked) {
							brands.addElement(manufacturerNames[i].value);
						}
					}
					
					var featureNames = new Vector();
					//featureNames.removeAllElements();
					var featuresElements = document.FeatureNamesForm.elements;
					for (i=0; i<featuresElements.length; i++) {
						if (featuresElements[i].checked) {
							featureNames.addElement(featuresElements[i].value);
						}
					}
					
					dojo.debug("tempList.size() = "+ tempList.size());
					for (i=0; i<tempList.size(); i++) {
						var hasPrice = false;
						var hasBrand = false;
						var hasFeature = false;
						//check price
						var productObjNew = tempList.elementAt(i);
						dojo.debug("minPrice = "+ minPrice);
						dojo.debug("maxPrice = "+ maxPrice);
						dojo.debug("productObjNew.price = "+ productObjNew.price);
						dojo.debug("productObjNew.brand = "+ productObjNew.brand);
						if (productObjNew.price >= minPrice && productObjNew.price <= maxPrice) {
							hasPrice = true;
						}
						
						//check brands
						if (brands.contains(productObjNew.brand)) {
							hasBrand = true;
						}
						
						//check features
						for (f=0; f<productObjNew.features.length; f++) {
							dojo.debug("productObjNew.features["+f+ "] = "+ productObjNew.features[f]);
							if (featureNames.contains(productObjNew.features[f])) {
								hasFeature = true;
								break;
							}
						}
						dojo.debug("checking catentry = "+ productObjNew.catentryId);
						dojo.debug("hasPrice="+ hasPrice + ", hasBrand=" + hasBrand + ", hasFeature=" + hasFeature);
						if(hasPrice && hasBrand && hasFeature) {
							dojo.debug("adding catentry = "+ productObjNew.catentryId);
							this.catalogEntriesResultSet.addElement(productObjNew);
						}
					}
				}
			} else {
				this.catalogEntriesResultSet = new Vector();
				for (k=0; k<this.catalogEntriesByPrice.size(); k++) {
					this.catalogEntriesResultSet.addElement(this.catalogEntriesByPrice.elementAt(k));
				}
                            
				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 = (this.catalogEntriesResultSetTotal-beginIndex);
			} else {
				this.displayTotal = this.pageSize;
			}
			
			if (beginIndex == 0) {
				prevIndex = 0;
			} else {
				prevIndex = beginIndex-this.pageSize;
			}
			if ( (beginIndex+this.displayTotal) >= this.catalogEntriesResultSetTotal) {
				nextIndex = beginIndex;
			} else {
				nextIndex = beginIndex+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 resultsTDBottom = document.getElementById("pagingMessageDisplayBottom");
			var text = this.pagingMessage;
			if (this.catalogEntriesResultSetTotal != 0) {
				text = text.replace(/%0/, beginIndex+1);
			} else {
				text = text.replace(/%0/, beginIndex);
			}
			text = text.replace(/%1/, beginIndex+this.displayTotal);
			text = text.replace(/%2/, this.catalogEntriesResultSetTotal);
			
			var textNodeTop = document.createTextNode(text);
			var textNodeBottom = document.createTextNode(text);
			
			if (resultsTDTop.childNodes.length == 1) {
				resultsTDTop.removeChild(resultsTDTop.firstChild);
			}
			resultsTDTop.appendChild(textNodeTop);
			
			if (resultsTDBottom.childNodes.length == 1) {
				resultsTDBottom.removeChild(resultsTDBottom.firstChild);
			}
			resultsTDBottom.appendChild(textNodeBottom);
		},

		showPagingMessage2 : function() {
			var resultsTDTop = document.getElementById("pagingMessage2DisplayTop");
			var resultsTDBottom = document.getElementById("pagingMessage2DisplayBottom");
			var text = this.pagingMessage2;
			if (this.catalogEntriesResultSetTotal != 0) {
				text = text.replace(/%0/, this.catalogEntriesResultSetCurrentPageNumber);  
			} else {
				text = text.replace(/%0/, 0);
			}
			text = text.replace(/%1/, this.catalogEntriesResultSetTotalPages);
			
			var textNodeTop = document.createTextNode(text);
			var textNodeBottom = document.createTextNode(text);
			
			if (resultsTDTop.childNodes.length == 1) {
				resultsTDTop.removeChild(resultsTDTop.firstChild);
			}
			resultsTDTop.appendChild(textNodeTop);
			
			if (resultsTDBottom.childNodes.length == 1) {
				resultsTDBottom.removeChild(resultsTDBottom.firstChild);
			}
			resultsTDBottom.appendChild(textNodeBottom);
		},

		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 viewsTR = document.getElementById("viewsTR");
			
			var viewTypeTD1 = document.getElementById("viewTypeTD1");
			var viewTypeTD2 = document.getElementById("viewTypeTD2");
			
			if (this.viewType == "image") {
				if (viewTypeTD2 != null) {
					viewsTR.removeChild(viewTypeTD2);
				}
				if (viewTypeTD1 == null) {
					viewTypeTD1 = this.createViewTypeTD1();
				}
				viewsTR.appendChild(viewTypeTD1);
			} else if (this.viewType == "detailed") {
				if (viewTypeTD1 != null) {
					viewsTR.removeChild(viewTypeTD1);
				}
				if (viewTypeTD2 == null) {
					viewTypeTD2 = this.createViewTypeTD2();
				}
				viewsTR.appendChild(viewTypeTD2);
			}
			
			this.showResults("view");
		},

		createViewTypeTD1 : function() {
			var viewTypeTD1 = document.createElement("td");
			viewTypeTD1.setAttribute("id", "viewTypeTD1");
			
			var imageSelected = document.createElement("img");
			imageSelected.setAttribute("id", "imageTypeImageSelected");
			imageSelected.setAttribute("src", this.imagePath + "icon_image_selected.gif");
			imageSelected.setAttribute("border", "0");
			imageSelected.setAttribute("className", "ff_iconimages");
			imageSelected.setAttribute("class", "ff_iconimages");
			
			var detailedTypeLink = document.createElement("a");
			detailedTypeLink.setAttribute("href", "javascript: filterWithView('detailed');");
			detailedTypeLink.setAttribute("id", "detailedTypeLink");
			var detailedTypeImage = document.createElement("img");
			detailedTypeImage.setAttribute("src", this.imagePath + "icon_list.gif");
			detailedTypeImage.setAttribute("border", "0");
			detailedTypeImage.setAttribute("className", "ff_iconimages");
			detailedTypeImage.setAttribute("class", "ff_iconimages");
			detailedTypeLink.appendChild(detailedTypeImage);
			
			viewTypeTD1.appendChild(imageSelected);
			viewTypeTD1.appendChild(detailedTypeLink);
			
			return viewTypeTD1;
		},
		
		createViewTypeTD2 : function() {
			var viewTypeTD2 = document.createElement("td");
			viewTypeTD2.setAttribute("id", "viewTypeTD2");
			
			var detailedSelected = document.createElement("img");
			detailedSelected.setAttribute("id", "detailedTypeImageSelected");
			detailedSelected.setAttribute("src", this.imagePath + "icon_list_selected.gif");
			detailedSelected.setAttribute("border", "0");
			detailedSelected.setAttribute("className", "ff_iconimages");
			detailedSelected.setAttribute("class", "ff_iconimages");
				
			var imageTypeLink = document.createElement("a");
			imageTypeLink.setAttribute("href", "javascript: filterWithView('image');");
			imageTypeLink.setAttribute("id", "imageTypeLink");
			var imageTypeImage = document.createElement("img");
			imageTypeImage.setAttribute("src", this.imagePath + "icon_image.gif");
			imageTypeImage.setAttribute("border", "0");
			imageTypeImage.setAttribute("className", "ff_iconimages");
			imageTypeImage.setAttribute("class", "ff_iconimages");
			imageTypeLink.appendChild(imageTypeImage);
			
			viewTypeTD2.appendChild(imageTypeLink);
			viewTypeTD2.appendChild(detailedSelected);
			
			return viewTypeTD2;		
		},
		
		filterResultsWithPrevIndex : function(){
			document.FastFinderForm.beginIndex.value = prevIndex;
			beginIndex = prevIndex;
			document.FastFinderForm.initialState.value = "false";
			
			this.showResults("beginIndex");
		},

		filterResultsWithNextIndex : function(){
			document.FastFinderForm.beginIndex.value = nextIndex;
			beginIndex = nextIndex;
			document.FastFinderForm.initialState.value = "false";
			
			this.showResults("beginIndex");
		},

		filterResultsWithOrderBy : function(orderByNode){
			document.FastFinderForm.orderBy1.value = orderByNode.value;
			document.FastFinderForm.initialState.value = "false";
			
			this.showResults("orderBy");
		},

		filterResultsWithBrands : function(){
			document.FastFinderForm.initialState.value = "false";
			
			this.showResults("brand");
		},

		filterResultsWithFeatures : function(){
			document.FastFinderForm.initialState.value = "false";
		
			this.showResults("features");
		},


		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, "BrandsForm");
			formArray = fastFinderJS.getFormArray(formArray, "FeatureNamesForm");
			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++){
						if(element.options[j].selected) {
							//this.addForm(formArray, formName, name, "selected", newElementPropertyValue)
							//values.push(name + "=" + enc(formNode.options[j].value));
						}
						this.addForm(formArray, formName, name, "selectedIndex", element.selectedIndex);
					}
				}else if(dojo.lang.inArray(["radio", "checkbox"], type)){
					//if(formNode.checked){
						//values.push(name + "=" + enc(formNode.value));
					//}
					this.addForm(formArray, formName, name, "checked", element.checked);
				}else{
					//values.push(name + "=" + enc(formNode.value));
					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);
