//<%--
//********************************************************************
//*-------------------------------------------------------------------
//* Licensed Materials - Property of IBM
//*
//* WebSphere Commerce
//*
//* (c) Copyright IBM Corp.  2007
//* All Rights Reserved
//*
//* US Government Users Restricted Rights - Use, duplication or
//* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//*
//*-------------------------------------------------------------------
//*
//--%>
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	// CatalogSearchDisplayJS contains all the global variables and javascript functions 
	// necessary for this page to work.
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////////////
	   
	
	
	//declare the namespace if it does not already exist
	if (CatalogSearchDisplayJS == null || typeof(CatalogSearchDisplayJS) != "object") {
		var CatalogSearchDisplayJS = new Object();
	 }
	 
	CatalogSearchDisplayJS={	
	
		//global variables used in the CatalogSearchDisplay page
		//showResultsPage:boolean 
		//              a flag indicating if the search result should be displayed
		//searchModeVisible:boolean
		//		indicating if search form should be displayed
		//searchMode: String
		//		to store the search mode, which is one of the following: topVar, simple and advanced
		//invalidPageNumMsg: String
		// 		the message will be displayed if user choose an number which is out of range
		//isHistory   Boolean
		//		whether the update of context is caused by a history event(back/forward)
		showResultsPage:false,    
		searchModeVisible:true,   
		searchMode:"topBar",      
		invalidPageNumMsg:"",  
		productArray: new Array(),    
		isHistory:false,
		multipleAttributeSelectionErrorMessage:"",
		
		changeSearchMode:function(){
			
			// summary: This function toggle between simple search mode and advanced search mode
			// Description: This function toggle between simple search mode and advanced search mode
			// 		Assumptions: searchModeVisible is set to the correct value
			// 		dojo API: none	
				
						
			simpleSearchDiv = dojo.byId("Simple_Search_Form_div");
			advancedSearchDiv = dojo.byId("Advanced_Search_Form_div");
			advancedSearchCheckBox = dojo.byId("advanced_search_chekbox");
			searchResultDiv = dojo.byId("Search_Result_div");
			
			if(CatalogSearchDisplayJS.searchModeVisible == "true"){
				if(advancedSearchCheckBox.checked){
					dojo.html.hide(simpleSearchDiv);
					dojo.html.show(advancedSearchDiv);
					
				}else{
					dojo.html.hide(advancedSearchDiv);
					dojo.html.show(simpleSearchDiv);
				}
			}
		},

		
		showHideSearchMode:function(advanced){
		
		// summary: This function toggle between search mode and result display mode
		// Description: This function toggle between search mode and result display mode
		
		// advanced: boolean
		//		used to indicate if the current search mode is advanced search
		
			var methodName = "showHideSearchMode";
			dojo.debug(methodName + "advance: " + advanced);
		  
			simpleSearchDiv = dojo.byId("Simple_Search_Form_div");
			advancedSearchDiv = dojo.byId("Advanced_Search_Form_div");
			advancedSearchCheckBox = dojo.byId("advanced_search_chekbox");
			searchResultDiv = dojo.byId("Search_Result_div");
			searchFlipperDiv = dojo.byId("search_flipper");
			if(advanced){
				advancedSearchCheckBox.checked = true;
			}

			if(CatalogSearchDisplayJS.searchModeVisible == "true"){
				dojo.html.hide(simpleSearchDiv);
				dojo.html.hide(advancedSearchDiv);
				dojo.html.hide(searchFlipperDiv);
				dojo.html.show(searchResultDiv);
				CatalogSearchDisplayJS.searchModeVisible = "false";
			}else{
				dojo.html.show(searchFlipperDiv);
				CatalogSearchDisplayJS.searchModeVisible = "true";
				CatalogSearchDisplayJS.changeSearchMode();
				dojo.html.hide(searchResultDiv);
			}
		},

		
		submitSimpleSearch:function( formId){   
		
		// summary: this function submit the simple search form by using render.updateContext
		// Description: This function submit the simple search form by using render.updateContext
		
		// formId: html form
		//		it is the form Id of simple search form to be submitted.	
			var form = document.getElementById(formId);
		// pvh removed 5/16/11
		//	form.manufacturerPartNum.value=form.searchTerm.value;
			CatalogSearchDisplayJS.searchMode = "simple"; 			 
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").formId = formId;
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = "AjaxCatalogSearchResultView";
			
			cursor_wait();
			//provide meaningful value for the modes. searchResultsPageNum and searchResultsView is not enough
			//when we submit a new query, the search term changed, the number and view may stay the same
			//the best way to identify the state of the application is to provide the new url
			var queryString = dojo.io.encodeForm(dojo.byId(formId));
			var searchUrl = "AjaxCatalogSearchResultView?" + queryString;
			wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsPageNum: "1", searchResultsURL: searchUrl, searchResultsView: "image"});
		},
	
				
		submitAdvancedSearch:function(formId){
		
		// summary: This function submit the advanced search form by using render.updateContext
		// Description: This function submit the advanced search form by using render.updateContext			
		
		// form: html formId
		//		this is the advanced search form to be submitted.
			
			var methodName = "submitAdvancedSearch";
			
			
			form = document.getElementById(formId);
			//pvh removed 5/16/11
			//form.manufacturerPartNum.value=form.searchTerm.value; 	
			CatalogSearchDisplayJS.searchMode = "advanced"
			
			var elements_of_form =form.elements;
	        var ctr=0;
	        var attCtr=0;
	        var attrVarCtr=0;
	        for(var i=0;i<elements_of_form.length;i++)
	        {
	         	element=elements_of_form[i];
	         	var elementNamePrefix=element.name.split("_");  
	         	ctr=0;               	 
	         	if(elementNamePrefix[0]=='search')
	         	{         	   
	         	 	for(var j=0;j<element.options.length;j++)
	         	 	{
	         	 		if(element.options[j].selected==true)
	         	 		{           	 		    
	         	 			ctr++;
	         	 		}
	         	 	}
	         	 	
	         	 	if(ctr>3)
	         	 	{
	         	 		var errMessage = this.multipleAttributeSelectionErrorMessage;
	         	 		errMessage = errMessage.replace('{0}', elementNamePrefix[1]);	         	 	
	         	 		alert(errMessage);
	         	 		return;
	         	 	}
	         	 }
	          }
	          
	          for(var i=0;i<elements_of_form.length;i++)
	          {
	         	element=elements_of_form[i];
	         	var elementNamePrefix=element.name.split("_");                 	 
	         	if(elementNamePrefix[0]=='search')
	         	{ 
	         	 	var flag=false;
	         	 	var localCtr=1;
	         	 	var tmpEle;
	         	 	var tmpArray=new Array();
	         	 	//var tmpArray1=new Array();
	         	 	//alert(element.options[0].value);         	 	 
	         	 	//tmpArray=element.options; 
	         	 	//sortOptions(tmpArray);     
	         	 	     	 	      
	         	 	for(var j=0;j<element.options.length;j++)
	         	 	{
	         	 	  tmpArray[j]=[element.options[j].value,element.options[j].selected];         	 	  
	         	 	  //tmpArray[j]=element.options[j].selected;
	         	 	  
	         	 	}	         	 	
	         	 	//tmpArray.sort(sortMultiDimensional);
	         	 	var operator='Like';          	 	         
		 	 		var elementName=element.name.split("_"); 
		 	 		document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+attCtr).name='attributeName'+(attrVarCtr+1);
		 	 		document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+attCtr).value=elementName[1];
	         	 	document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+(attCtr+1)).name='attributeValue'+(attrVarCtr+1)
	         	 	var flag=0;
	         	 	for(var j=0;j<tmpArray.length;j++)
	         	 	{         	 	  
	         	 	  if(tmpArray[j][1]==true)
	         	 	  {         	 	 
	         	 	     var tmpElement=document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+(attCtr+1));  
	         	 	     if(flag!=0)
	         	 	     {         	 	      
	         	 	      tmpElement.value=tmpElement.value+','+tmpArray[j][0];   	 		    
		 	 			 }
		 	 			 else
		 	 			 {
		 	 			  tmpElement.value=tmpElement.value+tmpArray[j][0];
		 	 			 }
		 	 		 
		 	 			 flag=1;	 	 			 	 	 			    	 	
	         	 	  }
	         	 	}
	         	 		 document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+(attCtr+2)).name='attributeValueOperator'+(attrVarCtr+1);
		 	 			 document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+(attCtr+2)).value=operator;
		 	 			 document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+(attCtr+3)).name='attributeValueType'+(attrVarCtr+1);
		 	 			 document.getElementById('WC_CatalogSearchForm_FormInput_Attribute_Fields_In_AdvancedSearchForm_'+(attCtr+3)).value='STRING';  
	         	 	 attCtr+=4;
		 	 	    attrVarCtr++; 
	         	}
	         }
			//set the result catEntryType, which is checked on CatalogSearchResultDisplay.jsp: 
			// 1 = list items, packages, and bundles
			// 2 = list products, packages, and bundles
				
			if(form.searchTerm !== null && form.searchTerm != 'undefined')
				form.searchTerm.value = form.searchTerm.value.replace(/^\s+/g, '').replace(/\s+$/g, '');
		
			if(form.minPrice !== null && form.minPrice != 'undefined')
				form.minPrice.value = form.minPrice.value.replace(/^\s+/g, '').replace(/\s+$/g, '');
		
			if(form.maxPrice !== null && form.maxPrice != 'undefined')
				form.maxPrice.value = form.maxPrice.value.replace(/^\s+/g, '').replace(/\s+$/g, '');
		
		   // changed so always grab product 
			if ((form.minPrice.value == "") && (form.maxPrice.value == ""))
			{
				//form.resultCatEntryType.value = "2";
				form.currency.value="";
			}
			//else
			//{
				//form.resultCatEntryType.value = "1";
			//}
			
			cursor_wait();
			var queryString = dojo.io.encodeForm(dojo.byId(formId));
			var searchUrl = "AjaxCatalogSearchResultView?" + queryString;
			dojo.debug(methodName + " url: " + searchUrl);			
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").formId = formId;
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = "AjaxCatalogSearchResultView";
			wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsPageNum: "1", searchResultsURL: searchUrl, searchResultsView: "image"});			
			
		},
	
		loadContentFromURL:function(changeUrl){
	        //Summay: this function is used by history back and forward actions to refresh the page based on the url stored in the history tracker object
		//Description:	this function is used by history back and forward actions to refresh the page based on the url stored in the history tracker object
		//ChangeUrl: String
		//           the url stored in the history tracker object. It is used to refresh the page
			if (changeUrl == "simple"){//if the page was the search form page				
				this.showHideSearchMode(false);//display the simple form
		       }
			else if (changeUrl == "advanced"){
				this.showHideSearchMode(true);//display the advanced form
			}
			else{
				wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = changeUrl;
			
				wc.render.updateContext("catalogSearchResultDisplay_Context", { searchResultsURL: changeUrl});			
			}
		},
			 
		searchResultCallback:function(changeUrl){
		
		// summary: This function is the call back function for searchresult request
		// Description: This function is the call back function for context update. It uses dojo.undo.browser for adding history object onto dojo browser history
		// changUrl: String
		//	     The url used for updating context
		
			var methodName = "searchResultCallback";
			dojo.debug(methodName + " entry" );
		
			CatalogSearchDisplayJS.searchModeVisible = "true";
			CatalogSearchDisplayJS.showHideSearchMode();
		
			//Get the values from hidden fields
			var pageSize = parseInt(document.getElementById("pageSizeOfResult").value);
			var totalNumberOfResultSetPages = parseInt(document.getElementById("totalNumberOfPagesOfResult").value);
			var searchTerm = document.getElementById("searchTermOfResult").value;
			
	   		var identifier = "&identifier=" + (new Date()).getTime();
	   		var newUrl = changeUrl + identifier;
	    		
	    		//if the context updated was not invoked by a history event, add this url to the dojo browser history.			
			if( !CatalogSearchDisplayJS.isHistory ) {
				dojo.debug(methodName + " add to history: " + newUrl );
				var historyObject = new CatalogSearchDisplayJS.HistoryTracker(changeUrl, "Search_result_div", newUrl);
				dojo.undo.browser.addToHistory(historyObject);			
			}
			CatalogSearchDisplayJS.isHistory = false;
			cursor_clear();
			dojo.debug(methodName + " exit " );
		},
		
		goToResultPage:function(resultPageURL)
		// Summary: This function is used for flipping search result pages using the arrow button
		// Description: This function is used for flipping search result pages using the arrow button
		
		// resultPageURL: String
		//		This is the URL to be requested	
		{      
			cursor_wait();  
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = resultPageURL;
			//alert("result page url is " + resultPageURL);
			wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsURL: resultPageURL});
			
			
		},
					
			compareSelectedProducts:function(){
			//var storageKey = this.getStorageKey();
           // alert(storageKey);
   
            var result = new Array();
            var cnt=0;
            var catentryIds = document.forms['CompareForm1'].compareCatentryId;
            for (i=0;i<catentryIds.length;i++)
           	{
           		this.productArray[i]  = catentryIds[i].value;
           	}
           
          
			for(catEntryIdentifier in this.productArray)
			{
				 		
				var catEntryId =this.productArray[catEntryIdentifier];
		
				var ele = document.getElementById('compare_'+catEntryId);
				
				if(ele!=undefined && ele!=null && ele.checked)
				{
					result[cnt]=catEntryId;
					cnt++;
				}
			
		    }
		    		
            if(cnt>6)
            {
            	alert("You can compare only a maximum of 6 products");
            	return;
            
            }
            else if (cnt<2)
            {
            	alert("You should select atleast 2 products to compare");
            	return;
            
            }

			var url = document.CompareForm1.action + "?storeId=" + document.CompareForm1.storeId.value + "&catalogId=" + document.CompareForm1.catalogId.value +
				"&langId=" + document.CompareForm1.langId.value + "&categoryId=" + document.CompareForm1.categoryId.value;
 

			for(catEntryIdentifier in result){
				url = url + "&catentryId=" + result[catEntryIdentifier];
			}
           
			document.location.href = url;
		},
		
		
		submitJumpToSearch:function(form){
		// Summary: This function is used to jump to the search result page specified by a user's input
		// Description: This function is used to jump to the search result page specified by a user's input
				
		// form: html form
		//		form is either jumpToPageForm or jumpToPageForm2 which contains all the inputs for building the whole url for the catalog search request.
		
			//Get the values from hidden fields
			var pageSize = parseInt(document.getElementById("pageSizeOfResult").value);
			var totalNumberOfResultSetPages = parseInt(document.getElementById("totalNumberOfPagesOfResult").value);
			formId = form.id;
			if ( form.jumpToPage.value >=1 && form.jumpToPage.value <= totalNumberOfResultSetPages) {
				form.beginIndex.value = (form.jumpToPage.value-1) * pageSize;
				
		       		cursor_wait();
		       		var queryString = dojo.io.encodeForm(dojo.byId(formId));
		      
				var searchUrl = "AjaxCatalogSearchResultView?" + queryString;
				wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").formId = formId;
				wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = "AjaxCatalogSearchResultView";
				wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsURL:searchUrl, searchResultsPageNum:form.jumpToPage.value  , searchResultsView: form.pageView.value} );	
				
				
			} else {
				Common.formErrorHandleClient("jumpToPage", this.invalidPageNumMsg, formId, "Search_Result_div");				
			}
		},
		
		processURL:function(){
		// summary: This function processes the URL and act accordingly.
		// Description: This function processes URL and act accordingly. It also inits the search history.
		//		If there is query information in the url, extract the query string. 
		//              make AJAX call to request the search result and update the Search_Result_div
		
		var methodName ="processURL";
		dojo.debug(methodName + " enter" );   
		
		//we have three cases here
		//1. the url from bookmarked search page: we build a new url and use it to update context.
		//    1.1 advance: advanced = true 
		//    1.2 simple
		//	
		//2. the url from simple search: we need build a new url and use it to update context
		//3. the url for the regular result of advanced search form: no need to update context
		   
		var bookmarkId = location.hash;	
		dojo.debug( " bookmarkedId is " + bookmarkId);	
		
		var needContextUpdate = false;	
		var wholeUrl;
		if(bookmarkId){
		
		        //two pages can be bookmarked. in all cases, the search result is true, since we only 
		        // allow bookmark search result page 
		        //one is the simple search result page
		        //one is the advanced search result page
		        
			bookmarkId = bookmarkId.substring(1, bookmarkId.length);
			
			//when user does a refresh of a page which has bookId, we need strip off the identifier attached
			//so that it does not keeping appending one after another
			wholeUrl = bookmarkId;
			var indexOfIdentifier = bookmarkId.indexOf("identifier", 0);
	            	if ( indexOfIdentifier >= 0) {
		    		wholeUrl = bookmarkId.substring(0, indexOfIdentifier - 1);
		    	}
			CatalogSearchDisplayJS.showResultsPage = true;
			needContextUpdate = true;
		  	
		  		
		 }
		 //if this is a new request from the top bar simple search form
		else if(CatalogSearchDisplayJS.showResultsPage){
			var search = location.search;
			wholeUrl = "AjaxCatalogSearchResultView" + search ;
			needContextUpdate = true;
			
		}
	       else{ // this is the regular advanced search form page	       
	       		CatalogSearchDisplayJS.initSearchHistory("AjaxCatalogSearchResultView", "Search_area", "advanced");
		}		
		
		if (needContextUpdate) {			
			
			cursor_wait();
			
			CatalogSearchDisplayJS.initSearchHistory("AjaxCatalogSearchResultView", "Search_area", wholeUrl);
			
			//set this to true so that later in searchResultCallback we do not add this entry to the 
		        //dojo history stack.
			CatalogSearchDisplayJS.isHistory = true; 
		        dojo.debug( "wholeUrl: " + wholeUrl);	
		   	wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = wholeUrl;			
			wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsURL: wholeUrl});	
		}
		dojo.debug(methodName + " exit ");
	},
	
	
	initSearch:function(){
	
	// Summary:This function show/hide all the subdivs of the Search_area_div
	// Description: This function show/hide all the subdivs of the Search_area_div
	// 		Assumptions: the global var changeSearchMode is set with correct value
	// 
	
		var methodName = "initSearch" ;
		dojo.debug(methodName + " entry " );
		
		CatalogSearchDisplayJS.searchModeVisible = "true";
		CatalogSearchDisplayJS.changeSearchMode();
		if(CatalogSearchDisplayJS.showResultsPage) {
			CatalogSearchDisplayJS.showHideSearchMode();
		}
		dojo.debug(methodName + " value of searchMode " + CatalogSearchDisplayJS.searchModeVisible + " value of showResultPage " + CatalogSearchDisplayJS.showResultsPage);
		
	},		
	
	
	initSearchHistory:function(workAreaModeValue, elementId, changeUrl){
	
	// summary: this function sets the initial state of dojo browser history. 
	// Description: This function sets the initial state of dojo browser history for MyAccountDispay page. 
	// dojo API   : dojo.undo.browser.setInitialState
	// workAreaModeValue: String
	//		a value to uniquely identify an context.
	// elementId:String
	//             the id of the widget.
	// changeUrl:String
	//             the url used to load new context.
		var methodName = "initSearchHistory";
		dojo.debug(methodName + " mode: " + workAreaModeValue + " id: " + elementId + " url " + changeUrl);	
		var historyObject = new CatalogSearchDisplayJS.HistoryTracker(workAreaModeValue, elementId, changeUrl);
		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
		
		
	    
			CatalogSearchDisplayJS.loadContentFromURL(this.changeUrl);
			CatalogSearchDisplayJS.isHistory=true;
        },
        
        goForward:function(){
       
	// summary: this function belong to HistoryTracking for receiving forward notifications
	// description:this function belong to HistoryTracking for receiving forward notifications	
	        	
		CatalogSearchDisplayJS.loadContentFromURL(this.changeUrl);
		CatalogSearchDisplayJS.isHistory=true;
        },
		
	
	HistoryTracker:function(workAreaModeValue, elementId, changeUrl){
	
	// summary: History state object for history tracking
	// description:History state object for history tracking
	// workAreaModeValue: String
	//		the mode
	// elementId: String
	//		the name of the DOM object
	// changeUrl: String
	//		the url for the current state of this page
	
		this.workAreaModeValue = workAreaModeValue;
		this.elementId = elementId; 
		this.changeUrl =  changeUrl;
		
		
	}
	
	}//end of CatalogSearchDisplayJS   
	
	CatalogSearchDisplayJS.HistoryTracker.prototype.back = CatalogSearchDisplayJS.goBack;
	CatalogSearchDisplayJS.HistoryTracker.prototype.forward=CatalogSearchDisplayJS.goForward;
	

