selected = '';

var facets;
var excludes;
var showResultsFrom;
var numberOfItemsPerPage;
var noResultsFound;
var resultsFrom;
var	resultsUntil;
var	facetPagingNext;
var	facetPagingPrevious;
var fromMaster;
var facetItemDisableText;

$(document).ready(function(){
	// initialize facet settings
	var settingsUrl = $("#settingsCall").attr("href");
	if (settingsUrl != undefined && settingsUrl != '') {
		$.ajax({
			mode: "queue", 
			url: settingsUrl,
			type: "GET",
			dataType: "json",
			success: initFacetSettings
		});
		
		$("a[class^='facet']").each(function () {
			if ($(this).attr("rel") != 'true') {
				$(this).attr("rel", "false");
			} else {
				divId = '#' + $(this).next().text() + '#';
				selected += divId;
			}
		});
		
		defineForm();
	}
});

function initFacetSettings(data) {	
	facets = data.facets;
	showResultsFrom = data.showresultsfrom;
	numberOfItemsPerPage = data.numberofresultsperpage;
	noResultsFound = data.noresultstext;
	resultsFrom = data.showresultsfromtext;
	resultsUntil = data.showresultsuntiltext;
	facetPagingNext = data.pagingnexttext;
	facetPagingPrevious = data.pagingprevioustext;
	facetItemDisableText = data.facetitemdisable;
	excludes = data.exclude;
	
	fromMaster = parseInt(showResultsFrom);
}

function initAutoCompletion(urlFieldId, queryFieldId) {
	var autoCompleteUrl = $('#' + urlFieldId);
	var queryFieldId = $('#' + queryFieldId);
	if (autoCompleteUrl.length != 0 && queryFieldId.length != 0) {
		queryFieldId.autocomplete(autoCompleteUrl.attr("value") + '&' + queryFieldId.val(), {
			delay:10,
			width: 260,
			selectFirst: true,
			scroll:false,
			formatItem: function(item) {
				return item[0] + ' ' + item[1];
			}	
		});
	}
}

function showDetails() {
  $('#details').jqmShow();
}
  
function formProcess(event) {
  event.preventDefault();

  search('','');
  
  return false;
}

function search(mode, from) {
	base = $('#ajaxcall').attr("href");
	var urlSep = '&';
	
	if (base != null) {
		if (base.indexOf('?') < 0) {
			urlSep = '?';
		}
		base += urlSep + 'query=' + encodeURIComponent($('#searchquery').val()); 
		
		if (mode != 'initial') {
			$("a[rel^='true']").each(function () {
				var aFacetName = $(this).next().text().split('|')[0];
				var aFacetValue = $(this).next().text().split('|')[1];
				base += '&' + aFacetName + '=' + escape(aFacetValue);
			});
		}
		
		if (from != null && from != '') {
			base += '&from=' + from;
			//store the from in a hidden field, workaround for the next and previous buttons.
			fromMaster = from;
		}

		url = base + '&retrieve=all'
		
		$.ajax({
			mode: "queue", 
			url: url,
			type: "GET",
			dataType: "json",
			success: fillResult
		});
	}
}

function defineForm() {
	$('a.facet').click(searchFacet);
	$('a.paginglink').click(pageClick);
	$('a.pbut').click(pageClick); 
	
	$("div.more").each(function() {
		$(this).hide();
	});  
}

function pageClick(event) {
	var from = parseInt(fromMaster);
	search('', $(this).attr("name"));
	
	// prevent the link from following it's href
	event.preventDefault();
}

function searchFacet(event) {
	checked = $(this).attr("rel");
	if (checked == 'false') {
		$(this).attr("rel", "true");
	} else {
		$(this).attr("rel", "false");
	}
	checked = $(this).attr("rel");
	divId = '#' + $(this).next().text() + '#';
	if (checked == "true") {
		selected += divId;
	} else {
		selected = selected.replace(divId,'');  
	}
	search('', '0');
	
	// prevent the link from following it's href
	event.preventDefault();
}

function fillValues(data) {
	if (data.results.length > 0) {
		var $facetWrapper = $('<div class="facet-wrapper"></div>');
		$.each(data.facets, function(i,facet){
			// Get the name of the facet
			var facetName = facet.facet;
			// Get the label of the facet
			var facetLabel = facet.facet;
			
			// Check if the current facet has facet items which should be excluded
			var excludeFacet;
			$.each(excludes, function(k,exclude){
				if (exclude.facetname == facetName) {
					excludeFacet = exclude;
				}
			});
			
			// Loop the facet items and check if they have results. If not, the entire facet should not be rendered.
			var resultsFound = false;
			var facetItemExcluded = false;
			$.each(facet.values, function(k,facetitem){
				if (typeof facetitem !=  'undefined') {
					if (excludeFacet != undefined) {
						$.each(excludeFacet.facetitems, function(k,item){
							if (item.name == facetitem.name) {
								facetItemExcluded = true;
							}
						});
					}
					if (facetitem.count > 0 && !facetItemExcluded) {
						resultsFound = true;
					}
					facetItemExcluded = false;
				}
			});
			
			// We need language labels for the facet labels
			$.each(facets, function(i,facetsetting){
				if (facetLabel.indexOf(facetsetting.facetname) > -1) {
					facetLabel = facet.facet.replace(facetsetting.facetname, facetsetting.label);
				}
			})
			
			// If results are found render the facet
			if (resultsFound) {
				var $facetTitle = $('<div class="facet-title">' + facetLabel + '</div>');
				var $facetDef = $('<input type="hidden" class="facetdef" name="facets" value="' + facet.facet + '" />');
				
				$facetTitle.append($facetDef);
				$facetWrapper.append($facetTitle);
				var $facetItemWrapper = $('<div class="facet-items"></div>');
				var $facetList = $('<ul></ul>');
				$facetItemWrapper.append($facetList);
				$facetWrapper.append($facetItemWrapper);
				
				// For each facet item...
				$.each(facet.values, function(j,facetvalue){
					if (typeof facetvalue !=  'undefined') {
						var showFacetItem = true;
						
						// Check if the facet item should be excluded
						if (excludeFacet != undefined) {
							$.each(excludeFacet.facetitems, function(k,item){
								if (item.name == facetvalue.name) {
									showFacetItem = false;
								}
							});
						}
						
						// If the facet item has results AND the facet item must not be excluded...
						if (facetvalue.count != 0 && showFacetItem) {
							var $facetItem = $('<li></li>');
							$facetList.append($facetItem);
							
							var selectedFacetItem = false;
							
							if (selected.indexOf('#' + facet.facet + '|' + facetvalue.name + '#') != -1) {
								selectedFacetItem = true;
							}
							
							var relValue = "";
							if (selectedFacetItem) {
								relValue = 'true';
							} else {
								relValue += 'false';
							}
							
							var facetLabel = facetvalue.label;
							if (selectedFacetItem) {
								facetLabel = '<strong>' + facetLabel + '</strong>';
							}
							
							var $facetLink = '<a rel="' + relValue + '" href="#" onclick="return false;" class="facet" title="' + facetvalue.label + '">' + facetLabel + '</a> ';
														
							$facetItem.append($facetLink);
							
							var $facetVals = $('<span class="displayNone">' + facet.facet + '|' + facetvalue.name + '</span>');
							$facetItem.append($facetVals);
							
							var $facetCount;
							if (selectedFacetItem) {
								$facetCount = $('<span class="facetcount"><strong>(' + facetItemDisableText + ')</strong></span>');;
							} else {
								$facetCount = $('<span class="facetcount">(' + facetvalue.count + ')</span>');
							}
							$facetItem.append($facetCount);
						}
					}
				
				});
			}
		});

		// Append the constructed HTML
		$('#facetinfo').append($facetWrapper);
		
		// Attach event handlers to the constructed HTML
		defineForm();
	}
}

function fillResult(data) {
	$('#searchresult').html("");
	var from = parseInt(fromMaster);
	var nrOfItemsPerPage = parseInt(numberOfItemsPerPage);
  
	
	var until = from + nrOfItemsPerPage;
	if (data.results.length < nrOfItemsPerPage) {
		until = from + data.results.length;
	}
	
	newData = '<div class="search-result-count">';
	
	if (data.results.length == 0) {
		newData += noResultsFound;
	} else {
		newData += resultsFrom + ' ' + (from + 1) + ' ' + resultsUntil + ' ' + until;
	}
	
	newData += '</div>'
	newData += '<div class="search-wrapper">';
	newData += '<dl id="searchresultbox">';
	 
	$.each(data.results, function(i,r){
		newData += '<dt>';
		newData += '<span class="count">' + (from + (i + 1)) + '.&nbsp;</span>';
		newData += '<a href="' + r.location + '"><span>' + r.title + '</span></a>';
		newData += '</dt>';
		
		newData += '<dd>';
		newData += '<p>';
		
		if (r.snippets != null && r.snippets.length > 0) {
			$.each(r.snippets, function(j,s) {
				newData += s.snippet;
				if (!(r.snippets.length == (j + 1))) {
					newData += ' ... ';
				}
			})
		} else {
			newData += r.summary;
		}
		
		newData += '</p>';
		newData += '</dd>';
    
	});
	
	newData += '</dl></div><div class="clearer"><!--  --></div>';
	
	$('#searchresult').append(newData);
	
	// add the paging
	$('#pagingblock').html("");
	$('#pagingblock').append(createPagingBlock(data));	
   
	$('#facetinfo').html('');
	fillValues(data);
}

function createPagingBlock(data){
	paginghtml = '';
	currentFrom = parseFloat(fromMaster);
	itemPerPage = parseFloat(numberOfItemsPerPage);
	//determine the number of pages to build the paging for
	pages = data.count / parseFloat(itemPerPage);
	pages = pages.toFixed(0);
	
	paginghtml += "<div class=\"top\"><!--  --></div>";
	paginghtml += "<div class=\"wrapper\">";
	
	if ((pages * parseFloat(itemPerPage)) < data.count){
		pages ++;
	}
	
	// max pages size is 10
	if (pages > 10) {
		pages = 10;
	}
	
	// max data count = pages * itemPerPage
	var dataCount = data.count;
	if (dataCount > (pages * itemPerPage)) {
		dataCount = (pages * itemPerPage);
	}
	if (currentFrom > 1) {
		var previousLabel = facetPagingPrevious;
		paginghtml += '<span class="prev"><a href="#" onclick="return false;" class="paginglink navigation" name="'+ (currentFrom - itemPerPage) + '"><span>' + previousLabel + '</span></a></span>';
	}
	
	for(k = 0; k < pages; k++){
		showpage = k + 1;
		var until = showpage * itemPerPage;
		// check if the last page contains less results then 'itemPerPage'
		if (k == (pages - 1)) {
			if ((dataCount%itemPerPage) != 0) {
				until = (showpage * itemPerPage) - (itemPerPage - (data.count%itemPerPage));
			}
		}
		if (currentFrom != (k*itemPerPage)) {
			paginghtml += '<a href="#" onclick="return false;" class="paginglink navigation" name="'+ k*itemPerPage + '"><span>' + showpage + '</span></a>';
		}else{
			paginghtml += '<span>' + showpage + '</span>'
		}
	}
	
	if ((currentFrom != ((pages-1) * itemPerPage)) && pages > 1) {
		var nextLabel = facetPagingNext;
		paginghtml += '<span class="next"><a href="#" onclick="return false;" class="paginglink navigation" name="'+ (currentFrom + itemPerPage) + '"><span>' + nextLabel + '</span></a></span>';
	}
	
	paginghtml += '<div class="clearer"><!--  --></div></div><div class="bottom"><!--  --></div>';
	
	return paginghtml;
}
