/******************************************************************

GOOGLE CODE: RAW SERACH 
	
The code contained in this file is based on a Google Search
API Raw Search example at the following URL:

http://code.google.com/apis/ajax/playground/#raw_search

The Raw Search approach requires a HIGH LEVEL OF CUSTOMIZATION and 
does not require the use of the Google Search Control elements.
It also allows usage of the free Google Search tools without 
the Google brand and without the ads/paid results.

******************************************************************/



///////////////////////////////
// -- SEARCH FORM CONTROL -- //
///////////////////////////////



// -- Set this variable to build the custom action value in the beginSearch function
var thisUrl = "/searchResults.aspx";





// Use this function in onSubmit of the search form element
// It writes a custom action value using the search query and
// the form processes using this dynamic, custom action value
function beginSearch()
{
	var searchQuery = document.getElementById("searchText").value;
	//Sets the action attribute to the proper
	document.getElementById("searchForm").action = thisUrl + "?sg=" + searchQuery;
}




////////////////////////////////
// -- PROCESS SEARCH QUERY -- //
////////////////////////////////


// Extract URL query variable into a local variable
var fullUrl = window.location.href.split('?');

if (fullUrl[1])
{
	var vars = fullUrl[1].split('&');
	var query = vars[0].substr(3);
}
else
{
	var vars = "";	
	var query = "";
	
}
//alert(vars[1]);

//var query = vars[0].substr(3);
var resultsContainer = document.getElementById('searchResults');
var searchInput = document.getElementById("searchText");




// -- Search restricted to this site
var targetSite = "http://dhims.health.mil";




// Top-level function 
// RUN ON SEARCH RESULTS PAGE AT 
// LOAD TIME AFTER RESULTS CONTAINER
function getSearchResults()
{
	// Check for presence of value/data in query variable
	if(!query)
	{
		document.getElementById("searchText").value = "";
		document.getElementById("searchNumbers").innerHTML = 'No search term was entered';
		document.getElementById("searchResults").innerHTML = 'Enter a search term in the box to the left';
	}
	else
	{
		document.getElementById("searchText").value = query;
		//document.getElementById("searchNumbers").innerHTML = 'Showing 1-10 of 300 for <strong>&quot;'+query+'&quot;</strong>';
	
		// LOAD GOOGLE SEARCH TOOLS 
		google.load('search', '1');
		
		// Initialize variable to be used as object later
		//var gs;
		window.gs;
		
		// Write pagination elements for multi-page results (max of 8 pages w/ free search tools)
		// Reference for .cursor google.search.Search property can be found at the following URL
		// http://code.google.com/apis/ajaxsearch/documentation/reference.html#_property_GSearch
		// This will provide descriptions of what is being used in this function
		function addPaginationLinks() 
		{
			// The cursor object has all things to do with pagination
			var cursor = gs.cursor;
			var curPage = cursor.currentPageIndex; // check what page the app is on
			var pagesDiv = document.createElement('div'); // create a container for the page links
			
			
			// Loop through the pages to create proper amount and style of pagination links
			for (var i = 0; i < cursor.pages.length; i++) 
			{
				
				var page = cursor.pages[i];
				if (curPage == i)
				{ 
					// if we are on the current page, then don't make a link
					var nolink = document.createElement('a');
					//nolink.href = '';
					nolink.title = "Page " + (i+1);
					nolink.innerHTML = page.label;
					nolink.className = "disabled";
					// Create provision for the last page to have a custom class
					if (i >= cursor.pages.length || i >= 7) // The limit of 8 items is used because the free search only returns 8 pages
					{
						nolink.className = "disabled last";	
					}
					pagesDiv.appendChild(nolink);
				} else 
				{
					// If we aren't on the current page, then we want a link to this page.
					// So we create a link that calls the gotoPage() method on the searcher.
					var link = document.createElement('a');
					link.href = 'javascript:gs.gotoPage('+ i +')';
					link.onclick = "gs.gotoPage("+ i +")";
					link.title = "Page " + (i+1);
					link.innerHTML = page.label;
					// Create provision for the last page to have a custom class
					if (i >= cursor.pages.length || i >= 7) // The limit of 8 items is used because the free search only returns 8 pages
					{
						link.className = "last";	
					}
					pagesDiv.appendChild(link);
				}
			
			}
			
			
			// Create a "previous" link with a style and link based on the current page
			var prevLink = document.createElement('a');
			prevLink.id = "prevLink";
			prevLink.title = "Previous";
			prevLink.innerHTML = "Previous";
			
			if (curPage == 0)
			{
				//prevLink.href = '#';
				prevLink.className = "disabled";
			}
			else
			{
				prevLink.href = "javascript:gs.gotoPage("+ (curPage-1) +")";
			}
			
			
			// Create a "next" link with a style and link based on the current page
			var nextLink = document.createElement('a');
			nextLink.id = "nextLink";
			nextLink.title = "Next";
			nextLink.innerHTML = "Next";
			
			if (curPage >= 7)
			{
				//nextLink.href = '#';
				nextLink.className = "disabled";
			}
			else
			{
				nextLink.href = "javascript:gs.gotoPage("+ (curPage+1) +")";
			}
				
			// Create the elements for the Previous and Next buttons	
			var searchPrev = document.createElement('div');
			searchPrev.id = "searchPrev";
			
			var searchNext = document.createElement('div');
			searchNext.id = "searchNext";
			
			
			
			// Clear the paginationBlock element
			// to keep from duplicating pagination elements
			document.getElementById('paginationBlock').innerHTML = "";
			
			
			
			
			// Do final write-in of each of the pagination elements
			
			
			searchPrev.appendChild(prevLink);
			document.getElementById('paginationBlock').appendChild(searchPrev);
			
			var pagesContainerDiv = document.createElement('div');
			pagesContainerDiv.id = "searchPages";
			pagesContainerDiv.appendChild(pagesDiv);
			document.getElementById('paginationBlock').appendChild(pagesContainerDiv);
			
			searchNext.appendChild(nextLink);
			document.getElementById('paginationBlock').appendChild(searchNext);
			

			// If there are more than the max number of custom search results,
			// create a link to "vector" to an expanded Google power search
			if (gs.cursor.estimatedResultCount > 64)
			{
				var moreLink = document.createElement('a');
				moreLink.href = gs.cursor.moreResultsUrl;
				moreLink.className = "moreResultsLink";
				moreLink.target = "_blank";
				moreLink.innerHTML = 'Click here to see an expanded list of results for <strong>"' + query + '"</strong> on Google.';
				document.getElementById('paginationBlock').appendChild(moreLink);
			}
			
		}
		
		
		
		// Reference for google.searchWebSearch() object can be found at the following URL
		// http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GwebSearch
		// This function initializes all of the required Google search functions,
		// utilizes object methods, sets custom properties for the object, and 
		// executes the query to get search results.
		function init() 
		{
			// Our WebSearch instance
			gs = new google.search.WebSearch();
			
			// Restrictions on the search
			gs.setSiteRestriction(targetSite);
			gs.setRestriction(google.search.Search.RESTRICT_SAFESEARCH,
										google.search.Search.SAFESEARCH_MODERATE);
			gs.setResultSetSize(google.search.Search.LARGE_RESULTSET);
			
			// Here we set a callback so that anytime a search is executed, it will call
			// the searchComplete function and pass it our WebSearch searcher.
			// When a search completes, our WebSearch object is automatically
			// populated with the results.
			gs.setSearchCompleteCallback(this, searchComplete, null);
			
			// Get the results
			gs.execute(query);
		}
		
		
		// Create custom results list after the search is executed
		function searchComplete()
		{
			
				
			//alert(gs.results.length);
			// Check that we got results
			if (gs.results && gs.results.length > 0) {
				// Grab our content div, clear it.
				var contentDiv = document.getElementById('searchResults');
				contentDiv.innerHTML = '';
				
				// Loop through our results, printing them to the page.
				var results = gs.results;
				for (var i = 0; i < results.length; i++) {
					
					// Create a variable that will contain only the data 
					// in the current results array element. This simplifies
					// the code below by not having to use brackets and the iteration variable.
					var result = results[i];
					
					// For each result write a <div> to contain the result elements
					var resultBlock = document.createElement('div');
					resultBlock.className = "resultBlock";
					
					// For each result write a <h3> element to contain the link
					var title = document.createElement('h3');
					
					// For each result write an <a> element and set its attributes and properties
					var titleLink = document.createElement('a');
					titleLink.href = result.unescapedUrl;
					titleLink.title = result.titleNoFormatting; // Removes formatting
					titleLink.innerHTML = result.title; // Leaves formtting tags like <i> and <b>
					
					// For each result write a <p> element to hold the result content
					var content = document.createElement('p');
					content.innerHTML = result.content;
					
					// For each result write a special <p> element to display the shortened link
					var dummyLink = document.createElement('p');
					dummyLink.className = "dummyLink";
					dummyLink.innerHTML = result.url;
					
					// Within the current resultBlock div write the elements
					// defined above. The appendChild will add to the contents of
					// the given target element.
					resultBlock.appendChild(title);
					resultBlock.appendChild(content);
					resultBlock.appendChild(dummyLink);
					title.appendChild(titleLink);
					
					// Put our title + image in the content
					contentDiv.appendChild(resultBlock);
					
					
				}
				
				
			
			}
			else if (gs.results.length == 0)
			{
					document.getElementById("searchNumbers").innerHTML = '0 results for "' + query + '"';
					document.getElementById("searchResults").innerHTML = 'Your search term returned 0 results.';
			}
			
			// Now add the paging links so the user can see more results.
			addPaginationLinks(gs);	
			
			// Display the total number of results
			document.getElementById("searchNumbers").innerHTML = gs.cursor.estimatedResultCount + ' results for <strong>&quot;'+query+'&quot;</strong>';
			
		}
		
		// 
		google.setOnLoadCallback(init);
		
	}
}
