/**
 * @author Rik
 */
var searchRequest=null;

//stop conflicts with other libs that use netaphorSearch.query, use netaphorSearch.query instead
var netaphorSearch = {};
netaphorSearch.query = jQuery.noConflict(true);

var NetaphorConfig = {
		autoComplete:false,
		autoCompleteUrl:"core/lib/autocomplete/autoComplete.php?q=",
		resultOpener:"<li class='result'>",
		titleOpener:"<div class='title'>",
		titleCloser:"</div>",
		abstractOpener:"<div class='description'>",
		abstractCloser:"</div>",
		resultCloser:"</li>",
		closeDiv:"</div>",
		resultCountOpener:'<div id="resultCount">',
		resultCountCloser:'</div>',
		baseResultsUrl:"",
		baseResultsUrlAppender:"",
		baseResultsUrlAppender:"",
		baseServerURI:"",
		searchServer:function(){
			var serverURI = this.baseServerURI;
			return serverURI;
		},
		searchPage:null,
		start:0,
		resultCount:0,
		resultsPerPage:10,
		renderBackClass:"paginationLink",
		renderForwardClass:"paginationLink",
		paginationControls:"<div class='pagination'>",
		jsonSearchPage:"/searchAsJSON.php",
		appendSearchTo:"",
		abstractTrimLength:400,
		resultsImagePath:"",
		currentSuggestion:null,
		autoCompleteTrimLength:38

};
 
var NetaphorData = {
	suggestions: null, 
	suggestionsFullTexts:null,
	allowSuggestionHiding:true,
	q: "",
	fq: [],
	start: 0,
	ajr:null // a pointer to the suggestion auto complete ajax request
};

var NetaphorTools = {
	autoComplete:function (theKey){
		var q = netaphorSearch.query('#searchBox').val();
		
		//we dont always want to do a search so iterate over the exlcude list and return false if we dont want to perform the search
		function isValidKeyEntry (){
			var excludeList = ["40","38","13","37","39"];
			var isValid = true;
			for (var i = 0; i< excludeList.length; i++){
				if (theKey == excludeList[i]){
					isValid = false;
					break;
				}
			}
			return isValid;
		}
		
		if(theKey == "38" || theKey == "40"){
			// if there is a suggestion already highlighted then un-hihglight it
			if(netaphorSearch.query("#suggestion"+NetaphorConfig.currentSuggestion)){
				netaphorSearch.query("#suggestion"+NetaphorConfig.currentSuggestion).css("background-color","white");
			} 
			// if there is not a current selection or we are at the end of the list reset to 0
			if(NetaphorConfig.currentSuggestion == null || (NetaphorConfig.currentSuggestion == 4 && theKey == "40")){
				NetaphorConfig.currentSuggestion = 0;
				netaphorSearch.query("#suggestion"+NetaphorConfig.currentSuggestion).css("background-color","#f0f0f0");
			} 
			// if we at the start of the list and going backwards the set to the end of thelist 
			else if (NetaphorConfig.currentSuggestion == 0 && theKey == "38"){
				NetaphorConfig.currentSuggestion = 4;
				netaphorSearch.query("#suggestion"+NetaphorConfig.currentSuggestion).css("background-color","#f0f0f0");
			} 
			// if we are in the middle of the list the increment if moving fowards and decrement if moving backwards
			else{
				theKey == "40" ? NetaphorConfig.currentSuggestion++ : NetaphorConfig.currentSuggestion--;
				netaphorSearch.query("#suggestion"+NetaphorConfig.currentSuggestion).css("background-color","#f0f0f0");
			}			

		}
		
		
		if(q.length >= 3 && isValidKeyEntry()){
			// cancel the previous request so that we don't end up with loads of 'em
			if(NetaphorData.ajr && NetaphorData.ajr !== null) {NetaphorData.ajr.abort();}
			var areThereResults = true;
			
			NetaphorData.ajr = netaphorSearch.query.getScript(NetaphorConfig.searchServer() + NetaphorConfig.autoCompleteUrl + q + "&site=" + NetaphorConfig.clientId, function(){
				if(NetaphorData.suggestions.response && NetaphorData.suggestions.response.numFound > 0){
					netaphorSearch.query('#suggestions').css("display", "block");
					var suggestionList = '';
					var suggestionCount = 0;
					NetaphorData.suggestionsFullTexts = [];
					for(var property in NetaphorData.suggestions.response.docs){
						
						if (NetaphorData.suggestions.response.docs[property].title){
							//console.log(NetaphorData.suggestions.response.docs[property].title);
							var titleString = NetaphorData.suggestions.response.docs[property].title;
							
							//the full text string, used if a user selects the item to search
							NetaphorData.suggestionsFullTexts[suggestionCount] = titleString;
							
							// see if we have a result with some highlighting
							var titleHighlight = SearchRenderer.getHighlighting("title", NetaphorData.suggestions.response.docs[suggestionCount].id, NetaphorData.suggestions);
							
							//if we do have highlighting the use that
							if(titleHighlight !== false){
								titleString = titleHighlight;
							} 
							
							// if the lenght of the title text is too long for the tect box then we should trim it down a bit
							//if(titleString.length > NetaphorConfig.autoCompleteTrimLength){
							//	titleString = titleString.substring(0,NetaphorConfig.autoCompleteTrimLength) + "...";
							//}
							
							//build up the html displayed to the user
							suggestionList += "<div class='suggestionContainer' id='suggestion" + suggestionCount + "' onmouseover='NetaphorTools.highlightAutoCompleteResult(this,true)'  onmouseout='NetaphorTools.highlightAutoCompleteResult(this,false)'><span class='suggestionLink' onclick='NetaphorTools.searchWithSuggestion(" + suggestionCount + ")' class='suggestItem'>" + titleString + "</span></div>";
							suggestionCount++;
						}
						
					}
					netaphorSearch.query('#suggestions').html(suggestionList);
				}
			});
			
		} else if (q.length < 3){
			netaphorSearch.query('#suggestions').html("");
			netaphorSearch.query('#suggestions').css("display", "none");
		}
	},
	highlightAutoCompleteResult: function(obj,highlight){
		// un-highlight the current one if necessary:
		NetaphorConfig.currentSuggestion !== null ? netaphorSearch.query("#suggestion"+NetaphorConfig.currentSuggestion).css("background-color","white") : "";
		highlight ? netaphorSearch.query("#"+obj.id).css("background-color","#f0f0f0") : netaphorSearch.query("#"+obj.id).css("background-color","#fff");
		NetaphorConfig.currentSuggestion = null;
	},
	searchWithFacet: function(value){
		NetaphorData.fq.push(value);
		NetaphorData.start = 0;
		//netaphorSearch.query('#netaphorSearchForm').submit();
		this.newSearch();
	},
	searchWithSuggestion: function (selectedSuggestion){
		var query = NetaphorData.suggestionsFullTexts[selectedSuggestion];
		NetaphorData.start = 0;
		NetaphorData.q = query;
		this.newSearch();
	},
	removeFilter: function(value){
		for(var i = 0; i < NetaphorData.fq.length; i++){
			if (value == NetaphorData.fq[i]){
				NetaphorData.fq.splice(i,1);
			}
		}
		//netaphorSearch.query('#netaphorSearchForm').submit();
		NetaphorData.start = 0;
		this.newSearch();
	},
	doSearch: function (url){
		netaphorSearch.query.getScript(url, function(){
			SearchRenderer.setupPage();
			SearchRenderer.renderResults();
		});
	},
	navigatePage: function (start){
		NetaphorData.start = start;
		this.newSearch();
	},
	newSearch: function (){
		window.location.href = NetaphorConfig.searchPage + NetaphorQueryTools.getSearchQuery();
	},
	formatPrice: function (value){
		tValue = value.toString();
		sLength = tValue.length;
		var valueAsPounds = "";
		var price = "";
		var beforeDecimal = tValue.substring(0, sLength-2);
		var afterDecimal = tValue.substring(sLength-2, sLength);
		if(beforeDecimal.length > 3){
			sbLength = beforeDecimal.length;
			var beforeComma = beforeDecimal.substring(0, sbLength-3);
			var afterComma = beforeDecimal.substring(sbLength-3, sLength);
			price = beforeComma + "," + afterComma;
		} else {
			price = beforeDecimal;
		} 
		valueAsPounds = "&pound;" + price + "." + afterDecimal + "<span class='plusVat'>+VAT</span>";
		return valueAsPounds;
	}
};

var SearchRenderer = {
	setupPage: function (){
		if(NetaphorConfig.appendSearchTo == ""){
			netaphorSearch.query("body").append('<div id="netaphorSearch"></div>');
		} else {
			netaphorSearch.query("#" + NetaphorConfig.appendSearchTo).html('<div id="netaphorSearch"></div>');
		}
		this.rendernetaphorSearchForm();
		// bind the autocomplete method to the search box. Note there may be two of them (search boxes that is)...
		this.bindAutoComplete();
		this.setupNetaphorSearchForm();
	},
	setupNetaphorSearchForm: function (){
		netaphorSearch.query("#netaphorSearchForm").submit(function(){
			if(NetaphorConfig.currentSuggestion != null){
				var suggestionValue = NetaphorData.suggestionsFullTexts[NetaphorConfig.currentSuggestion];
				netaphorSearch.query("#searchBox").val(suggestionValue);
			}
		});
	},
	bindAutoComplete: function (){
		var searchBox = netaphorSearch.query('#searchBox');
		if(NetaphorConfig.autoComplete){
			searchBox.keyup(function(e){
				NetaphorTools.autoComplete(e.keyCode);
			});
			searchBox.blur(function(){
				// hide the suggestions if they are 
				SearchRenderer.hideSuggestions();
			});
			
			// We do not want the hideSuggestions method to complete if the blur event has been triggered over the suggestions box
			netaphorSearch.query('#suggestions').hover(function(){NetaphorData.allowSuggestionHiding = false;},function(){NetaphorData.allowSuggestionHiding = true;});

		}
	},
	hideSuggestions:function(){
		NetaphorData.allowSuggestionHiding ? netaphorSearch.query('#suggestions').css("display", "none") : "";
	},
	renderResults: function (){
		if(window.location.href.indexOf("principal") == -1){
			this.renderFacets();
		}
		this.renderControls();
		this.renderList();
		this.renderPagination(searchRequest.response.start);
	},
	renderControls: function (){
		var pageCountControls = "";
		pageCountControls += NetaphorConfig.resultCountOpener;
		if(searchRequest.response.start / NetaphorConfig.resultsPerPage > 0){
			pageCountControls += "Page " + "<strong>" + (searchRequest.response.start / NetaphorConfig.resultsPerPage + 1) + "</strong> of ";
		}
		pageCountControls += '<span id="theCount">' + searchRequest.response.numFound + '</span> result(s)';
		netaphorSearch.query("#netaphorSearch").append(pageCountControls);
	},
	rendernetaphorSearchForm: function (){
		var q="";
		if(searchRequest !== null){
			q = searchRequest.responseHeader.params.q;
		}
		var netaphorSearchForm = '<div id="searchBoxArea"><form method="GET" action="'+ NetaphorConfig.searchPage + '" id="netaphorSearchForm" autocomplete="off">';
		netaphorSearchForm += '<input type="hidden" name="start" value="0" id="start" />';
		netaphorSearchForm += '<input type="hidden" name="fq" value="" id="fq" />';
		netaphorSearchForm += "<input type='text' name='q' value='" + q + "' id='searchBox'/>";
		netaphorSearchForm += "<button type='submit' id='netaphorSearchButton'>Go</button>";
		netaphorSearchForm += "<br/><div><div id='suggestions'></div></div>";

		netaphorSearchForm += '</form></div>';
		netaphorSearch.query("#netaphorSearch").append(netaphorSearchForm);
	},
	getHighlighting:function(type, id, requestObj){
		var highlightingText = false;
		if(requestObj.highlighting[id][type]){
			highlightingText = requestObj.highlighting[id][type][0];
		}
		return highlightingText;
	},
	renderList: function(){
		netaphorSearch.query("#netaphorSearch").append('<ul id="results"></ul>');
		for(var i=0; i < searchRequest.response.docs.length;i++){
			var resultOutput = "";
			var titleHighlight = this.getHighlighting("title", searchRequest.response.docs[i].id, searchRequest);
			var descHighlight = this.getHighlighting("longdesc", searchRequest.response.docs[i].id, searchRequest);
			var descText = "";
			var resultUrl = "";
			
			if(searchRequest.response.docs[i].urlsegment.indexOf("http://") > -1){
				// if we have a fully qulaified URL the use it
				resultUrl = searchRequest.response.docs[i].urlsegment;
			} else if (searchRequest.response.docs[i].manufacturer == "Principal"){
			    resultUrl = searchRequest.response.docs[i].urlsegment;    
			} else {
				// otherwise construct the URL
				resultUrl = NetaphorConfig.baseResultsUrl + searchRequest.response.docs[i].urlsegment + NetaphorConfig.baseResultsUrlAppender;
			}
			
			resultOutput += NetaphorConfig.resultOpener;
			resultOutput += NetaphorConfig.titleOpener;
			
			resultOutput += "<a href='" + resultUrl + "'>";
			
			if(titleHighlight != false){
				resultOutput += titleHighlight;
			} else {
				resultOutput += searchRequest.response.docs[i].title;
			}
			
			resultOutput += "</a>";
			resultOutput += NetaphorConfig.titleCloser;
			resultOutput += NetaphorConfig.abstractOpener;
			
			// if there is an image then use it
			if(searchRequest.response.docs[i].imagename){
				resultOutput += "<a href='" + resultUrl + "'>";
				resultOutput += '<div class="imageWrapper"><img src="'+NetaphorConfig.resultsImagePath+searchRequest.response.docs[i].imagename+'" class="descriptionImage"/></div>';
				resultOutput += "</a>";
			}
			//if(descHighlight != false){
			//	
			//} else {
			if (descHighlight != false){
				descText = descHighlight  + "...";
			} else if (searchRequest.response.docs[i].metadescription){
				descText = searchRequest.response.docs[i].metadescription;
			} else if (searchRequest.response.docs[i].longdesc){
				descText = searchRequest.response.docs[i].longdesc;
			}

			
			if(descText.length > NetaphorConfig.abstractTrimLength){
				var absStart = descText.substring(0,NetaphorConfig.abstractTrimLength);
				var absEnd = descText.substring(NetaphorConfig.abstractTrimLength,descText.length);
				resultOutput += absStart + "<span class='showMore' onclick='netaphorSearch.query(\"#abs" + i + "\").css({\"display\":\"inline\"}),this.style.display=\"none\"'>...show more</span>";
				resultOutput += "<span class='extraAbstract' id='abs" + i + "'>" + absEnd + "</span>";
			} else {
				resultOutput += descText;
			}
			
			if(searchRequest.response.docs[i].manufacturer != "Principal"){
				resultOutput += '<div class="metaData">';
				resultOutput += '<span>Manufacturer: </span>' + searchRequest.response.docs[i].manufacturer + '&nbsp;&nbsp;&nbsp;&nbsp;<span>Part no: </span>' + searchRequest.response.docs[i].manupart;
				if(NetaphorConfig.clientId == "officeMagic"){
					resultOutput += '&nbsp;&nbsp;&nbsp;&nbsp;<span>Price: </span>';
					var price = searchRequest.response.docs[i].priceexcvat;
					if(price == 0){
					   resultOutput += "POA"; 
					} else {
					   resultOutput += NetaphorTools.formatPrice(price);   
					}
					 
				}
				resultOutput += "</div>";
			}
			
			resultOutput += NetaphorConfig.abstractCloser;
			resultOutput += NetaphorConfig.resultCloser;
			netaphorSearch.query("#results").append(resultOutput);
		}
	},
	renderPagination: function (start){
		var paginationString = "<div id='pagination'>";
		
		function paginationValues (position,direction){
			if(direction == "f"){ // we are going deeper into the results set
				position += NetaphorConfig.resultsPerPage;
			} else if (position > 0){// we are going backwards but check we are not on page 1 already (start = 0)
				position -= NetaphorConfig.resultsPerPage;
			} else {
				position = 0;
			}
			
			return position;
		}
		
		function renderSearchLink (linkText, start, classId){
			var pagination = "<span onclick='NetaphorTools.navigatePage(" + start + ")' class='" + classId + "'>" + linkText + "</span>";
			return pagination;
		}

		if(start > 0){
			paginationString += renderSearchLink("&lt;&lt; Previous " + NetaphorConfig.resultsPerPage + " results", paginationValues(start,"b"), NetaphorConfig.renderBackClass);
			paginationString += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		} 
		
		if(searchRequest.response.numFound - searchRequest.response.start > NetaphorConfig.resultsPerPage){
			paginationString += renderSearchLink("Next " + NetaphorConfig.resultsPerPage +  " results &gt;&gt;", paginationValues(start,"f"), NetaphorConfig.renderForwardClass);
			paginationString += "</div>";
		}
		
		netaphorSearch.query("#netaphorSearch").append(paginationString);

	},
	createListControl: function (controlListAsArray, controlName, title){
		var control = "<div style='float:left;padding-top:15px;'><span>" + title + "</span><br/>";
		control += "<select name='" + controlName + "' multiple='mulitple' size='5'>";
		for (var i=0; i<controlListAsArray.length; i=i+2 ){
			control += "<option onclick='NetaphorTools.searchWithFacet(\"" + controlName + ":" + controlListAsArray[i] + "\")' value='" + controlName + ":" + controlListAsArray[i] + "'>" + this.reconstructFacetValue(controlListAsArray[i]) + " (" + controlListAsArray[i+1] + ")</option>";
		}
		control += "</select></div>";
		netaphorSearch.query("#browser").append(control);
	},
	createHorizontalListControl: function (controlListAsArray, controlName, title){
		var control = "<div class='filterBlock'><span class='filterTitle'>" + title + ": </span>";
		for (var i=0; i<controlListAsArray.length; i=i+2 ){
			// if there are facets in the response then check to see if the current value is one of those already request
			if (searchRequest.responseHeader.params.fq && this.isFacetSelected(controlName + ":" + controlListAsArray[i], searchRequest.responseHeader.params.fq)){
				control += "<span class='selectedFacetLink' onclick='NetaphorTools.removeFilter(\"" + controlName + ":" + controlListAsArray[i] + "\")'>" + this.reconstructFacetValue(controlListAsArray[i]) + "<span class='removeFacet'> <img src='http://www.officemagic.co.uk/i/button-remove.gif'></span></span>";
			} else {
				control += "<span class='facetLink' onclick='NetaphorTools.searchWithFacet(\"" + controlName + ":" + controlListAsArray[i] + "\")'>" + this.reconstructFacetValue(controlListAsArray[i]) + "<span class='facetCount'> (" + controlListAsArray[i+1] + ")</span></span>";	
			}
		}
		control += "</div>";
		netaphorSearch.query("#browser").append(control);
	},
    createProductTypeListControl: function (controlListAsArray, controlName, title){
        var control = "<div class='filterBlock'><span class='filterTitle'>" + title + ": </span>";
        var controlData = [];
        for (var i=0; i<controlListAsArray.length; i=i+2 ){
            // if there are facets in the response then check to see if the current value is one of those already request
            if (searchRequest.responseHeader.params.fq && this.isFacetSelected(controlName + ":" + controlListAsArray[i], searchRequest.responseHeader.params.fq)){
                controlData[controlListAsArray[i]] = "<span class='selectedFacetLink' onclick='NetaphorTools.removeFilter(\"" + controlName + ":" + controlListAsArray[i] + "\")'>" + this.reconstructFacetValue(controlListAsArray[i]) + "<span class='removeFacet'> <img src='http://www.officemagic.co.uk/i/button-remove.gif'></span></span>";
            } else {
                controlData[controlListAsArray[i]] = "<span class='facetLink' onclick='NetaphorTools.searchWithFacet(\"" + controlName + ":" + controlListAsArray[i] + "\")'>" + this.reconstructFacetValue(controlListAsArray[i]) + "<span class='facetCount'> (" + controlListAsArray[i+1] + ")</span></span>"; 
            }
        }
        controlData["Product"] ? control += controlData["Product"] : "";
        controlData["Accessory"] ? control += controlData["Accessory"] : "";
        controlData["Consumable"] ? control += controlData["Consumable"] : "";
        
        control += "</div>";
        netaphorSearch.query("#browser").append(control);
    },	
	createPriceControl: function(){
		var priceRanges = [["&lt; &pound;100","priceexcvat:[0 TO 10000]"],["&pound;100 - &pound;250","priceexcvat:[10000 TO 25000]"],["&pound;250 - &pound;500","priceexcvat:[25000 TO 50000]"],["&pound;500 - &pound;1000","priceexcvat:[50000 TO 100000]"],["&pound;1000 - &pound;2500","priceexcvat:[100000 TO 250000]"],["&pound;2500 - &pound;5000 ","priceexcvat:[250000 TO 500000]"],["&pound;5000 - &pound;10000 ","priceexcvat:[500000 TO 1000000]"],["&gt; &pound;10000","priceexcvat:[1000000 TO *]"]];
		var control = "<div class='filterBlock'><span class='filterTitle'>Price: </span>";
		for (var i=0; i<priceRanges.length; i++ ){
			// if there are facets in the response then check to see if the current value is one of those already request
			if (searchRequest.responseHeader.params.fq && this.isFacetSelected(priceRanges[i][1], searchRequest.responseHeader.params.fq)){
				control += "<span class='selectedFacetLink' onclick='NetaphorTools.removeFilter(\"" + priceRanges[i][1] + "\")'>" + priceRanges[i][0] + "<span class='removeFacet'> <img src='http://www.officemagic.co.uk/i/button-remove.gif'></span></span>";
			} else if (searchRequest.facet_counts.facet_queries[priceRanges[i][1]] && searchRequest.facet_counts.facet_queries[priceRanges[i][1]] > 0){
				control += "<span class='facetLink' onclick='NetaphorTools.searchWithFacet(\"" + priceRanges[i][1] + "\")'>" + priceRanges[i][0] + "<span class='facetCount'> (" + searchRequest.facet_counts.facet_queries[priceRanges[i][1]] + ")</span></span>";	
			}
		}
		netaphorSearch.query("#browser").append(control);
	},
	booleanControl: function(controlListAsArray, controlName, title){
		var control = "<div class='filterBlock'><span class='filterTitle'>" + title + ": </span>";
		for (var i=0; i<controlListAsArray.length; i=i+2 ){
			// if there are facets in the response then check to see if the current value is one of those already request
			if (searchRequest.responseHeader.params.fq && this.isFacetSelected(controlName + ":" + controlListAsArray[i], searchRequest.responseHeader.params.fq)){
				control += "<span class='selectedFacetLink' onclick='NetaphorTools.removeFilter(\"" + controlName + ":" + controlListAsArray[i] + "\")'>" + this.reconstructBooleanFacetValue(controlListAsArray[i], "Accessories", "Products") + "<span class='removeFacet'> <img src='http://www.officemagic.co.uk/i/button-remove.gif'></span></span>";
			} else {
				control += "<span class='facetLink' onclick='NetaphorTools.searchWithFacet(\"" + controlName + ":" + controlListAsArray[i] + "\")'>" + this.reconstructBooleanFacetValue(controlListAsArray[i], "Accessories", "Products") + "<span class='facetCount'> (" + controlListAsArray[i+1] + ")</span></span>";	
			}
		}
		control += "</div>";
		netaphorSearch.query("#browser").append(control);
	},
	isFacetSelected: function (value, listToCheck){
		var facetIsSelected = false;
		
		// this is an arse, SOLR returns FQ values as a string if only one is passed and an array if more that one is passed.
		if (typeof listToCheck == "string"){
			value == listToCheck ? facetIsSelected = true : "";
		} else {
			for (var i = 0; i < listToCheck.length; i++){
				
				if(value == listToCheck[i]){
					facetIsSelected = true;
					break;
				}
			}
		}
		return facetIsSelected;
	},
	reconstructFacetValue: function (value){
		var valueAsArray = value.split("_");
		var newValue = "";
		for(var i=0; i<valueAsArray.length; i++){
			newValue += valueAsArray[i] + " ";
		}
		return newValue;
	},
	reconstructBooleanFacetValue: function (value, trueText, falseText){
		var booleanText = "";
		value == "true" ? booleanText = trueText : booleanText = falseText;
		return booleanText;
	},
	renderFacets: function (){
		netaphorSearch.query("#netaphorSearch").append('<div id="browser"></div>');
	    this.createHorizontalListControl(searchRequest.facet_counts.facet_fields.manufacturerFacet,"manufacturerFacet","Manufacturer");
        //this.createHorizontalListControl(searchRequest.facet_counts.facet_fields.category,"category","Category");		
		this.createPriceControl();
		this.createProductTypeListControl(searchRequest.facet_counts.facet_fields.primaryCategory,"primaryCategory","Type");
		//this.booleanControl(searchRequest.facet_counts.facet_fields.isaccessory,"isaccessory","Type");
	}
};

var NetaphorQueryTools = {
	parseQueryString:function(){
		// if there is a search query then extract the paramters and do a search
		// first check for any params and then if there is the required q param
		if (window.location.href.indexOf("?") > 0 && window.location.href.indexOf("q=") > 0) {
			var urlArray = window.location.href.split("?");
			NetaphorConfig.searchPage = urlArray[0]; // set the search page in config, it is whatever comes before the ?
			
			// split the remaing query into its different components
			var theParams = urlArray[1].split("&");

			// extract the bits we want and store them for later use
			var searchQuery = this.getQueryValue(theParams, "q=");
			var filterParams = this.getQueryValue(theParams, "fq=");
			var startValue = this.getQueryValue(theParams, "start=");
			
			// update application config 
			searchQuery != false ? NetaphorData.q = searchQuery : ""; 
			// for fq fields there may be multiple values seperated by "|"s, we want to store them as an array
			filterParams != false ? NetaphorData.fq = filterParams.split("|") : "";
			startValue != false ? NetaphorData.start = startValue : "";
			
			var allParams = urlArray[1]; 
			
			// check we have a search query, if we do then execute a search appending the client ID as we go
			if (searchQuery.length > 0) {
				NetaphorTools.doSearch(NetaphorConfig.searchServer() + NetaphorConfig.clientId + NetaphorConfig.jsonSearchPage + this.getSearchQuery() + "&clientId=" + NetaphorConfig.clientId);
			} else {
				// if not just setup the search page UI
				SearchRenderer.setupPage();
			}
		} else{
			NetaphorConfig.searchPage = window.location.href;
			SearchRenderer.setupPage();
		}
	},
	getQueryValue: function (queryArray, paramIdentifier){
		// parse the params looking for and extracting the specific value requested
		var queryValue = false;
		for (var i=0; i < queryArray.length; i++){
			if(queryArray[i].indexOf(paramIdentifier) == 0){
				queryValue = queryArray[i].substring(paramIdentifier.length, queryArray[i].length);
				queryValue = decodeURI(queryValue);// remove any URL encoding
				//queryValue = unescape(queryValue);
				break;
			}
		}
		return queryValue;
	},
	// this method returns a query string suitable for searching. It can be passed wither to the Netaphor search server for getting
	// results or for requesting a new search page
	getSearchQuery: function (){
		var searchUrl = "?";
		// add the query value
		searchUrl += "q=" + encodeURI(NetaphorData.q);
		
		// if there are filter params add the necessary param value and iterate over the values in the array
		NetaphorData.fq.length > 0  ? searchUrl += "&fq=" : ""; 
		for (var i = 0; i < NetaphorData.fq.length; i++){
			searchUrl += NetaphorData.fq[i];
			// only add the | seperator if there is another value coming
			i != NetaphorData.fq.length - 1 ? searchUrl += "|" : "";
		}
		
		// finally add the start value
		searchUrl += "&start=" + NetaphorData.start;
		return searchUrl; 
	}
}

window.onload=function(){	
	NetaphorQueryTools.parseQueryString();
};




