//<%--
//********************************************************************
//*-------------------------------------------------------------------
//* 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:"",     
		isHistory:false,
		
		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	
			
			var methodName = "changeSearchMode ";
			dojo.debug(methodName + CatalogSearchDisplayJS.searchModeVisible);				
						
			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 != null && advancedSearchCheckBox.checked){
					if ( simpleSearchDiv != null )
						dojo.html.hide(simpleSearchDiv);
					if ( advancedSearchDiv != null )
					dojo.html.show(advancedSearchDiv);
					
				}else{
					if ( advancedSearchDiv != null )
						dojo.html.hide(advancedSearchDiv);
					if ( simpleSearchDiv != null )
						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 != null && advanced){
				advancedSearchCheckBox.checked = true;
			}

			if(CatalogSearchDisplayJS.searchModeVisible == "true"){
				if ( simpleSearchDiv != null )
					dojo.html.hide(simpleSearchDiv);
				if ( advancedSearchDiv != null )
					dojo.html.hide(advancedSearchDiv);
				if ( searchFlipperDiv != null )
					dojo.html.hide(searchFlipperDiv);
				if ( searchResultDiv != null )
					dojo.html.show(searchResultDiv);
				CatalogSearchDisplayJS.searchModeVisible = "false";
			}else{
				if ( searchFlipperDiv != null )
					dojo.html.show(searchFlipperDiv);
				CatalogSearchDisplayJS.searchModeVisible = "true";
				CatalogSearchDisplayJS.changeSearchMode();
				if ( searchResultDiv != null )
					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.	
			
			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);
			CatalogSearchDisplayJS.searchMode = "advanced"
			//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, '');
		
		
			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?&orderBy1=CatEntDescName&orderByOperator1=ascOperator&" + queryString;
			dojo.debug(methodName + " url: " + searchUrl);
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").formId = formId;
			//wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = "AjaxCatalogSearchResultView";
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = searchUrl;
			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;
	    	dojo.debug("url is "+changeUrl);	
	    		//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});
			
			
		},
		
		goToResultPage:function(resultPageURL,pagesize)
		// 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(); 	
			if(pagesize == "PriceDesc" ){
				
				resultPageURL = resultPageURL + "&orderBy1=OfferPricePrice&orderByOperator1=descOperator" ;
			} else if(pagesize == "PriceAsc" ){
				
				resultPageURL = resultPageURL + "&orderBy1=OfferPricePrice&orderByOperator1=ascOperator" ;
			} else if(pagesize == "NameAsc" ){
				
				resultPageURL = resultPageURL + "&orderBy1=CatEntDescName&orderByOperator1=ascOperator" ;
			} else if(pagesize == "NameDesc" ){
				
				resultPageURL = resultPageURL + "&orderBy1=CatEntDescName&orderByOperator1=descOperator" ;
			}
			else {
			
				resultPageURL = resultPageURL + "&pageSize=" + pagesize;
				
				}
			wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = resultPageURL;
			//alert("result page url is " + resultPageURL);
			wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsURL: resultPageURL});
			
			
		},
		
		
		submitJumpToSearch:function(pageNo,resultPageURL){
		// 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) {
				var beginIndex = (pageNo - 1) * pageSize;		
					cursor_wait();
		       		//var queryString = dojo.io.encodeForm(dojo.byId(formId));
		      
				//var searchUrl = "AjaxCatalogSearchResultView?" + queryString;
				resultPageURL = resultPageURL +"&beginIndex=" +beginIndex;
				//wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").formId = formId;
				wc.render.getRefreshControllerById("catalogSearchResultDisplay_Controller").url = resultPageURL;
				wc.render.updateContext("catalogSearchResultDisplay_Context", {searchResultsURL:resultPageURL} );	
				
				
			//} 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 loc = new String(document.location); 
			var simpleSearchParams = loc.split('?');			
			// Url is for category product display
			if(simpleSearchParams[1] == null) {			
				var prodDisplayParams = loc.split('_');					
				var params = "";
				for(var i=1;i<prodDisplayParams.length;i++){				
					params = params +"_"+ prodDisplayParams[i];
				}	
				wholeUrl = "prodCatResultsDisplay" + params ;				
			} // Url is for simple search
			else {
					var search = location.search;
					dojo.debug( " search is " + 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;
	
