
///////////////////////////////////////////////////////
// Update the "content area" (right hand side) of the 
// book player with the book chapter/section indicated
// by the specified eid.
//

// Register the left pane tab module with the ajax history manager:
function initSearchHistory() {
	// Is there an initial search for populating the search pane?
	// Try it from the hash (the "bookmarked state"):
	var initialSearch = YAHOO.util.History.getBookmarkedState( "search" );
	
	// And if that doesn't work...
	if(!initialSearch || initialSearch == "") {
		// Try to get it directly from the hash:
		initialSearch = getParam(window.location.hash, "search");		
	}
		
	// Otherwise try it from the query string:		
	if(!initialSearch || initialSearch == "") {
		initialSearch = YAHOO.util.History.getQueryStringParameter( "searchQuery" );
		
		// If a search query it can optionally indicate if it's a new search,
		// or a more results/next page search:			
		if(initialSearch || initialSearch == "") {
			var searchType = YAHOO.util.History.getQueryStringParameter( "searchType" );
			if(searchType && searchType != "") {
				// Within the state string we use ; instead of &:
				initialSearch = initialSearch + ';type=' + searchType;
			}
			// We may also know which page of the search results:
			var pageNum = YAHOO.util.History.getQueryStringParameter( "searchPg" );
			if(pageNum && pageNum != "") {
				// Within the state string we use ; instead of &:
				initialSearch = initialSearch + ';pg=' + pageNum;
			}			
		}			
	}
				
	if(!initialSearch) {
		// We chose to use "none" since it looks odd in the url to have "search=" (nothing)
		initialSearch = "none";  // No search by default
	}		

	// Register our "search" module. Module registration MUST take
	// place before calling YAHOO.util.History.initialize.
	YAHOO.util.History.register( "search", initialSearch, 
		function( searchState ) {
			// This is called after calling YAHOO.util.History.navigate, or after the user
			// has trigerred the back/forward button. We cannot discrminate between
			// these two situations.
			updateSearchArea("searchTab", searchState); 
			
			// The url hash has changed - remember the current url in a cookie for
			// returning to the book player from supplemental content pages: 
			rememberCurrentBookPlayerUrl();										
		}
	);

	// Subscribe to this event before calling YAHOO.util.History.initialize,
	// or it may never get fired! Note that this is guaranteed to be fired
	// after the window's onload event.
	YAHOO.util.History.onLoadEvent.subscribe( 
		function() {
			activateSearchArea();
		} 
	);
}

// This function doesn't do much right now.  *If* we use a cookie at some
// point to remember their last search, this is where it would be read
// (i.e. if/when the history manager returns no current search state).
function activateSearchArea() {
	// The window's onload handler is called when the user comes back to 
	// our page using the back button.
	var currentSearch = YAHOO.util.History.getCurrentState( "search" );
	if (currentSearch && currentSearch != "none") {		
		updateSearchArea("searchTab", currentSearch);		
	}	
}

// Handle when the user clicks on a link that runs a search
// Note:  This is displayed in the search area on the left (it does not add a history entry)
function searchAnchorSelected()
{								
	// 'this' should be the actual anchor tag DOM element...								
	if(this.eid) {	
	
		// Construct a search "state" in the form we're using with the
		// ajax history manager:	
		var searchState = toSearchState(this.searchQuery, this.searchType, 
							this.searchScope, this.textSearchPage);
					
		// If the Browser History Manager was not successfuly initialized,
		// the following call to YAHOO.util.History.navigate will throw an
		// exception. We need to catch it and update the UI. The only
		// problem is that this new state will not be added to the browser
		// history.
		try {
			YAHOO.util.History.navigate( "search", searchState );
		} catch ( e ) {
			updateSearchArea("searchTab", searchState);	 		
		}					
						
		// Don't follow the link we're updating via Ajax.
		return false; 				
	}
}

// Construct a search "state" in the form we're using with the
// ajax history manager:
function toSearchState(searchQuery, searchType, scope, pageNum) {

	var searchState = searchQuery;
	if(searchType) {
		searchState += (";type=" + searchType);
	}
	if(pageNum) {
		searchState += (";pg=" + pageNum);
	}
	if(scope && scope != "Books") {
		searchState += (";scope=" + scope);
	}
	
	return searchState;
}

function updateSearchArea(searchAreaDivId, searchState) {
	if(!searchState) {
		return;
	} 
	
	if(searchState == "none") {
		// No search results:	
		setElementValue("searchQuery", "");
		
		var searchAreaElement = dojo.byId(searchAreaDivId);
		if(searchAreaElement) {
			searchAreaElement.innerHTML = "";
				
		}
		
		return;
	}

	// The eid is just the top level eid in our address line:	
	var eid = getQueryParam(window.location.href, "eid");

	// The default search is simply the search query, but it can
	// optionally have semicolon delimited "parts" for type and page num.
	var stateParts = searchState.split(";");
	
	var searchQuery = stateParts[0];
	var scope = "Books";	
	var textSearchPage = "1";
	var searchType = "new";	
	if(stateParts.length > 1) {
		// For each semi colon delimited part of the "state":
		for(var part=1;part<stateParts.length;part++) {		
			var partNvp = stateParts[part].split("=");
			if(partNvp.length > 1) {
				if(partNvp[0] == "type") {
					searchType = partNvp[1];				
				}			
				if(partNvp[0] == "pg") {
					textSearchPage = partNvp[1];				
				}
				if(partNvp[0] == "scope") {
					scope = partNvp[1];				
				}				
			}
		}
	}

	searchQuery = escape(searchQuery);
	
	var url = "search.dx?method=getSearchResults&eid=" + eid + 
				"&searchType=" + searchType + 
				"&searchScope=" + scope + 
				"&searchQuery=" + searchQuery +
				"&textSearchPage=" + textSearchPage;
	
	// Allow that left pane might not be there: 
	var xPane = getElsExpansionPane(); 
	var smartTabs = getElsSmartTabs(); 		
		
	var ioRequest = {
		method: "GET",
		url: url,

		// Data for use once we have data for an elsBookPlayerState object
		// layoutContainerId: "main",
		xPane: xPane,	
		smartTabs: smartTabs,			
		areaDivId: searchAreaDivId,
		load: handleSearchUpdate,
		error: handleAjaxError,
		searchQuery: searchQuery,
		searchType: searchType,
		eid: eid,				
			
		timeoutSeconds: 15,
		timeout: handleAjaxTimeout
	};

	displayAjaxSpinner("bookContentPane");	
	
	userActivity(); // the user's done something!		
	dojo.io.bind(ioRequest);	
}

// A Dojo Ajax handler 
// (Dojo defines this parameter signature) 
function handleSearchUpdate(type, htmlData, xhrObject, ioRequest) {

	hideAjaxSpinner("bookContentPane");

	// Make sure the search field always shows the search query corresponding
	// to these results (e.g. this could be happening because they hit the 
	// back button:
	if(ioRequest.searchQuery) {
		var query = unescape(ioRequest.searchQuery);
		// For some reason the escaped spaces are changing to
		// plus signs but not unescaping:
		query = query.replace(/\+/gi, " ");
		setElementValue("searchQuery", query);
	}
	
	// Change the contents to show the new search results
	var searchAreaElement = dojo.byId(ioRequest.areaDivId);
	if(searchAreaElement) {	
		searchAreaElement.innerHTML = htmlData;	
	
	}

	cvtAnchorsToUseAjax(ioRequest.areaDivId, "search");
	
	// The app can define a javascript variable "webAnalyticsTracker" to call a method
	// for tracking the ajax changes - e.g. we have one called "trackGoogleAnalytics"
	// in bookUtils.js:
	if((typeof(webAnalyticsTracker) != 'undefined') && webAnalyticsTracker) {
		// "normalize" the search query so that the tracker ignores upper/lower case, etc.:
		var trackerUrl;		
		var normalizedQuery = normalizeSearchQuery(getQueryParam(ioRequest.url, "searchQuery"));
		if(normalizedQuery) {
			trackerUrl = setQueryParam(ioRequest.url, "searchQuery", normalizedQuery, false);
			webAnalyticsTracker(trackerUrl);			
		}  
	}
		
	// NOTE:  Safari on Macintosh always showed a blank search
	//        results tab until this navigate was moved here to
	//        the end of this method (presumably to *after*
	//        the search tab's innerHTML was set.
	
	// Make the search tab be the active (forward) one:
	try {
		YAHOO.util.History.navigate( "lpTab", "searchTab" );
	} catch ( e ) {
		if(ioRequest.smartTabs) {
			ioRequest.smartTabs.activateTab("searchTab");
		}			
	}													
}

// Normalize the search query to the analytics engine gets consistent data.  We:
//  	a.  Lower case it.
//  	b.  Change spaces to plus signs.
//  	c.  Change %20 (encoded spaces) to plus signs.
// Note:  We send plus signs instead of spaces to google analytics because otherwise
//        it shows %20's (it can't seem to show spaces due to a problem on their end).
 
function normalizeSearchQuery(query) {
	var normalizedQuery = query.toLowerCase();
	normalizedQuery = 	normalizedQuery.replace(/ /g,'+');		
	normalizedQuery = 	normalizedQuery.replace(/\%20/g,'+');
	return normalizedQuery;
}

// Perform the search when the user clicks the search/go button
function performSearch() {
	var scope = getElementValue("searchScope");
	if(!scope || scope == undefined) {
		scope = "Books";
	}
	
	var searchQuery = getElementValue("searchQuery");
	var searchType = getElementValue("searchType");
	
	// This is the new search		
	var searchState = toSearchState(searchQuery, searchType, scope);

	// What was the last search?
	var currentState = YAHOO.util.History.getCurrentState( "search" );		

	var smartTabs = getElsSmartTabs();

	if(searchState != currentState) { 
		// If the Browser History Manager was not successfuly initialized,
		// the following call to YAHOO.util.History.navigate will throw an
		// exception. We need to catch it and update the UI. The only
		// problem is that this new state will not be added to the browser
		// history.
		try {
			YAHOO.util.History.navigate( "search", searchState );
		} catch ( e ) {
			updateSearchArea("searchTab", searchState);	 		
		}
	}
	else {	
		// The search query is the same as before!
		// Just make the search tab be the active (forward) one:
		try {
			YAHOO.util.History.navigate( "lpTab", "searchTab" );
		} catch ( e ) {
			if(smartTabs) {
				smartTabs.activateTab("searchTab");
			}			
		}	
	}
		
	// If we use Yahoo history manager to "navigate" the index
	// forward, things blow up - so we don't.  But this means
	// the browser history doesn't know that index is forward
	// in the "lpTab" setting of the browser hash.  Compensate 
	// here by *always* forcing it forward:			
	if(smartTabs.activeTab() == "indexTab") {			
		if(smartTabs) {
			smartTabs.activateTab("searchTab");		
		}
	}				
}


