/**
 * jquery.multiAutoSuggest.js
 * @author lewis barclay - splendid : www.howsplendid.com
 */

 
(function($) {

	 /* @name multiAutoSuggest
     * 	@type jQuery
     * 	@param cfg A set of key/value pairs to set as configuration properties.
     *  cfg  :
     *  	{
     *  		jsonUrlTpl 	: a template for the JSON url - must contain space for text and numItems i.e. getData.json?q={text}&s={numItems} 
     *   		resultsid	: the id of the element to add the list to (should be hidden by default using display:none)
     *   		innerClass	: the class of the inner div, containing the list of suggestions
     *   		waitIn		: the amount of time in milliseconds to wait before requesting the suggestions data
     *   		waitOut		: the amount of time in milliseconds to wait before hiding the suggestions
     *   		itemCount	: the number of items to return for each list
     *   		footerHtml	: html to be appended to the bottom of the div
     *  	}
     */
    $.fn.multiAutoSuggest = function(cfg) {
        return this.each(function() {
            new $jmas(this, cfg);
        });
    };
	
	$.multiAutoSuggest = function(elm, cfg){
		//some defaults
		cfg = (cfg?cfg:{});
		cfg.jsonUrlTpl = (cfg.jsonUrlTpl ? cfg.jsonUrlTpl :  'js/exampledata/suggestions.json?q={text}&s={numItems}');
		cfg.resultsId = (cfg.resultsId ? cfg.resultsId : 'searchSuggestions');
		cfg.innerClass = (cfg.innerClass ? cfg.innerClass :  'predictiveSearchMain');
		cfg.waitIn = (cfg.waitIn ? cfg.waitIn : 1000);
		cfg.waitOut = (cfg.waitOut ? cfg.waitOut : 7500);
		cfg.itemCount = (cfg.itemCount ? cfg.itemCount : 5);
		cfg.footerHtml = (cfg.footerHtml ? cfg.footerHtml : ''); 
		
		//helpers -->
		cfg.rId = (function(c){return '#' + c.resultsId;})(cfg);
		
		//validation & checks 
		if($(cfg.rId+' div').length == 0){
			$(cfg.rId).append('<div class=\"'+cfg.innerClass+'\"></div>')
		}
		
		//event handler
		$(elm).keypress(function(){
			suggestionKeyDown(elm, cfg);
		})
	};
	
	//shortcut for internal use
	$jmas = $.multiAutoSuggest;
	
	function suggestionKeyDown(elm, cfg){
		if (cfg.waitOutTimeout) {clearTimeout(cfg.waitOutTimeout);};
		if (cfg.waitInTimeout) {clearTimeout(cfg.waitInTimeout);};
		$(cfg.rId).css('display', 'none');		
		
		cfg.waitInTimeout = setTimeout(function(){
				getSuggestions($(elm).val(), displaySuggestions, cfg);
			}, cfg.waitIn);
	}
	
	function getSuggestions(input, onCompletedFn, cfg){
		var jsonUrl = (function(){
			return cfg.jsonUrlTpl.replace('{text}', input).replace('{numItems}', cfg.itemCount);
			})();
		
		jQuery.getJSON(jsonUrl, function(results, status){
			onCompletedFn(results, cfg);}
			);
	}
	
	function displaySuggestions(suggestions, cfg){
		var html = '';
		for(var i = 0; i<suggestions.items.length; i++){
			html += createSuggestionsHtml(suggestions.items[i]);
		}
		
		if(cfg.footerHtml){
			html += cfg.footerHtml;
		}
		
		//setup the content and then show
		$(cfg.rId+' div').html('');
		$(cfg.rId+' div').html(html);
		$(cfg.rId).fadeIn('quick');
		
		//setup a timeout for the fade out
		if(cfg.waitOut > 0){
			cfg.waitOutTimeout = setTimeout(function(){
				$(cfg.rId).fadeOut('slow');
			}, cfg.waitOut)
		} 
	}
	
	function createSuggestionsHtml(suggestionsItem){
		function hTpl(text){return ['<h2>', text,'</h2>\n'].join('');};
		function ulTpl(listHtml){return ['<ul>', listHtml,'</ul>\n'].join('');};
		function liTpl(text){return ['<li>', text ,'<li>\n'].join('');};
		function aTpl(url, title){return ['<a href=\"', url ,'\">', title,'</a>'].join('');};
		
		var listItems = '';
		
		for(var i = 0; i < suggestionsItem.options.length; i++){
			var so = suggestionsItem.options[i];
			
			listItems += liTpl(aTpl(so[1], so[0]));
		}
		
		var html = hTpl(suggestionsItem.title) + ulTpl(listItems);

		return html; 		  
	}	
	
})(jQuery);


