google.load('search', '1');

//divBox will contain Search Results that are stored inside a div tag generated by google CSE
var divBox;

//iframeBox will be opened when a user clicks a search result.
var browseBox;

//variable to store the dhtml window for data tables listed under "Data by Discipline" etc.
var data_table;

//This is used to allow the browse window to be resized with the browser window is resized, but prevents the window from being re-opened each time. This just makes the process look a little cleaner, minimizing the flicker created by reopening the window
var browseResize = 0; 

//searchControl will hold the Search controls
var searchControl;

//a new div must be created each time a new search term is requested, dynDiv is incremented and used
//for the names of the new divs
var dynDiv = 1;

//global variables for the size and position of the dhtml windows, so if the user changes them and then opens a different 
//page they remain the same. 

//setting up more permanent storage for the browser height and width variables.

var browserHeight;
var browserWidth;


/**************************************************
 * This function sets up the google customSearcher
 * object, setting preferences for all searches.
 **************************************************/
function getBrowserSize() {
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    browserWidth = window.innerWidth;
    browserHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    browserWidth = document.documentElement.clientWidth;
    browserHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    browserWidth = document.body.clientWidth;
    browserHeight = document.body.clientHeight;
  }
  //window.alert( 'Width = ' + browserWidth );
  //window.alert( 'Height = ' + browserHeight );
}
getBrowserSize();

//sizes and position for Data Table window
var dtHeight = (browserHeight * .647)|0; //550
var dtWidth = (browserWidth * .742)|0;   //950
var dtTop = (browserHeight * .082)|0;  //70
var dtLeft = (browserWidth * .1484)|0;  //190
//handle the minimized versions of the window
var dtMin = 0;
var dtMinTop;
var dtMinLeft;

//sizes and positions for browse window
var browseHeight = (browserHeight * .906)|0; //775
var browseWidth = (browserWidth * .5)|0;  //640
var browseTop = (browserHeight * .0035)|0;  //3
var browseLeft = (browserWidth * .476)|0;  //610
//handle the minimized versions of the window
var browseMin = 0;
var browseMinTop;
var browseMinLeft;

//sizes and positions for results window
var resultHeight = (browserHeight * .685)|0;  //699
var resultWidth = (browserWidth * .468)|0;  //600
var resultTop = (browserHeight * .0035)|0;  //3
var resultLeft = (browserWidth * .0023)|0;  //3
//handle the minimized versions of the window
var resultMin = 0;
var resultMinTop;
var resultMinLeft;

//customSearcher object that will be manipulated by several functions.
var customSearcher;

//title of the browse window.
var datasetId = "Arcss Datasets";


/**************************************************
 * This function sets up the google customSearcher
 * object, setting preferences for all searches.
 **************************************************/
function OnLoad() {
	
	//create a search control, this is the searchbox, including text field and button.
	searchControl = new google.search.SearchControl();
	//Set the size of the results returned. LARGE can be replaced with SMALL 
	searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);

	//Tell the Searcher to open links in the same window.
	searchControl.setLinkTarget(document.getElementById("content"));

	//Create a variable that holds a WebSearch() object, this is the standard google search.
	customSearcher = new google.search.WebSearch();
	//Set the site restriction. This string is unique to the ARCSS custom search. 
	customSearcher.setSiteRestriction("005203271943822719354:vjvukaqsjk4");
	
	//Tells the Searcher to not omit any results (google sometimes omits results it deems similar)
	customSearcher.setRestriction(google.search.Search.RESTRICT_EXTENDED_ARGS, {"filter":"0"});

	//the options variable specifies multiple settings, before being passed to .addSearcher()
	var options = new google.search.SearcherOptions();
	
	//The Web Search has three different views that are selectable one the page. The first is not expanded and shows 1
	//result. The Second and third are both expanded, which is set in the command below. Once set to expanded you can 
	//then set the resultset size. Which is done above, as an attribute of searchControl.
	options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
	
	//This sets the root div tag where the search results will appear. 
	options.setRoot(document.getElementById("content"));
	searchControl.addSearcher(customSearcher, options);

	//When a search is completed, the function Window() is called.
	searchControl.setSearchCompleteCallback(customSearcher, Window);

	//Sets a String to return when No results are found.
	searchControl.setNoResultsString("No Results");

	//this variable holds drawOptions, similar to the options above it can contain multiple options settings that will
	//later be passed as one parameter.
	var drawOptions = new google.search.DrawOptions();
	drawOptions.setInput(document.getElementById("inputElement"));
	//drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);

	//Tell the searhcer to draw itself and tell it where to attach
	searchControl.draw(document.getElementById("searchControl_div"), drawOptions);


	//Set the initial search parameter to be searched on load.
	//searchControl.execute("sturm");


	}
	google.setOnLoadCallback(OnLoad);

/**************************************************
 * This function takes a string and removes the div
 * with that name which is a child of 'content'
 **************************************************/

function removeElement(divNum) {
  var d = document.getElementById('content');
  var olddiv = document.getElementById(divNum);
  d.child = olddiv;
  d.removeChild(olddiv);
}

/**************************************************
 * This function watches for the browser window 
 * being re-sized, and updates dhtml vars accordingly
 **************************************************/

window.onresize = function (){

//update browser sizes
getBrowserSize();

dtHeight = (browserHeight * .647)|0; //550
dtWidth = (browserWidth * .742)|0;   //950
dtTop = (browserHeight * .082)|0;  //70
dtLeft = (browserWidth * .1484)|0;  //190

browseHeight = (browserHeight * .906)|0; //775
browseWidth = (browserWidth * .5)|0;  //640
browseTop = (browserHeight * .0035)|0;  //3
browseLeft = (browserWidth * .476)|0;  //610

//resizes and positions for browse window
browseHeight = (browserHeight * .906)|0; //775
browseWidth = (browserWidth * .5)|0;  //640
browseTop = (browserHeight * .0035)|0;  //3
browseLeft = (browserWidth * .476)|0;  //610

//resizes and positions for results window
resultHeight = (browserHeight * .685)|0;  //699
resultWidth = (browserWidth * .468)|0;  //600
resultTop = (browserHeight * .0035)|0;  //3
resultLeft = (browserWidth * .0023)|0;  //3


//ensures the browse window isn't recreated
browseResize = 1;

//Once the dimensions are updated we can use setSize() and moveTo() functions to dynamically update the windows
if(dtMin == 0 && data_table != null){
	data_table.setSize(dtWidth, dtHeight);
	}else if(dtMin == 1 && data_table != null){
	data_table.moveTo(((data_table.minimizeorder * 0.1953 * browserWidth)|0), (0.95855 * browserHeight)|0);
	}

if(resultMin == 0 && divBox != null){
	divBox.setSize(resultWidth, resultHeight);
	}else if(resultMin == 1 && divBox != null){
	divBox.moveTo(((divBox.minimizeorder * 0.1953 * browserWidth)|0), (0.95855 * browserHeight)|0);
	}

if(browseMin == 0 && browseBox != null){
	browseBox.setSize(browseWidth, browseHeight);
	browseBox.moveTo(browseLeft, browseTop);
	}else if(browseMin == 1 && browseBox != null){
	browseBox.moveTo(((browseBox.minimizeorder * 0.1953 * browserWidth)|0), (0.95855 * document.body.clientHeight)|0);
	}
}

/******************************************************************
 * This function gets the total number of results including the 
 * current page, but not beyond the current page. 
 * It takes a Searcher object as a parameter and returns the total
 *****************************************************************/

function getTotalResults(cs){
   var total;
   //8 results per page (assuming LARGE_RESULTSET)
   if(cs.cursor != null){
	//8 per page
   	total = ((cs.cursor.currentPageIndex)*8);
	//count the results on the current page
	total += cs.results.length;
   }

   return total;
}




/************************************************************
 * This function takes a customSearcher object, and the name 
 * of the div where results are stored. It adds links to the
 * specified div. These links (at the bottom of the div) 
 * provide forward/backward home/end navigation features. 
 ***********************************************************/

function addNavigationLinks(cs, name) {
  var curPage = cs.cursor.currentPageIndex; // check what page the app is on
  var nexPage = curPage + 1; //set the next page
  var prePage = curPage - 1; //set the previous page
  var home = 0; //home is always page 0
  var end = cs.cursor.pages.length - 1; //set the end page
  
  //pagesDiv will contain all the navigation controls
  var pagesDiv = document.createElement('div');

      //ADD PREV LINK
      if(curPage != home){//don't display PREV link when on home page
      var preLink = document.createElement('a'); //create the element
      preLink.href = 'javascript:customSearcher.gotoPage('+prePage+');';//point to previous page
      preLink.innerHTML = "PREV [<]"; //displayed text
      preLink.className = 'nav-on'; //class name for css
      pagesDiv.appendChild(preLink); //append to pagesDiv
      }else{
      var preLink = document.createElement('a'); //if on the home page display prev grayed out
      preLink.innerHTML = "PREV [<]"; //displayed text
      preLink.className = 'nav-off'; //class name for css
      pagesDiv.appendChild(preLink); //append
      }
      
      //ADD SPACER
      var space1 = document.createElement('a');
      space1.className = 'nav-spacer';
      space1.innerHTML = "  ";
      pagesDiv.appendChild(space1);

      //ADD NEXT LINK
      if(curPage != end){
      var nexLink = document.createElement('a');
      nexLink.href = 'javascript:customSearcher.gotoPage('+nexPage+');';
      nexLink.innerHTML = "NEXT [>]";
      nexLink.className = 'nav-on';
      pagesDiv.appendChild(nexLink);
      }else{
      var nexLink = document.createElement('a');
      nexLink.innerHTML = "NEXT [>]";
      nexLink.className = 'nav-off';
      pagesDiv.appendChild(nexLink);
      }

      //ADD SPACER
      var space2 = document.createElement('a');
      space2.className = 'nav-spacer';
      space2.innerHTML = "  ";
      pagesDiv.appendChild(space2);

      //ADD HOME LINK
      if(curPage != home){
      var homeLink = document.createElement('a');
      homeLink.href = 'javascript:customSearcher.gotoPage('+home+');';
      homeLink.innerHTML = "HOME [<<]";
      homeLink.className = 'nav-on';
      pagesDiv.appendChild(homeLink);
      }else{
      var homeLink = document.createElement('a');
      homeLink.innerHTML = "HOME [<<]";
      homeLink.className = 'nav-off';
      pagesDiv.appendChild(homeLink);
      }

      //ADD SPACER
      var space3 = document.createElement('a');
      space3.className = 'nav-spacer';
      space3.innerHTML = "  ";
      pagesDiv.appendChild(space3);

      //ADD END LINK
      if(curPage != end){
      var endLink = document.createElement('a');
      endLink.href = 'javascript:customSearcher.gotoPage('+end+');';
      endLink.innerHTML = "END [>>]";
      endLink.className = 'nav-on';
      pagesDiv.appendChild(endLink);
      }else{
      var endLink = document.createElement('a');
      endLink.innerHTML = "END [>>]";
      endLink.className = 'nav-off';
      pagesDiv.appendChild(endLink);
      }

      //ADD SPACER
      var space3 = document.createElement('a');
      space3.className = 'nav-spacer';
      space3.innerHTML = "<br><br>";
      pagesDiv.appendChild(space3);

      //If displaying a total of 64 results then add a link to google for additional results
      if( (cs.cursor.currentPageIndex == 7) && (cs.results.length == 8) ){
      var space4 = document.createElement('p');
      pagesDiv.appendChild(space4);
      var moreLink = document.createElement('a');
      moreLink.href = "http://www.google.com/cse?cx=005203271943822719354%3Avjvukaqsjk4&ie=UTF-8&q=" + document.getElementById('inputElement').value + "&sa=Search";
      moreLink.target = "_blank"; //open link in a new tab
      moreLink.innerHTML = "More results @ Google";
      moreLink.className = 'nav-on';
      pagesDiv.appendChild(moreLink);
      }

  //Append pagesDiv to the contentDiv
  var contentDiv = document.getElementById(name);
  contentDiv.appendChild(pagesDiv);
}



/*********************************************************************
 * This function takes a string containing search results, the 
 * customSearcher object being used, and the total # of results.
 * It returns the same string but all links open in a new dhtml window.
 *********************************************************************/

function buildResults(text, cs, total)
{

	//loop counter
	var current = 0;	

	//insertionPoints will split the search results html at a point where onclick="" can be added
	var insertionPoints = new Array();
	insertionPoints = (text.split("href=\""));

	//String to rebuild the Search results html in. 
	var cleanedResults = "";
	cleanedResults = "Search query: " + document.getElementById('inputElement').value + "<br>" + "There are " + total + " results in pages 1 - " + (cs.cursor.currentPageIndex + 1) + "<br>" + "You are currently on Page: " + (cs.cursor.currentPageIndex + 1) + "<br>" + "<br>" ;

	//holds Search results split on "http"
	var trashURLs = new Array();
	
	//list of URLs for the search results once they have been cleaned.
	var URLs = new Array();

	//create trashURLs
	trashURLs = (text.split("http"));
	
	//Pull just the URL out of trashURLs and insert it into URLs
	for(current=0;current<trashURLs.length;current=current+1)
	{
	URLs[current] = "http" + trashURLs[current].substr(0, trashURLs[current].indexOf('"'));
	}
	
	

	//Add an onclick tag to the insertionPoints array. This onclick will open the URL in a dhtmlwindow
	for(current=0;current<insertionPoints.length;current=current+1)
	{
	//extract the datasetId to use for the window title
	if(URLs[current+1] != null){
	datasetId = ((URLs[current+1]).split("="))[1];
		//make sure there isn't a trailing '/' left on the datasetId
		if (datasetId != null){
			var dLength = datasetId.length;
			if (datasetId.substr(dLength-1, 1) == '/'){
				datasetId = datasetId.substr(0, dLength-1);
			}
		}
	}
	//add in code to open the result in a dhtml window when clicked.
	insertionPoints[current] = insertionPoints[current].substr(0, (insertionPoints[current].length - 1)) + " onclick=\" browseBox = dhtmlwindow.open('browseBox', 'iframe',' " + URLs[current+1] + "', '" + "ARCSS data sets" + "', 'width=' + browseWidth + 'px,height=' + browseHeight + 'px,left=' + browseLeft + 'px,top=' + browseTop + 'px,resize=1,scrolling=1');\" ";
	}

	//Build the cleanedResults string from the insertionPoints array.
	for(current=0;current<(insertionPoints.length -1);current=current+1)
	{
	cleanedResults = cleanedResults + String(insertionPoints[current]) + insertionPoints[current+1].substr(0, insertionPoints[current+1].indexOf('>'));
	}
	return cleanedResults;	

}


/***********************************************
* This function is the main body of the search.
* It calls all the helper functions as needed.
* And sets up the dhtml windows based on the 
* user input.
***********************************************/
function Window(result) {

	//reset the total for this search.
	var total = 0; 
	//reset the minimized state for both of the search windows. 
	resultMin = 0;
	browseMin = 0;

	//as long as something hasn't gone wrong, get the total and build the Results page
	if(customSearcher.cursor != null){
	total = getTotalResults(this);
	cleanedResults = buildResults(document.getElementById("content").innerHTML, this, total);
	}else{cleanedResults = "<h1>No Datasets Found.</h1>" + "Search Query: " + document.getElementById('inputElement').value;} //catch queries that return no results.

	
	//Create a new blank div container
	newDiv1 = document.createElement("div");
	
	//The div container "content" contains the search results for your custom search.
	//This line sets the contents of the newly created newDiv1 to be a copy of "contents"
	newDiv1.innerHTML = cleanedResults;
	
	//window.name contains an incremented value to give the new div container a unique id.
	dynDiv = dynDiv + 1;
	
	//convert window.name to a string so it can be used as an id
	var name = String(dynDiv);

	//set the id of the new div container.
	newDiv1.id=(name);
	
	//insert the div container into the body of the html page.
	//document.body.insertBefore(newDiv1, document.getElementById("content"));
	
	var container = document.getElementById("content");
	container.appendChild(newDiv1);
	
	//As long as nothing has gone wrong, add navigation links.
	if(customSearcher.cursor != null){
	addNavigationLinks(this, name);
	}

	//only open up a fresh browse window if there isn't already one active
	if((browseBox == null) || (browseResize == 1)) {
	//open the browse dhtml window displaying the Arcss datasets main page.
	browseBox = dhtmlwindow.open('browseBox', 'iframe','http://data.eol.ucar.edu/codiac/projs?ARCSS', 'ARCSS data sets', 'width=' + browseWidth + 'px,height=' + browseHeight + 'px,left=' + browseLeft + 'px,top=' + browseTop + 'px,resize=1,scrolling=1');
	browseResize =0;
	}

	//create the dhtml results window displaying the newly created div container with the copied search results.
	divBox = dhtmlwindow.open('box', 'div', name, 'Search Results', 'width=' + resultWidth + 'px,height=' + resultHeight + 'px,left=' + resultLeft + 'px,top=' + resultTop + 'px,resize=1,scrolling=1');

	//remove the newly created div now that its content has been loaded into the dhtml window.
	removeElement(dynDiv);

}
