(function($j){

	$j.fn.jsonSuggest = function(searchData, settings) {
		
		var defaults = {  
			minCharacters: 1,
			maxResults: undefined,
			wildCard: "",
			caseSensitive: false,
			notCharacter: "!",
			maxHeight: 350,
			highlightMatches: true,
			onSelect: function() {
						document.wierdengooglezoek.submit();
					},	
			ajaxResults: false,
			width: 300,
			s_align: "left"
			};  
		settings = $j.extend(defaults, settings);  
		
		return this.each(function() {
			
			function regexEscape(txt, omit) {
				var specials = ['/', '.', '*', '+', '?', '|',
								'(', ')', '[', ']', '{', '}', '\\'];
				
				if (omit) {
					for (var i=0; i < specials.length; i++) {
						if (specials[i] === omit) { specials.splice(i,1); }
					}
				}
				
				var escapePatt = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
				return txt.replace(escapePatt, '\\$1');
			}
			
			var obj = $j(this),
				wildCardPatt = new RegExp(regexEscape(settings.wildCard || ''),'g'),
				results = $j('<div />'),
				currentSelection, pageX, pageY;
			
			function selectResultItem(item) {
				obj.val(item.text);
				$j(results).html('').hide();
				
				if (typeof settings.onSelect === 'function') {
					settings.onSelect(item);
				}
			}

			function setHoverClass(el) {
				$j('div.resultItem', results).removeClass('hover');
				$j(el).addClass('hover');
				
				currentSelection = el;
			}
			
			function buildResults(resultObjects, sFilterTxt) {
				sFilterTxt = "(" + sFilterTxt + ")";
			
				var bOddRow = true, i, iFound = 0,
					filterPatt = settings.caseSensitive ? new RegExp(sFilterTxt, "g") : new RegExp(sFilterTxt, "ig");
					
				$j(results).html('').hide();
				
				for (i = 0; i < resultObjects.length; i += 1) {
					var item = $j('<div />'),
						text = resultObjects[i].text;
						
					if (settings.highlightMatches === true) {
						text = text.replace(filterPatt, "<strong>$1</strong>");
					}
					
					if (typeof resultObjects[i].text === 'string') {
						$j(item).append('<p class="text">' + text + '</p>');
					}
										
					$j(item).addClass('resultItem').
						addClass((bOddRow) ? 'odd' : 'even').
						click(function(n) { return function() {
							selectResultItem(resultObjects[n]);						
						};}(i)).
						mouseover(function(el) { return function() { 
							setHoverClass(el); 
						};}(item));
					
					$j(results).append(item);
					bOddRow = !bOddRow;
					
					iFound += 1;
					if (typeof settings.maxResults === 'number' && iFound >= settings.maxResults) {
						break;
					}
				}
				
				if ($j('div', results).length > 0) {
					currentSelection = undefined;
					$j(results).show().css('height', 'auto');
					
					if ($j(results).height() > settings.maxHeight) {
						$j(results).css({'overflow': 'auto', 'height': settings.maxHeight + 'px'});
					}
				}
			}
			
			// Prepare the search string based on the settings for this plugin,
			// run it against each item in the searchData and display any 
			// results on the page allowing selection by the user.
			function runSuggest(e) {	
				if (this.value.length < settings.minCharacters) {
					$j(results).html('').hide();
					return false;
				}
				
				var resultObjects = [],
					sFilterTxt = (!settings.wildCard) ? regexEscape(this.value) : regexEscape(this.value, settings.wildCard).replace(wildCardPatt, '.*'),
					bMatch = true, 
					filterPatt, i;
						
				if (settings.notCharacter && sFilterTxt.indexOf(settings.notCharacter) === 0) {
					sFilterTxt = sFilterTxt.substr(settings.notCharacter.length,sFilterTxt.length);
					if (sFilterTxt.length > 0) { bMatch = false; }
				}
				sFilterTxt = sFilterTxt || '.*';
				sFilterTxt = settings.wildCard ? '^' + sFilterTxt : sFilterTxt;
				filterPatt = settings.caseSensitive ? new RegExp(sFilterTxt) : new RegExp(sFilterTxt,"i");
				
				// Get the results from the correct place. If settings.ajaxResults then results are retrieved from
				// an external function each time they are needed else they are retrieved from the data
				// given on contruction.
				if (settings.ajaxResults === true) {
					resultObjects = searchData(this.value, 	settings.wildCard, 
															settings.caseSensitive,
															settings.notCharacter);
															
					if (typeof resultObjects === 'string') {
						resultObjects = JSON.parse(resultObjects);
					}
				}
				else {
					// Look for the required match against each single search data item. When the not
					// character is used we are looking for a false match. 
					for (i = 0; i < searchData.length; i += 1) {
						if (filterPatt.test(searchData[i].text) === bMatch) {
							resultObjects.push(searchData[i]);
						}
					}
				}
				
				buildResults(resultObjects, sFilterTxt);
			}
			
			// To call specific actions based on the keys pressed in the input
			// box. Special keys are up, down and return. All other keys
			// act as normal.
			function keyListener(e) {
				switch (e.keyCode) {
					case 13: // return key
						$j(currentSelection).trigger('click');
					
						return false;
					case 40: // down key
						if (typeof currentSelection === 'undefined') {
							currentSelection = $j('div.resultItem:first', results).get(0);
						}
						else {
							currentSelection = $j(currentSelection).next().get(0);
						}
						
						setHoverClass(currentSelection);
						if (currentSelection) {
							$j(results).scrollTop(currentSelection.offsetTop);
						}
						
						return false;
					case 38: // up key
						if (typeof currentSelection === 'undefined') {
							currentSelection = $j('div.resultItem:last', results).get(0);
						}
						else {
							currentSelection = $j(currentSelection).prev().get(0);
						}
						
						setHoverClass(currentSelection);
						if (currentSelection) {
							$j(results).scrollTop(currentSelection.offsetTop);
						}
						
						return false;
					default:
						runSuggest.apply(this, [e]);
				}
			}
			
			// Prepare the input box to show suggest results by adding in the events
			// that will initiate the search and placing the element on the page
			// that will show the results.
			$j(results).addClass('jsonSuggestResults').
				css({
					'top': (obj.position().top + obj.height() + 5) + 'px',
					'width': settings.width || ((obj.width() + 5) + 'px')
				}).hide();
				
				//VNO
				if (settings.s_align == "left") {
					$j(results).addClass('jsonSuggestResults').css({'left': obj.position().left + 'px'}).hide();
				}
						
				else {
					$j(results).addClass('jsonSuggestResults').css({'left':obj.position().left -settings.width + obj.width() + 'px'}).hide();
				}
				
			obj.after(results).
				keyup(keyListener).
				blur(function(e) {
					// We need to make sure we don't hide the result set
					// if the input blur event is called because of clicking on
					// a result item.
					var resPos = $j(results).offset();
					resPos.bottom = resPos.top + $j(results).height();
					resPos.right = resPos.left + $j(results).width();
					
					if (pageY < resPos.top || pageY > resPos.bottom || pageX < resPos.left || pageX > resPos.right) {
						$j(results).hide();
					}
				}).
				focus(function(e) {
					$j(results).css({
						'top': (obj.position().top + obj.height() + 5) + 'px',
						'left': obj.position().left + 'px'
						//'left':obj.position().left - obj.width() + 'px',
					});
					
					// VNO
					if (settings.s_align == "left") {
						$j(results).css({'left': obj.position().left + 'px'});
					}
					else {
						$j(results).css({'left':obj.position().left -settings.width + obj.width() + 'px'});
					}
					
				
					if ($j('div', results).length > 0) {
						$j(results).show();
					}
				}).
				attr('autocomplete', 'off');
			$j().mousemove(function(e) {
				pageX = e.pageX;
				pageY = e.pageY;
			});
			
			// Opera doesn't seem to assign a keyCode for the down
			// key on the keyup event. why?
			if ($j.browser.opera) {
				obj.keydown(function(e) {
					if (e.keyCode === 40) { // up key
						return keyListener(e);
					}
				});
			}
			
			// Escape the not character if present so that it doesn't act in the regular expression
			settings.notCharacter = regexEscape(settings.notCharacter || '');
			
			// We need to get the javascript array type data from the searchData setting.
			// Setting can either be a string, already an array or a function that returns one
			// of those things. We only get this data if it isn't being provided using ajax on
			// each search
			
			if (!settings.ajaxResults) {
				if (typeof searchData === 'function') {
					searchData = searchData();
				}
				if (typeof searchData === 'string') {
					searchData = JSON.parse(searchData);
				}
			}
		});
	};

})(jQuery);
