//
//-------------------------------------------------------------------
// 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;
		var categoryImageDiv = null;
		var categoryImageDivShow = false;

		/**********************************************************
		* 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.productDisplayURLNoColour = "";
				this.toolTipHTML = "";
			this.category = "category display";
		}

	categoryDisplayJS={
			catalogEntriesResultSet : new Vector(), 
			catalogEntriesByPrice : new Vector(),
			
			pageSize : 10,
			resultsPerRow : 5,
			displayCounter : 0,
			displayRowCounter : 0,
			productIdentifierString : "catBrowse",
			newResultsPerRow : null,
			
			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) 
			{
				//alert("createProductWidget = ");
					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 = "";
						var _colourSwatches = "";
						var _categoryImageDiv = "";
						//alert("catima = " + _categoryImageDiv);  
						_colourSwatches = "<li><img src='"+ productObj.features[0].swatch +"' alt='"+ productObj.features[0].colour +"' border='0' /></li>\n";
						for (var i in productObj.features)
						{
							if(i==0)
								_colourSwatches = "<li><a href='"+ productObj.productDisplayURLNoColour + "_" + productObj.features[i].colour + "' ><img src='"+ productObj.features[i].swatch +"' alt='Available in "+ productObj.features[i].colour +"' width='15' height='15' /></a></li>\n";
							else
								_colourSwatches = _colourSwatches + "<li><a href='"+ productObj.productDisplayURLNoColour + "_" + productObj.features[i].colour + "' ><img src='"+ productObj.features[i].swatch +"' alt='Available in "+ productObj.features[i].colour +"' width='15' height='15' /></a></li>\n";
						}
						//alert("_colourSwatches = " + _colourSwatches);
						//alert("catima2x = " + categoryImageDivShow); 
					  if (this.categoryImageDivShow)
					  	_categoryImageDiv = this.categoryImageDiv;
					  						 
					  //alert("catima2 = " + _categoryImageDiv); 
						if (viewType == "image") {
							_baseContentNamePrice = ""
													+"		" + _categoryImageDiv + "\n"
													+"<td id='"+ _id + "Td' align='center' >\n"
													+"  <div id='"+ _id + "' class='product'>\n"  
													+"		<a id='imgcatBrowse"+ _id + "' href='"+ productObj.productDisplayURL +"' >\n"
													+"			<img src='"+ _baseContentImgSrc +"' alt='"+ productObj.shortDescription +"' border='0' />\n"
													+"		</a>\n"
													+"	<h4 id='" + _id + "NamePriceDiv' >\n"
													+"    <a href='"+ productObj.productDisplayURL +"' ><strong>\n"
													+"		" + productObj.name + "\n"
													+"		</strong><br/>\n"
													+"		" + productObj.displayPrice + "\n"
													+"		</a>\n"
													+"	</h4>\n"
													+"  <span>Colours available:</span>\n"
													+"  <ul class='colourways'>\n"
													+"		" + _colourSwatches + "\n"
													+"	</ul>\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 = ""	
										
										+"						" + _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) 
			{
					//alert("createProductToolTipWidget");
					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.open= function () {
					    if (this.isShowingNow) { return; }
							node=this._connectNode;
							dojo.widget.PopupContainerBase.prototype.open.call(this, node.offsetLeft+150,node.offsetTop+4, node);
						}
					
					
			toolTipContentWidget.productObj = productObj;
			},


			addElementToVector : function(targetVector, catentryId, SKU, name, identifierCounter, shortDescription, smallImageSrc, mediumImageSrc, 
										price, displayPrice, brand, productDisplayURL, dragSourceType, featuresArray, baseContentHTML, productDisplayURLNoColour, toolTipHTML){
				//alert("addElementToVector = " + name);
				//alert("addElementToVector = " + featuresArray);
				//alert("addElementToVector = " + featuresArray.length); 
				
				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 = eval('{ ' + featuresArray + '}');
				
				wcProduct.baseContentHTML = baseContentHTML;
				wcProduct.productDisplayURLNoColour = productDisplayURLNoColour;
				wcProduct.toolTipHTML = toolTipHTML;

				targetVector.addElement(wcProduct);
			},

			
	
			showResults : function(filterAction) {			
				cursor_wait();
				//destroy only catalog browsing widgets 
				//alert("showResults " + filterAction);
				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 categoryImageDiv2 = document.getElementById("categoryImage").innerHTML;
				
				this.categoryImageDiv = trim(document.getElementById("categoryImage").innerHTML);
				
				var productObj = null;
				var fastFinderResultsDiv = document.getElementById("fastFinderResults");
				
				if (fastFinderResultsDiv != null) {
					for (j=0; j<fastFinderResultsDiv.childNodes.length; j++) {
						fastFinderResultsDiv.removeChild(fastFinderResultsDiv.childNodes[j]);
					}
					this.displayCounter = 0;
					this.displayRowCounter = 0;
					 
					this.generateResultSet(filterAction);
								
				if(this.categoryImageDiv.length != 0) 
				{ 
					if(this.displayTotal == this.pageSize) 
						this.displayTotal = this.displayTotal - 2;
			    	else if(this.displayTotal == (this.pageSize - 1))
							this.displayTotal = this.displayTotal - 1; 
			    }  
							    	
					//create new product quick view HTML for the new result set and display them
					for (i=beginIndex; i<(beginIndex + this.displayTotal); i++) {
					
						if(i == 0 && this.categoryImageDiv != "")
							this.categoryImageDivShow = true;
						else  
							this.categoryImageDivShow = false;
							
						if(i == 1 && this.categoryImageDiv != "")
							this.displayCounter = this.displayCounter + 2;
							
						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);
					}
				}
				cursor_clear();
			},
			
			//
			// Generate the result set based on user input. Set the helper global javascript variables.
			//
			generateResultSet : function(filterAction) {
			//alert("generateResult");
				this.catalogEntriesResultSet = new Vector();
				for (k=0; k<this.catalogEntriesByPrice.size(); k++) {
					this.catalogEntriesResultSet.addElement(this.catalogEntriesByPrice.elementAt(k));
				}

				var viewTypeTD2 = document.getElementById("viewTypeTD2");
				var viewTypeTD1 = document.getElementById("viewTypeTD1");
				if(viewTypeTD2 != null && viewTypeTD1 != null){
					if (this.viewType == "image") {
							dojo.html.hide(viewTypeTD2);
							dojo.html.show(viewTypeTD1);
					} else if (this.viewType == "detailed") {
							dojo.html.hide(viewTypeTD1);
							dojo.html.show(viewTypeTD2);
					}
				}

				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;
				}
				
			},


			filterResultsWithView : function(view,pageSize){
				//alert("filterResultsWithView pageSize" + pageSize);
				this.pageSize = pageSize;
				document.FastFinderForm.pageView.value = view;
				this.viewType = view;
				document.FastFinderForm.initialState.value = "false";
				
				var viewTypeTD1 = document.getElementById("viewTypeTD1");
				var viewTypeTD2 = document.getElementById("viewTypeTD2");
				
				if (this.viewType == "image") {
						dojo.html.hide(viewTypeTD2);
						dojo.html.show(viewTypeTD1);
				} else if (this.viewType == "detailed") {
						dojo.html.hide(viewTypeTD1);
						dojo.html.show(viewTypeTD2);
				}
				
				this.showResults("view");
			},


			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 == ""){

				}
			},

			initCategoryHistory : function(){
					//category history tracking
					//alert("initCategoryHistory");
					var params = new Object();
					params["pageView"] = this.viewType;
					params["beginIndex"] = this.beginIndex;
					params["pageSize"] = this.pageSize;
					
					//each entry in the history stack need have unique hashcode value. so we need attach a timestamp after each url.
					var identifier = "&identifier=" + (new Date()).getTime();
					var workAreaModeValue = new Object();
					
					workAreaModeValue["action"] = "filterResults";
					workAreaModeValue["actionNameSpace"] = null;
					workAreaModeValue["actionParameter"] = params;

					var historyObject = new categoryDisplayJS.HistoryTracker(workAreaModeValue, identifier);
					dojo.undo.browser.setInitialState(historyObject);
			},

			goBack:function(){
			// summary: this function belong to HistoryTracking for receiving Back notifications
			// description: this function belong to HistoryTracking for receiving Back notifications	
				if(this.workAreaModeValue.action != null && this.workAreaModeValue.action != ""){
					if(this.workAreaModeValue.actionNameSpace != null && this.workAreaModeValue.actionNameSpace != "")
						this.workAreaModeValue.actionNameSpace =  null;
					
					var func = eval(this.workAreaModeValue.action);
					func.call(this.workAreaModeValue.actionNameSpace, this.workAreaModeValue.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.workAreaModeValue.action != null && this.workAreaModeValue.action != ""){
					if(this.workAreaModeValue.actionNameSpace != null && this.workAreaModeValue.actionNameSpace != "")
						this.workAreaModeValue.actionNameSpace =  null;

					var func = eval(this.workAreaModeValue.action);
					func.call(this.workAreaModeValue.actionNameSpace, this.workAreaModeValue.actionParameter);
				}
			},
				
			
			HistoryTracker:function(workAreaModeValue, 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.workAreaModeValue = null;
				this.workAreaModeValue = workAreaModeValue;
				//TODO: commenting this out breaks FF 1.5. Others? Can't seem to find iframe id/name?
				this.changeUrl =  changeUrl;
			}
	}
		
		
	function onLoad(){
		categoryDisplayJS.initCategoryHistory();
		//alert("onload");
		categoryDisplayJS.showResults();
		//alert("after onload");
	}
	
	

	dojo.addOnLoad(onLoad);
	
	categoryDisplayJS.HistoryTracker.prototype.back		=	categoryDisplayJS.goBack;
	categoryDisplayJS.HistoryTracker.prototype.forward	=	categoryDisplayJS.goForward;
