/**
 * Copyright 2010, TechniSat Digital GmbH, http://www.technisat.de/
 *
 * Uses AJAX Solr
 * http://github.com/evolvingweb/ajax-solr
 * Copyright 2009, Evolving Web Inc.
 * AJAX Solr is released under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0.
 */

// Define log, if not defined
if(typeof this.window['log'] != 'function')
	function log() {}


/**
 * Event based lib loading, needs to be defined here, not in functions.js
 * 
 * @param aLibs
 * @return void
 */
function loadLibs(aLibs, callback) {
	if(typeof window[callback] != 'function')
		return;
	
	if(aLibs.length == 0)
		return;
	
	var lib = aLibs.shift();
	
	$.ajax( {
		url : lib,
		complete : function(XMLHttpRequest, textStatus) {
			if(aLibs.length > 0) {
				loadLibs(aLibs, callback);
			} else {
				window[callback]();
			}
		},
		dataType : 'script',
		cache : true
	});	
}


/**
 * Run this if document is fully loaded
 */
jQuery(function($) {
	// these vars must be set
	if(typeof SearchConfig == 'undefined')
		alert('SearchConfig has to be defined before inclusion of solr.js');
	if(typeof SearchConfig.checkoutDir == 'undefined')
		alert('A checkout dir must be defined for SearchConfig.checkoutDir');

	// Default template to assure that presentation works correct
	defaultTpl = { 
			pageHeader : 'Results %from% to %to% of %total% for "%query%"',
			noResults : 'No results',
			autoComplete : '<h3>%title%</h3><p>%description%</p>',
			searchField : '%searchfield%',
			resultEntry : '<div><h3><a href="%url%" target="_blank" onclick="$.cookie(\'lasturl\', location.href);">%title%</a></h3><p class="description">%description%</p></div>'
	};	
	
	// Overload all unset vars
	if(SearchConfig.tpl) {
		for(key in defaultTpl) {
			if(typeof SearchConfig.tpl[key] == 'undefined') {
				SearchConfig.tpl[key] = defaultTpl[key];
			}
		}
	} else {
		SearchConfig.tpl = defaultTpl;
	}			
		
		
		
	// If these config vars are not set, an automatically setting is tried
	if(typeof SearchConfig.baseURL == 'undefined')
		SearchConfig.baseURL = location.href.substring(0, location.href.indexOf("/", location.href.indexOf("//")+2));
	if(typeof SearchConfig.solrUrl == 'undefined')
		SearchConfig.solrUrl = SearchConfig.checkoutDir + "/php/search.php?";
	if(typeof SearchConfig.statScript == 'undefined')
		SearchConfig.statScript = SearchConfig.checkoutDir + "/php/stats.php";
	if(typeof SearchConfig.seedScript == 'undefined')
		SearchConfig.seedScript = SearchConfig.checkoutDir + "/php/getseed.php";		
	if(typeof SearchConfig.residenceInterval == 'undefined')
		SearchConfig.residenceInterval = 0;
	if(typeof SearchConfig.inputID == 'undefined')
		SearchConfig.inputID = '#query';
	if(typeof SearchConfig.queryMaxlen == 'undefined')
		SearchConfig.queryMaxlen = 80;
	if(typeof SearchConfig.disabled == 'undefined')
		SearchConfig.disabled = false;
	
	SearchConfig.defaultParams = {
		'fl': 'id,title,description,url_t',
		'hl':true,
		'hl.fragsize' : 150,
		'hl.fl' : 'description',
		'hl.snippets' : 1,
		'hl.alternateField' : 'text_t',
		'hl.maxAlternateFieldLength'  : 150,
		'hl.usePhraseHighlighter' : true, 
		'hl.highlightMultiTerm' : true,
//		'indent' : 'on',
		'json.nl' : 'map'	
	};

	
	// These config vars should not be changed, they are set automatically
	SearchConfig.libMode = 'light'; // Default libmode (light: only load libs for auto completition)
	SearchConfig.query = '';	// Default query if no query is set
	SearchConfig.aLibs = []; // Container for javascript libs
	SearchConfig.clicked = false; // Count clicks
	
	// Define libmode, only load all libs if results are presented
	window.location.href.replace(/[?&]+(q)=([^&]*)/gi, function(m,key,value) {
		// check q parameter, if it is set, load all libs (for result presentation)
		if(key == 'q') {
			SearchConfig.libMode = 'full';
		}
	});

	// Default libs, autocomplete and cookie
	SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/functions.js');
	SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/jquery/jquery.autocomplete.pack.js');
	SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/jquery/jquery.cookie.pck.js');

	// Libs for result presentation
	if(SearchConfig.libMode == 'full') {
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/core/Core.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/core/AbstractManager.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/core/Parameter.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/core/ParameterStore.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/core/AbstractWidget.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/widgets/jquery/PagerWidget.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/helpers/jquery/ajaxsolr.theme.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/lib/helpers/ajaxsolr.support.pck.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/ResultWidget.js');
		SearchConfig.aLibs.push(SearchConfig.checkoutDir + '/js/solr/Manager.technisat.jquery.js');
	}

	// Search manually disabled
	if(SearchConfig.disabled)
		return;
	
	// load all libs (next when finshed)
	if(typeof SearchConfig.seedIDs == 'undefined')
		loadLibs(SearchConfig.aLibs, 'loadSeedID');
	else
		loadLibs(SearchConfig.aLibs, 'initSearch');
	
});


/**
 * load seedID via ajax request
 * 
 * @param cookieName
 * @return
 */
function loadSeedID() {
	var cookieName = 'seedID';
	
	// SeedID already loaded (stored in cookie)
	if($.cookie(cookieName) != null)
		if($.cookie(cookieName).match(/^[1-9][0-9]*$/gi)) {
			SearchConfig.seedIDs = $.cookie(cookieName);
			if(typeof SearchConfig.addParams == 'undefined')
				SearchConfig.addParams = '&fq=seedid_i:' + SearchConfig.seedIDs;
			
			initSearch();
			return;
		}
	
	// SeedID must be loaded via AJAX
	$.ajax( {
		url : SearchConfig.seedScript,
		success : function(data) {
			if(parseInt(data) > 0) {
				$.cookie(cookieName, data);
				SearchConfig.seedIDs = data;
				if(typeof SearchConfig.addParams == 'undefined')
					SearchConfig.addParams = '&fq=seedid_i:' + SearchConfig.seedIDs;
			}
		},
		complete : function(XMLHttpRequest, textStatus) {
			initSearch();
		},
		dataType : 'html',
		cache : false
	});		
	
}



function initSearch() {
	// SeedIDs must be configured or loaded via loadSeedID()
	if(typeof SearchConfig.seedIDs == 'undefined')
		return;
	
	// Check all query parameters
	window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		// count query, is q (for results) or acquery (for autocomplete) is set

		// Set query for result presentation
		if(key == 'q')
			SearchConfig.query = urldecode(value);
		
		// count query
		if(key == 'acquery' || key == 'q')
			countQuery(urldecode(value));
				
		// if get parameter searchoverride=yes, show search online, even if inactive
		if(key == 'searchoverride' && value=='yes')
			$.cookie('override', 'yes', { path: '/', expires: 1 });
		
		
		// Count clicks via php script
		if(key == 'searchpageID') {
			var clickUrl = appendUrlParam(SearchConfig.baseURL + SearchConfig.statScript, 'pageID=' + value + '&mode=click');
			$.ajax( {
				url : clickUrl,
				complete : function(XMLHttpRequest, textStatus) {},
				dataType : 'html',
				cache : false
			});
			
			$.cookie('searchpageID', value);
			
			if(SearchConfig.residenceInterval > 0)
				window.setInterval("countResidence()", (1000 * SearchConfig.residenceInterval));
		}
	});	
	
	// activation on dev projects
	/*
	if($.cookie('override') != 'yes') {
		if(isOnline())
			return;
	}
	*/

	// reset data for next click count
	if($.cookie('lasturl') != '' || $.cookie('searchpageID') != '') {
		$.cookie('lasturl', '');	
		$.cookie('searchpageID', '');
	}	
	
	
	// Show searchfield
	var sf = tplReplace(SearchConfig.tpl.searchField, {'%searchfield%': '<input type="text" id="query" name="query"/>'});
	$('#searchfield').html(sf).show();	
	
	/**
	 * AUTOCOMPLETE
	 * options: http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
	 */
	var requestSent = false;
	var jsonUrl = SearchConfig['solrUrl'] + 'select?wt=json&json.wrf=?' + SearchConfig.addParams + '&' + createQueryString(SearchConfig.defaultParams);
	// jsonUrl = appendUrlParam(jsonUrl, )
	$(SearchConfig.inputID).autocomplete(jsonUrl, {
		dataType: 'jsonp',
		delay : 250,
		minChars: 3,
		autoFill : true,
		scrollHeight : 300,
		max : 15,
		width : 350,
		selectFirst : false,
	    extraParams: {
			'q': function () { return prepareQuery($(SearchConfig.inputID).val()); }
		}, 
		parse : function(jsonData) {
			return parseJSONResponse(jsonData);
		},
		formatItem : function(data, count, max, value, term) {
			var replace = {
					'%title%' : data['title'],
					'%description%' : data['description']
			};
			return tplReplace(SearchConfig.tpl.autoComplete, replace);
		}
	}).result( function (e, listItem) {
		// click or enter on autocomplete result
		$.cookie('lasturl', location.href);
		$.cookie('searchpageID', listItem['id']);		
		location.href = appendUrlParam(listItem['url_t'], 'searchpageID=' + listItem['id'] + '&acquery=' + urlencode(SearchConfig.query));
		requestSent = true;
	}).bind('keyup', function(e) {
		// Keyup in input field
		SearchConfig.query = $(SearchConfig.inputID).val();
		if($(SearchConfig.inputID).val().length > SearchConfig.queryMaxlen)
			$(SearchConfig.inputID).val($(SearchConfig.inputID).val().substring(0, SearchConfig.queryMaxlen));
		
		// e.which: Enter
		// requestSent: No autocomplete result selected
		// trim: query not empty
		if(e.which == 13 && requestSent===false && jQuery.trim(SearchConfig.query) != '') {
			// redirect to resultpage
			showResults();
		}
		requestSent = false;
	});		
	
	/**
	 * RESULTS PRESENTATION
	 * Add Manager Result and Pager, if resultpage is used
	 */
	if(SearchConfig.libMode == 'full') {
		var Manager;
		
		// Init AjaxSolr.Manager for result presentation
		Manager = new AjaxSolr.Manager( {
			solrUrl : SearchConfig.solrUrl,
			addParams : SearchConfig.addParams
		});
		Manager.init();	
		
		// Add default params
		for ( var name in SearchConfig.defaultParams) {
			Manager.store.addByValue(name, SearchConfig.defaultParams[name]);
		}	
		
		Manager.addWidget(new AjaxSolr.ResultWidget({
	      id: 'result',
	      target: '#docs'
	    }));
		 
		Manager.addWidget(new AjaxSolr.PagerWidget({
	      id: 'pager',
	      target: '#pager',
	      prevLabel: '<span>&lt;</span>',
	      nextLabel: '<span>&gt;</span>',
	      innerWindow: 1,
	      renderHeader: function (perPage, offset, total) {
			
			var replace = { '%from%' : Math.min(total, offset + 1), 
							'%to%' : Math.min(total, offset + perPage), 
							'%total%' : total, 
							'%query%' : prepareOutputQuery(SearchConfig.query)
			};
			
			var pageHeaderText = tplReplace(SearchConfig.tpl.pageHeader, replace);
			$('#pager-header').html($('<span/>').text(pageHeaderText));
	      }
	    }));
		
		
		// keep query in field
		$(SearchConfig.inputID).val(SearchConfig.query);
		
		Manager.store.addByValue('q', prepareQuery(SearchConfig.query));
		Manager.doRequest();			
	}	

	
}