
var nxautocompletebox = {
	ajaxDelay: 500,
	highlightMinLength: 3
};

(function() {
	
	
	
	
	if (typeof(nxautocompletebox.xajaxwrapper) == 'undefined') {
		nxautocompletebox.xajaxwrapper = function(a, b, c) {
			
			var tmpXajaxRequestUri = xajaxRequestUri;
			var tmpXajaxDebug = xajaxDebug;
			var tmpXajaxStatusMessages = xajaxStatusMessages;
			var tmpXajaxWaitCursor = xajaxWaitCursor;
			var tmpXajaxDefinedGet = xajaxDefinedGet;
			var tmpXajaxDefinedPost = xajaxDefinedPost;
			var tmpXajaxLoaded = xajaxLoaded;
			
			xajaxRequestUri = '?eID=nxautocompletebox';
			xajaxDebug = false;
			xajaxStatusMessages = false;
			xajaxWaitCursor = false;
			xajaxDefinedGet = 0;
			xajaxDefinedPost = 1;
			xajaxLoaded = false;
			
			var returnValue = tx_nxautocompletebox__checkAutoCompleteRequest(a, b, c);
			
			xajaxRequestUri = tmpXajaxRequestUri;
			xajaxDebug = tmpXajaxDebug;
			xajaxStatusMessages = tmpXajaxStatusMessages;
			xajaxWaitCursor = tmpXajaxWaitCursor;
			xajaxDefinedGet = tmpXajaxDefinedGet;
			xajaxDefinedPost = tmpXajaxDefinedPost;
			xajaxLoaded = tmpXajaxLoaded;
			
			return returnValue;
			
		};
	}
	
	
	
	
	if (typeof(nxautocompletebox)=='undefined')
		nxautocompletebox = {};
	nxautocompletebox.ajaxStack = {};
	nxautocompletebox.boxClosingTimer = {};
	nxautocompletebox.cursorStack = {};
	nxautocompletebox.submitEventStack = {};
	if (typeof(nxautocompletebox.ajaxDelay)!='number')
		nxautocompletebox.ajaxDelay = 1000;
	if (typeof(nxautocompletebox.highlightMinLength)!='number')
		nxautocompletebox.highlightMinLength = 3;
	
	
	
	
	if (typeof(nxautocompletebox.ajaxCallBack)=='undefined') {
		nxautocompletebox.ajaxCallBack = function(possibleCollections, targetBoxId, searchSlotName) {
			
			if (typeof(nxautocompletebox.resultsBlock)=='undefined')
				nxautocompletebox.resultsBlock = {};
			
			if (typeof(nxautocompletebox.resultsBlock[targetBoxId])=='undefined')
				nxautocompletebox.resultsBlock[targetBoxId] = [];
				
			nxautocompletebox.resultsBlock[targetBoxId] = possibleCollections;
			
			var target = $(targetBoxId);
			var source = $('nxautocompletebox_input-'+targetBoxId+'-');
			target.innerHTML = '';
			
			var ulElement = new Element("ul", {}).injectInside(target).setStyle("display", "block");
			var eachExpressionsMatching = true;
			
			$each(possibleCollections[0], function(singleExpression) {
				if (singleExpression.foundPattern!=singleExpression.searchedPattern || singleExpression.patternFound!='1')
					eachExpressionsMatching = false;
			});
			var targetSet = [target, $(target.getAttribute('id')+'-iframe')];
			if (
				possibleCollections.length == 1
				&&
				(
					(possibleCollections[0][0].foundPattern == '' && possibleCollections[0][0].patternFound == '')
					||
					eachExpressionsMatching
				)
			) 
			{
				$each(targetSet, function(targetElement) {
						targetElement.setStyles({
						display: 'none'
					});
				});
			}
			else {
				$each(targetSet, function(targetElement) {
						targetElement.setStyles({
						display: 'block'
					});
				});
			}
			
			$each(possibleCollections, function(searchCollection) {
				var liElement = new Element("li", {}).injectInside(ulElement).setStyle("display", "block");
				var plainContent = '';
				var formatedContent = '';
				nxautocompletebox.cursorStack[targetBoxId] = false;
				$each(searchCollection, function(singleElement) {
					plainContent = singleElement.foundPattern+' '+plainContent;
					if (singleElement.patternFound) {
						formatedContent = singleElement.foundPattern.replace(singleElement.searchedPattern, '<span class="matchingSubPart">'+singleElement.searchedPattern+'</span>')+' '+formatedContent;
					}
					else {
						if (typeof singleElement.foundPattern != 'undefined') {
							formatedContent = '<span class="notMatchingExpression">'+singleElement.foundPattern+'</span> '+formatedContent;
						}
					}
				});
				liElement.innerHTML = '<a rel="nxautocompleteboxSuggestion::'+plainContent+'">'+formatedContent+'</a>';
				liElement.addEvent('click', function() {
					source.value = plainContent;
					source.focus();
					nxautocompletebox.inputChanged(targetBoxId, plainContent);
					nxautocompletebox.cursorStack[targetBoxId] = plainContent;
					nxautocompletebox.xajaxwrapper(targetBoxId, plainContent, 0);
				});
			});
			if(typeof(nxautocompletebox.eventsList['complete'])!='undefined') {
				$each(nxautocompletebox.eventsList['complete'], function(callBackFunction) {
					if(typeof(callBackFunction)=='function') {
						callBackFunction(source, target, searchSlotName, possibleCollections);
					}
				});
			}
		};
	}




	if (typeof(nxautocompletebox.inputBlured) == 'undefined') {
		nxautocompletebox.inputBlured = function(callerObject) {
			
			var event = new Event(callerObject);
			
			if (typeof(event)=='undefined')
				return false;
			if (typeof(event.target)=='undefined')
				return false;
			if(typeof(event.target.id)!='string')
				return false;
			targetBoxId = /^nxautocompletebox_input-(.*)-$/.exec(event.target.id)[1];
			var target = $(targetBoxId);
			var targetSet = [target, $(target.getAttribute('id')+'-iframe')];
			nxautocompletebox.boxClosingTimer[targetBoxId] = (function() {
				$each(targetSet, function(targetElement) {
					targetElement.setStyles({display:"none"});
				});
			}).delay(150);

		};
	}




	if (typeof(nxautocompletebox.closeSuggestionBox) == 'undefined') {
		nxautocompletebox.closeSuggestionBox = function(targetBox, sourceInput) {

			var dummyinput = new Element('input', {type: 'text'});
			var targetSet = [targetBox, $(targetBox.getAttribute('id')+'-iframe'), dummyinput];

			dummyinput.injectInside(targetBox);
			try {
				dummyinput.focus();
			}
			catch (e) {
			}

			$each(targetSet, function(targetElement) {
				targetElement.setStyles({display:"none"});
			});
		};
	}




	if (typeof(nxautocompletebox.highlightContents) == 'undefined') {
		nxautocompletebox.highlightContents = function(targetBoxId, highlightExpressionsString) {
			targetBoxId = /nxautocompletebox-input-(.*)-[0-9]+_[0-9]+-/.exec(targetBoxId);
			if (targetBoxId!=null && typeof(targetBoxId[1])!='undefined' && targetBoxId[1].length > 0) {
				targetBoxId = targetBoxId[1];
				highlightExpressions = [];
				$each(highlightExpressionsString.split(' '), function(highlightExpression) {
					if (highlightExpression.length>=nxautocompletebox.highlightMinLength)
						highlightExpressions.push(highlightExpression.trim());
				});
				$each(document.getElements('.nxautocompletebox-highlight-'+targetBoxId), function(highlightableBox) {
					highlightableBox.removeClass('nxautocompletebox-highlighted-box');
					highlightableBox.addClass('nxautocompletebox-highlightable-box');
					$each(highlightableBox.getElements('.nxautocompletebox-highlighted-content'), function(highlightedContent) {
						highlightedContent.removeClass('nxautocompletebox-highlighted-content');
						highlightedContent.addClass('nxautocompletebox-highlightable-content');
					});
					if (highlightExpressions.length==0)
						return false;
					var foundElementsStack = [];
					var foundExpressionsStack = {};
					var foundExpressionsCounter = 0;
					$each(highlightableBox.getElements('.nxautocompletebox-highlightable-content'), function(highlightedContent) {
						$each(highlightExpressions, function(highlightExpression) {
							if (highlightedContent.innerHTML.toLowerCase().search(highlightExpression.toLowerCase())!=-1) {
								foundElementsStack.push(highlightedContent);
								if (typeof(foundExpressionsStack[highlightExpression]) == 'undefined') {
									foundExpressionsCounter++;
								}
								foundExpressionsStack[highlightExpression] = highlightExpression;
							}
						});
					});
					if (highlightExpressions.length == foundExpressionsCounter) {
						$each(foundElementsStack, function(highlightedContent) {
							highlightedContent.removeClass('nxautocompletebox-highlightable-content');
							highlightedContent.addClass('nxautocompletebox-highlighted-content');
						});
						highlightableBox.removeClass('nxautocompletebox-highlightable-box');
						highlightableBox.addClass('nxautocompletebox-highlighted-box');
					}
				});
			}
			else 
				targetBoxId = '';
		};
	}
	
	
	
	
	if (typeof(nxautocompletebox.drawHoverLinks) == 'undefined') {
		nxautocompletebox.drawHoverLinks = function(targetBoxId) {
			$each($(targetBoxId).getElements('a'), function(linkElement, position) {
				if (linkElement.rel.test('^nxautocompleteboxSuggestion::.*')) {
					var suggetstion = linkElement.rel.substr(29);
					linkElement.className =
						(nxautocompletebox.cursorStack[targetBoxId] == suggetstion)
						? 'hover'
						: 'unhover'
						;
				}
			});
		};
	}
	
	
	
	
	if (typeof(nxautocompletebox.moveCursor) == 'undefined') {
		nxautocompletebox.moveCursor = function(targetBoxId, direction) {
			var currentPosition = -1;
			var newPosition;
			var newContent;
			var maxPosition = -1;
			var suggestion;
			if (typeof(nxautocompletebox.cursorStack[targetBoxId])=='undefined')
				nxautocompletebox.cursorStack[targetBoxId] = '';
			$each($(targetBoxId).getElements('a'), function(linkElement, position) {
				suggestion = linkElement.rel.substr(29);
				maxPosition = position;
				if (suggestion==nxautocompletebox.cursorStack[targetBoxId])
					currentPosition = position;
			});
			newPosition=0;
			if (currentPosition==-1)
				newPosition=0;
			else if (direction == 'up')
				newPosition = currentPosition-1;
			else if (direction == 'down')
				newPosition = currentPosition+1;
			if (newPosition>maxPosition)
				newPosition = maxPosition;
			$each($(targetBoxId).getElements('a'), function(linkElement, position) {
				if (position==newPosition) {
					suggestion = linkElement.rel.substr(29);
					nxautocompletebox.cursorStack[targetBoxId] = suggestion;
				}
			});
			$('nxautocompletebox_input-'+targetBoxId+'-').value = suggestion;
			nxautocompletebox.highlightContents(targetBoxId, suggestion);
		};
	}
	
	
	
	
	if (typeof(nxautocompletebox.inputChanged) == 'undefined') {
		nxautocompletebox.inputChanged = function(targetBoxId, inputValue) {
			if (typeof(nxautocompletebox.ajaxStack[targetBoxId]) != 'undefined')
				$clear(nxautocompletebox.ajaxStack[targetBoxId]);
			nxautocompletebox.ajaxStack[targetBoxId] = (function(){
				nxautocompletebox.xajaxwrapper(targetBoxId, inputValue);
				nxautocompletebox.highlightContents(targetBoxId, inputValue);
			}).delay(nxautocompletebox.ajaxDelay);
		};
	}
	
	
	
	
	if (typeof(nxautocompletebox.submit) == 'undefined') {
		nxautocompletebox.submit = function(targetBoxId) {
		};
	}
	
	
	
	
	if (typeof(nxautocompletebox.addEvent) == 'undefined') {
		nxautocompletebox.addEvent = function(eventType, callbackFunction) {
			if (typeof(nxautocompletebox.eventsList)=='undefined')
				nxautocompletebox.eventsList = {};
			if (typeof(nxautocompletebox.eventsList[eventType])=='undefined')
				nxautocompletebox.eventsList[eventType] = [];
			nxautocompletebox.eventsList[eventType].push(callbackFunction);
		};
	}
	
	
	
	if (typeof(nxautocompletebox.addOnBlurEvents) == 'undefined') {
		nxautocompletebox.addOnBlurEvents = function(targetBox, sourceInput) {
			var sourceInputId = sourceInput.getAttribute('id');

			var mouseOutTimer;

			var mouseOutFunction = function() {
				mouseOutTimer = (function() {
					nxautocompletebox.closeSuggestionBox(targetBox, sourceInput);
				}).delay(1000);
			};
			var mouseOverFunction = function() {
				$clear(mouseOutTimer);
			};

			$each([targetBox, sourceInput], function(element) {

				element.removeEvent('mouseout', mouseOutFunction);
				element.addEvent('mouseout', mouseOutFunction);

				element.removeEvent('mouseover', mouseOverFunction);
				element.addEvent('mouseover', mouseOverFunction);

			});

		};
	}
	
	
	
	
	if (typeof(nxautocompletebox.addEvents) == 'undefined') {
		nxautocompletebox.addEvents = function(){
			$each($$('span'), function(el, spanCounter){
				if (el.className.test(/^nxautocompletebox-input-.*$/)) {
					if (!el.hasClass('nxautocompletebox-input-processed')) {
						var className = el.className;
						el.addClass('nxautocompletebox-input-processed');
						$each(el.getElements('input', 'textarea'), function(input, inputCounter){
							
							
							var targetBoxId = className + "-" + spanCounter + "_" + inputCounter + "-";
							new Element("iframe", {
								"id": targetBoxId+"-iframe",
								"scrolling": "no",
								"frameborders": "no",
								"z-index": "0",
								"class": "nxautocompletebox nxautocompletebox-resultbox"
							}).injectInside(el).setStyle("display", "none");
							var targetBox = new Element("div", {
								"id": targetBoxId,
								"class": "nxautocompletebox nxautocompletebox-resultbox"
							});
							targetBox.injectInside(el).setStyle("display", "none");
							input.id = ("nxautocompletebox_input-" + targetBoxId + "-");
							input = $("nxautocompletebox_input-" + targetBoxId + "-");
							nxautocompletebox.submitEventStack[targetBoxId] = [];
							
							input.setAttribute('autocomplete', 'off');
							
							input.addEvent('focus', function(){
								nxautocompletebox.addOnBlurEvents(targetBox, input);
								nxautocompletebox.inputChanged(targetBoxId, input.value);
							});
							
							input.addEvent('keyup', function(key){
							
								switch (key.keyCode) {
								
									case 10:
									case 13:{
										nxautocompletebox.inputChanged(targetBoxId, input.value);
										nxautocompletebox.submit(targetBoxId);
										break;
									}
									
									case 40:{
										// down
										nxautocompletebox.moveCursor(targetBoxId, 'down');
										nxautocompletebox.drawHoverLinks(targetBoxId);
										break;
									}
									
									case 38:{
										// up
										nxautocompletebox.moveCursor(targetBoxId, 'up');
										nxautocompletebox.drawHoverLinks(targetBoxId);
										break;
									}
									
									default:
										{
											// other key
											nxautocompletebox.inputChanged(targetBoxId, input.value);
											break;
										}
										
								}
								
							});
							
							nxautocompletebox.highlightContents(targetBoxId, input.value);
							
						});
					}
				}
			});
		};
	}
	
	
	
	
	window.addEvent('domready', function() {
		nxautocompletebox.addEvents();
	});
	
})();
