var searchNum = 0;
var lastSearch;
var loggedIn = false;
var bannerBrand;


/*
 * Standard callback function for RSH (Really Simple History)
 * Loaded when the browser back or forward buttons have been pressed.
 * 
 */
var historyChange = function(newLocation, historyData) 
{			
	//alert("NewLocation: " + newLocation);
	if (newLocation != "")
		loadEntryPage("#"+newLocation, "",true,null);
}

   /*
    * Initialize RSH (Really simple History
    */
   function initializeHistory()
   {
   	window.dhtmlHistory.initialize();
   	window.dhtmlHistory.addListener(historyChange);   	
   }

	String.prototype.startsWith = function (a) {
		return this.substr(0, a.length) === a;
	}

   /*
    * Called when the Statistical web page is loaded first time. If the URL was bookmarked,
    * the anchor hash will contain extra data which will be used to restore the bookmarked state.
    * The anchor hash starts with #search for a search page, #main for the first screen.
    */
   function loadEntryPage(anchorHash, product, history, defaultSearchType)
   {		   
	   //alert(anchorHash.length);
	   //alert(product);
	   var posamp = anchorHash.indexOf("&");		   
  	   var queryString = anchorHash.substring(posamp+1,anchorHash.length);
  	   
	   sub = anchorHash.substring(1,anchorHash.length);
	   
	   var hist = "";
	   
	   if (history)
		   hist = "&histchange=true";	   	   
	   	   
	   if (anchorHash.startsWith("#datasets") || (anchorHash.length == 0 && product=='DS'))
	   {
		   getPageSynch("content", "Product=DS"+hist, "GET", "maincontent",null);   
	   }
	   else
	   {
		   var pos = queryString.indexOf("searchtype");
		   var type;
		   if (pos >= 0)
		   {
			   if (queryString.substring(pos+11).startsWith("basic"))
				   type = "basic";
			   else
				   type = "advanced";
		   }
		   else
		   {
			   if (defaultSearchType)
				   type = defaultSearchType;
			   else
				   type = "basic";
		   }
		   getPageSynch("content", "Product=ST"+hist+"&searchtype="+type, "GET", "maincontent",null);
		   if (anchorHash.startsWith("#search"))
		   {		   		   		   		
			    // there is a number after #search (required by RSH to make a unique entry), and will be igored. 
			   	// The query string containing the state of the search is after the first &
			   		   		
				loadSearch(queryString,sub,queryString,true);			   		
		   }
		   else 
		   {		   
			    loadMainPage();					   
		   }
	   }
   }
   
   /**
    * loads the welcome page
    */
   function loadMainPage()
   {	
	   var type;
	   if ($('searchselector').Searchtype[0].checked)
	      type = "basic";
	   else
		  type = "advanced";
	    	  
	     
	   searchNum = searchNum + 1;
	   
	   queryString = "terms=<Enter Search Term>&start=1&limit=10&sort=relevance&facets=&searchtype="+type;
   	   // add parameters for search history, constructed from the query string
   	   loadSearch(queryString,"search"+searchNum+"&"+queryString,queryString,true);   	      	     
   }
      
   var prevQueryTerm = "";
   var prevFacetTerm = "";
   var prevSearchType = "";
   
   /**
    * Loads a new search page
    * 
    * @param queryString  contains the search parameters (terms, starting position of search results etc.)
    * @param loadFacets  boolean true/false to determine if the facets div will be updated
    */
   function loadSearchPage(loadFacets)
   {				  	   
	   var searchFormID = 'search';
	   var term = getFormValue(searchFormID,"terms");
	   var facet = getFormValue(searchFormID,"facets");
	   var searchtype = getFormValue(searchFormID,"searchtype")
	   
	   if (term != prevQueryTerm || facet != prevFacetTerm || searchtype != prevSearchType)
	   {		   
		   // make the first search hit the default whenever a new search has been made		
		   setFormValue(searchFormID,"start","1");		   
		   prevQueryTerm = term;
		   prevFacetTerm = facet;
		   if (prevSearchType != "" && searchtype != prevSearchType)
		   {
			  if (searchtype == "basic")
				  $(searchFormID).terms.value = "<Enter Search Term>";
			  else
				 $(searchFormID).terms.value = "";
		   }
		   prevSearchType = searchtype;
		   clearBatch();
	   }
	   
	   var queryString = getFormQueryString(searchFormID);
	   //alert(queryString);
	   
   	   searchNum = searchNum + 1;   	
   	   // add parameters for search history, constructed from the query string
   	   loadSearch(queryString,"search"+searchNum+"&"+queryString,queryString,loadFacets);   	   	   	   	   		   
   }
        
      
   function loadDatasetsView(index)
   {
	   switchToDatasets("view=true&index="+index);	  
   }
   
   function loadDatasetsHistory(index)
   {
	   switchToDatasets("history=true&index="+index);	  
   }
   
   function loadSearchPageWithQueryString(queryString)
   {				  	   
	   
	   if (isDatasets())
	   {	
		   switchToStatistical("");		   			      			    
	   }
	   
	   var searchtype = getQueryVariable(queryString,'searchtype');
	   
	   if (searchtype == "basic")		
		   $('searchselector').Searchtype[0].checked = true;		   
	   else
		   $('searchselector').Searchtype[1].checked = true;
	   
	   searchNum = searchNum + 1;   	
	   // add parameters for search history, constructed from the query string
	   loadSearch(queryString,"search"+searchNum+"&"+queryString,queryString,true);   	   	   	   	   		   
	   
   }
   
   
   function setLoggedIn(loggedInParam)
   {
	   loggedIn = loggedInParam;
	   if (loggedIn)
	   {
		   closeMenu('menu1');
		   setDivVisible('searchesClass',true);
		   getPageSynch('Profile','','POST','menu1',null);
		   getPageSynch('SavedSearches','','POST','SavedSearchesMenu',null);
		   getPageSynch('SearchHistory','','POST','LastSearchMenu',null);
		   appletResize();
	   }
   }
   
   /**
    * 
    * @return has the user logged in to the profile
    */
   function isLoggedIn()
   {
	   return loggedIn;
   }
   
   function searchPageLoaded(queryString)
   {
	   var terms = getQueryVariable(queryString,"terms");
	   var facets = getQueryVariable(queryString,"facets");
	   var searchtype = getQueryVariable(queryString,"searchtype");
	   getPageSynch('Facet','terms='+terms+'&facets='+facets+'&searchtype='+searchtype,'POST','facetdiv',null);
   }
   
   var queryStringT;
   var newLocationT; 
   var historyDataT;
   var loadFacetsT;
   
   function loadSearch(queryString,newLocation, historyData, loadFacets)
   {	    	   	    
	    $('main').innerHTML = "<div style='color:#C8C8C8; margin-left:200px;margin-right:200px;margin-top:300px;margin-bottom:0px;'><p><h2>Loading...</p></h2></div>";
	    queryStringT = queryString;
   		newLocationT = newLocation;  
   		historyDataT = historyData;
   		loadFacetsT = loadFacets;
   		setTimeout(loadSearchTimer,0);
   		
   }
   
   function loadSearchTimer()
   {
	    var queryString = queryStringT;
   		var newLocation = newLocationT;  
   		var historyData = historyDataT;
   		var loadFacets = loadFacetsT   	    
	    
	    lastSearch = queryString;	    
	    var callback = loadFacets ? searchPageLoaded : null;
	    
	    
	    var type = getQueryVariable(queryString,"searchtype");
	    
	    var searchName;
	    
	    if (type == "basic")
	    	searchName = "SearchBasic";
	    else if (type == "advanced")
	    	searchName = "SearchAdvanced";
	    
		getPageWithHistorySynch(searchName,queryString,'POST','main',newLocation,historyData,callback);	   	
	   	$('facetdiv').show();
	   	//$('footer').hide();
	   	
	   	if (isLoggedIn())
	   	{
	   		var terms = getQueryVariable(getLastSearch(),'terms');
	   		if (terms == null)
	   			alert("No search Terms!");
	   		else
	   			getPage('SearchHistory','queryString='+c_urlencode(queryString)+'&name='+terms,'POST','LastSearchMenu',null);
	   	}
   }
   
   
   /**
    * Gets the query string for the last search performed.
    * 
    */
   function getLastSearch()
   { 	   
	   return lastSearch;
   }
         
   
   /**
    * Called when a user add a new saved search (see /jsp/SavedSearches.jsp).
    */
   function processCurrentSearch()
   {
	   var last = getLastSearch();
	   
	   if (isDatasets())
	   {
		   getPage('SavedSearches','promptname=true','POST','SavedSearchesMenu',null);
	   }
	   else
	   {
		   if (last != null)
		   {
			   var name = getQueryVariable(getLastSearch(),'terms');
			   //var name = prompt('Enter a name for your search',getQueryVariable(getLastSearch(),'terms'));
			   //if (name != null)
			   {
				   getPage('SavedSearches','queryString='+c_urlencode(getLastSearch())+'&name='+name+'&promptname=true','POST','SavedSearchesMenu',null);
			   }
		   }
		   else
		   {
			   alert("You have not performed a search yet");   
		   }
	   }
   }
   
   
   /*
    * Called when a user has named a saved search (see /jsp/SavedSearches.jsp).
    */    
   function confirmSavedSearch()
   {
	   var object = $('promptInput');
	   var name = object.value;
	   
	   if (isDatasets())
	   {
		   getPage('SavedSearches','name='+c_urlencode(name),'POST','SavedSearchesMenu',null);
	   }
	   else
	   {	  
		   var last = getLastSearch();
		   
		   if (last != null)
		   {		   		       
				   getPage('SavedSearches','queryString='+c_urlencode(getLastSearch())+'&name='+c_urlencode(name),'POST','SavedSearchesMenu',null);		
		   }
	   }
   }
   
   function selectResultType(type)
   {
	   if (type == 's')
	   {
	      $('leftdiv').show();
	      $('dataset_results').hide();
	      $('statistical_results').show();
	   }
	   else
	   {
	      $('leftdiv').hide();
	      $('dataset_results').show();
	      $('statistical_results').hide();
	   }

   }
   
   function isDatasets()
   {
	   var apl = $('AppletFrame');
	   if (apl)
		   return true;
	   else
		   return false;
		   
   }
   
   function appletResize()
   {   	  
	   
	  var relheight = document.body.clientHeight-90;
	  
	  if (relheight > 400)
	  {		
		  relheight = 400;
	  }
	  
	  var w = $('reldropdown');
	  if (w)
	  {
		  w.style.height = relheight;	  
		  closePulldownMenu();
	  }	  	  
	  
      var apl = $('AppletFrame');
      if (apl)
      {	
    	 var col = $('collapsibleX');
    	 var aplc = $('AppletContainer');
    	     	     	     	  
    	 var menuWidth;
    	 
    	 if (col)
    	 {
	    	 if (col.style.display == "block")
	    	   menuWidth = 277;    	  
	    	 else
	    	   menuWidth = 0;
    	 }
    	 else
    	 {
    		 menuWidth = 0;
    	 }
    	
    	 aplc.style.left = menuWidth;
    	 
    	 var img = $("DownImage")
    	 var height = img != null ? 25 : 0;    	 
    	 var bannerHeight = 42;
    	 var footerHeight = 36;     	     	     	     	 
    	     	 
      	 apl.style.height = document.body.clientHeight-height-bannerHeight-footerHeight;
         apl.style.width = document.body.clientWidth-menuWidth;
                           
         //alert(aplc.style.left);
         aplc.style.top = height;
         //alert(document.body.clientHeight+","+document.body.clientWidth);        
         
      }
   }       
   
   function switchToDatasets(params)
   {
	   getPageSynch(bannerBrand,"Product=DS","POST","framecontentTop");
	   var cont = $('maincontent');
	   cont.style.overflowX="hidden";
	   cont.style.overflowY="auto";
	   cont.style.background="transparent";
	   cont.style.backgroundAttachment="scroll";
	   getPageSynch("Datasets", params, "GET", "statisticaldiv",appletResize);     
   }
   
   function switchToStatistical(params)
   {
	   getPageSynch("banner","Product=ST","POST","framecontentTop");
	   var cont = $('maincontent');
	   cont.style.overflowX="auto";
	   cont.style.overflowY="scroll";
	   cont.style.backgroundImage = "url(images/gray.gif)";
	   cont.style.backgroundPosition = "top left";
	   cont.style.backgroundRepeat = "no-repeat";	  
	   cont.style.backgroundAttachment="fixed";
	   	   
	   getPageSynch("Statistical", params, "GET", "statisticaldiv",null);
   }
    
   function switchToDatasetsLink(metaID,I2)
   {	
	   $('maincontent').style.overflowX="hidden";
	   $('maincontent').style.overflowY="hidden"; 
	   getPageSynch("Datasets", "metaID="+metaID+"&I2="+I2, "GET", "statisticaldiv",appletResize);     
   }
   
   function switchToStatisticalLink(identifier)
   {	   
	   $('maincontent').style.overflowX="auto";
	   $('maincontent').style.overflowY="auto"; 	   
	   getPageSynch("StatisticalLink", "identifier="+identifier, "POST", "statisticaldiv",null);
   }
   
   
   function fixLeftPaneHeight()
   {	
	   /*
	  var pane = $('facet-menus');
	  if (pane)
	  {
		      var rf = YAHOO.util.Dom.getRegion('facet-menus');
			  var menuHeight = rf.bottom-rf.top;			  
			  var rm = YAHOO.util.Dom.getRegion('main');
			  
			  var mEndPos = rm.bottom;
			  
			  var xPos = rf.top;		  
			  var height = mEndPos-xPos;
			  if (rf.top+height < YAHOO.util.Dom.getDocumentHeight())
				height = YAHOO.util.Dom.getDocumentHeight() - rf.top - rm.top;
			  
			  if (rf.bottom > rm.bottom && rf.bottom > YAHOO.util.Dom.getDocumentHeight())
				  height = menuHeight;
			  
			  pane.style.height = height;			  			              
		  
	  }
	  */
	
   }
   
   function abisEntry(description,accNum, docnum,file,filename)
   {	   	  
	   try 
	   {		   
		   var numFiles = file.length;
		   var name = "";
		   if (filename)
		   {
			   name = "&fileName="+c_urlencode(filename);
		   }
		   
		   for (var i = 0; i < numFiles; i = i + 1)
		   {
			   getPageSynch("ABIS","description="+c_urlencode(description)+"&accnum="+c_urlencode(accNum)+"&docnum="+c_urlencode(docnum)+"&lib=STATGW&file="+c_urlencode(file[i])+name,"POST",null);
		   }
	   }
	   catch (e)
	   {
		   LogMessage("abisEntry failed");
		   LogMessage("abisEntry failed for file " + file + ":" + description + ", filename" + filename);		   
	   }   
   }
   
   function LogMessage(msg)
   {	   
	   getPageSynch("JavascriptLogger","msg="+c_urlencode(msg),"POST",null);
   }       
   
   function printContent(id){
	   str=document.getElementById(id).innerHTML
	   newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
	   newwin.document.write('<HTML>\n<HEAD>\n')
	   newwin.document.write('<TITLE>Print Page</TITLE>\n')
	   newwin.document.write('<script>\n')
	   newwin.document.write('function chkstate(){\n')
	   newwin.document.write('if(document.readyState=="complete"){\n')
	   newwin.document.write('window.close()\n')
	   newwin.document.write('}\n')
	   newwin.document.write('else{\n')
	   newwin.document.write('setTimeout("chkstate()",2000)\n')
	   newwin.document.write('}\n')
	   newwin.document.write('}\n')
	   newwin.document.write('function print_win(){\n')
	   newwin.document.write('window.print();\n')
	   newwin.document.write('chkstate();\n')
	   newwin.document.write('}\n')
	   newwin.document.write('<\/script>\n')
	   newwin.document.write('</HEAD>\n')
	   newwin.document.write('<BODY onload="print_win()">\n')
	   newwin.document.write(str)
	   newwin.document.write('</BODY>\n')
	   newwin.document.write('</HTML>\n')
	   newwin.document.close()
	   }

   function resetSearch()
   {	   
	   $('searchxx').value ='';loadSearchPage(true);
   }
   
     
