/* $Id$ */

function SolrRequest() {
	//set the query for this request
	this.solrQuery = document.getElementById("searchBox").query.value;
}

SolrRequest.SERVER = "http://www.alloypipefittings.net/select?wt=json&json.wrf=solrResponse&fl=id,title&q=";

SolrRequest.prototype.makeRequest = function(page) {
/*
 * Dynamically creates the script tag which then
 * sends the request to the Solr server.
 */
	this.jsonReq = new SolrScript(SolrRequest.SERVER + this.solrQuery + "&start=" + page);
	this.jsonReq.makeTag();
	this.jsonReq.addTag();
}

function requestHandler(page) {
/*
 * Called on search form submit and on results page request;
 * starting page argument is optional and defaults to 0.
 */
	var pageNum = page || 0;
	var solrReq = new SolrRequest();
	solrReq.makeRequest(pageNum);
	return false; //needed to keep the form from performing action
}

function solrResponse(obj) {
/*
 * Catches the response from the Solr server. Displays
 * results and adds page links to paginated results. This
 * function assumes 10 results per page.
 */
	var docTitles = "";
	var pageLinks = "";
	var j;
	// figure out how many results are in the current page
	if (obj.response.numFound - obj.response.start < 10) {
		j = obj.response.numFound - obj.response.start;
	} else {
		j = 10;
	}
	// create result list
	for (var i=0; i<j; i++) {
		docTitles += "<a href='http://help.unc.edu/" +
			obj.response.docs[i].id + "'>" + obj.response.docs[i].title + "</a><br />";
	}
	// create page links
	var pages = Math.ceil(obj.response.numFound/10);
	for (var i=0; i<pages; i++) {
		pageLinks += "<a href='#' onclick='requestHandler(" + eval(i*10) + ")'>" + eval(i+1) + "</a> ";
	}
	// write to document
	document.getElementById('result').innerHTML = docTitles;
	document.getElementById('pages').innerHTML = pageLinks;
}

function SolrScript(url) {
/*
 * This class manages the dynamic script tag. Script
 * tag is added with id="solrScript".
 */
    this.url = url;
    this.headTag = document.getElementsByTagName("head").item(0);
	// clean up previous dynamic script tag
	if (document.getElementById("solrScript")) {
		this.headTag.removeChild(document.getElementById("solrScript"));
	}
}

SolrScript.prototype.makeTag = function () {
    this.scriptTag = document.createElement("script");
    this.scriptTag.setAttribute("type", "text/javascript");
    this.scriptTag.setAttribute("src", this.url + '&time=' + (new Date()).getTime());
    this.scriptTag.setAttribute("id", "solrScript");
}

SolrScript.prototype.addTag = function () {
    this.headTag.appendChild(this.scriptTag);
}