/*
  SITESEARCH by Christian Heilmann
  Version: 1.0
  Featured in 24ways.org 2008 and Webkrauts advent calendar 2008
  Copyright (c) 2008, Christian Heilmann
  Code licensed under the BSD License:
  http://wait-till-i.com/license.txt
  
  Additional code to support pagination and
  some modifications by Tiffany B. Brown 
  http://www.tiffanybbrown.com/
  See an example at  http://www.tiffanybbrown.com/search
  
*/
SITESEARCH = function(){
  var config = {
	IDs:{
	  searchForm:'customsearch',
	  term:'term',
	  site:'site',
	  resultscontainer:'search_results'
	},
	loading:'Loading results...',
	loadingErr:'Please enter search criteria.',
	noresults:'No results found.',
	appID:'YOUR-APP-ID',
	results:20
  };
  var form;
  var out;
  var results;
  var srchcontainer = document.getElementById(config.IDs.resultscontainer);
  var srchvars = getSrchVars();
 
  function getSrchVars(){
		// parses out the query string and stores it as a set of object-pair values
		var urlquery = {};
		
		if (!window.location.search) {
			urlquery.p = document.getElementById(config.IDs.term).value;
		}
		else {
			var q = decodeURI(window.location.search.replace('?', ''));
			var qvars = q.split('&');
			for (var i = 0; i < qvars.length; i++) {
				var pair = qvars[i].split('=');
				urlquery[pair[0]] = pair[1].replace('+', ' ');
			}
		}
		if (!urlquery.start) {
			urlquery.start = 0;
		}
		return urlquery;
	}
	function init(){
		
		if(config.appID === 'YOUR-APP-ID'){
			alert('Please get a real application ID!');
		} else {
			if(window.location.search){
				
				window.onload = function(){
					document.getElementById(config.IDs.term).value = srchvars.p;
					doSearchOnload();
					return false;
				};
			}
			
			form = document.getElementById(config.IDs.searchForm);
			if(form){
				form.onsubmit = function(){
					doSearch();
					return false;
				};
			} 
		}
	};
	function doSearchOnload(){
		var site = document.getElementById(config.IDs.site).value;
		var term = document.getElementById(config.IDs.term).value;
	
		if(typeof site === 'string' && typeof term === 'string'){
			if(typeof out !== 'undefined'){
			  out.parentNode.removeChild(out);
			}
			out = document.createElement('p');
			out.appendChild(document.createTextNode(config.loading));
			srchcontainer.appendChild(out);
			
			var APIurl = 'http://boss.yahooapis.com/ysearch/web/v1/' + 
						  srchvars.p + '?callback=SITESEARCH.found&sites=' + 
						  site + '&count=' + config.results + '&start=' + srchvars.start +
						  '&appid=' + config.appID;
			var s = document.createElement('script');
			s.setAttribute('src',APIurl);
			s.setAttribute('type','text/javascript');
			document.getElementsByTagName('head')[0].appendChild(s);	
		}
		
	};
	function doSearch(){
		var site = document.getElementById(config.IDs.site).value;
		var term = document.getElementById(config.IDs.term).value;
		
		if(typeof site === 'string' && typeof term === 'string'){
			if(typeof out !== 'undefined'){
			  out.parentNode.removeChild(out);
			}
			out = document.createElement('p');
			out.appendChild(document.createTextNode(config.loading));
			srchcontainer.appendChild(out);
			var APIurl = 'http://boss.yahooapis.com/ysearch/web/v1/' + 
						  term + '?callback=SITESEARCH.found&sites=' + 
						  site + '&count=' + config.results + 
						  '&appid=' + config.appID;
			var s = document.createElement('script');
			s.setAttribute('src',APIurl);
			s.setAttribute('type','text/javascript');
			document.getElementsByTagName('head')[0].appendChild(s);
				
		}
		return false;
	}
	function howManyPages(numresults, results){return Math.ceil(numresults / results); }
	function buildPagination(pages,injectIntoDiv){
		var i = 0;
		for(i=0; i < pages; i++){
			nlink = document.createElement('a');
			
			nlink.setAttribute('href',form.action+'?p='+getSrchVars().p+'&start='+((i)*config.results));
			nlink.innerHTML = i+1;
			injectIntoDiv.appendChild(nlink);
		}
	}
	function found(o){
		var results = o.ysearchresponse.resultset_web;
		if(results){
			
			// create x of x results found container/placeholder
			var cnt = document.createElement('p');
			cnt.className = 'ss_results_count';
			
			// determine the upper limit of results per page.
			var limit = (parseInt(srchvars.start)+config.results);
							
			// if the upper limit is greater than the hits returned ...
			if(limit >  o.ysearchresponse.totalhits){ limit =  o.ysearchresponse.totalhits; }
		
			countText = 'Viewing '+(parseInt(srchvars.start)+1)+' - '+limit+' of '+ o.ysearchresponse.totalhits;
			
			cnt.appendChild(document.createTextNode(countText));
			srchcontainer.appendChild(cnt);
			
			// Create pagination placeholder
			var pagination = document.createElement('div');
			pagination.className = 'ss_pagination';
			srchcontainer.appendChild(pagination);
			
			var list = document.createElement('dl');
			list.id = "ss_results";
					
			var item,link,description;
			for(var i=0,j=results.length;i<j;i++){
				item = document.createElement('dt');
				link = document.createElement('a');
				link.setAttribute('href',results[i].clickurl);
				link.innerHTML = results[i].title;
				item.appendChild(link);
				
				description = document.createElement('dd');
				description.innerHTML = results[i]['abstract'];
				list.appendChild(item);
				list.appendChild(description);
			}
			
			var numpages = howManyPages(o.ysearchresponse.totalhits,config.results);
			buildPagination(numpages,pagination);
			
			// create bottom pagination links by duplicating the ones above
			var bottompag = pagination.cloneNode(true);
			var bottomcnt = cnt.cloneNode(true);
			

		} else {
			list = document.createElement('p');
			list.appendChild(document.createTextNode(config.noresults));
		}
		srchcontainer.removeChild(out); // remove "Loading results" container
		srchcontainer.appendChild(list); // add the list of results
		
		if(results){
			// insert bottom placeholder links and the bottom count
			srchcontainer.appendChild(bottompag);
			srchcontainer.appendChild(bottomcnt);
		}
		// out = list;
	};
	
	return{
		config:config,
		init:init,
		found:found
	};
	
	
}();


SITESEARCH.config.appID = 'Q0djZ.vIkY5z.hGDdgmbzlcI_VpTCqvtWc3zdAAt'; // change this!
SITESEARCH.init();

