// On page load, set up a link click listener:
Event.observe(window, 'load', onPageLoad);
function onPageLoad() {

  //Loop through each 'a' tag in the page and register a listener 'onclick':
  $$('a').each(function(a){
      Event.observe(a, 'click', elrc_save_term_path);
  });
  $$('form').each(function(a){
      Event.observe(a, 'submit', elrc_save_term_resource);
  });
  
  saveNumResultsReturned();
  
}
function saveNumResultsReturned(){
	
	var term_ID = readCookie('ELRCSEARCHID');
	var numResults = readCookie('ELRCNUMRETURNED');

	if(term_ID != null && numResults == null && document.getElementById("elrc_total_results")){
		var numReturned = document.getElementById("elrc_total_results").innerHTML;

		// Create the new script element and assign the a src attribute
		var newScriptNumReturned = new Element('script', { 'src': 'http://apps.exploratorium.edu/nsdl/research/saveNumReturned.php?term_ID='+term_ID+'&numReturned='+numReturned});
				
		// Put the new script into the page
		document.getElementsByTagName('head').item(0).appendChild(newScriptNumReturned);
	}
	
}
function numReturnedCallback(response){
	var numReturnedResp = response.numReturned;
	
	if(numReturnedResp){
		document.cookie ="ELRCNUMRETURNED="+numReturnedResp+";path=/;domain=.exploratorium.edu";
					  	
	}
}
function elrc_save_term_path(event){
	var term_ID = readCookie('ELRCSEARCHID');
	if(term_ID != null){
		
		if(event.element().href.startsWith('http://nsdl.exploratorium.edu/nsdl/showRecord.do?') || event.element().href.startsWith('/nsdl/showRecord.do?')){
			
			var url = event.element().href;
			event.element().href = "#";
			// Create the new script element and assign the a src attribute
			var newScriptMoreInfo = new Element('script', { 'src': 'http://apps.exploratorium.edu/nsdl/research/saveSearchURL.php?term_ID='+term_ID+'&url='+url});
				
			// Put the new script into the page
			document.getElementsByTagName('head').item(0).appendChild(newScriptMoreInfo);
			setTimeout('window.location.href = "'+url+'"',100);
		} 
	}
}

function elrc_save_term_resource(event){
	var term_ID = readCookie('ELRCSEARCHID');
	if(term_ID != null){
		if(event.element().action.startsWith('http://nsdl.exploratorium.edu/nsdl/getAsset.do') || event.element().action.startsWith('/nsdl/getAsset.do')){
			var url = event.element().serialize();
			
			// Create the new script element and assign the a src attribute
			var newScriptGetRes = new Element('script', { 'src': 'http://apps.exploratorium.edu/nsdl/research/saveSearchURL.php?term_ID='+term_ID+'&url='+url});
				
			// Put the new script into the page
			document.getElementsByTagName('head').item(0).appendChild(newScriptGetRes);
		}
	}
		
}