function isInt(myNum) {
	// get the modulus: if it's 0, then it's an integer
	var myMod = myNum % 1;
	
	if (myMod == 0) {
	        return true;
	} else {
	        return false;
	}
}

var AutocompleteSelectAjax = new Class
(
	{
		initialize: function(elementId, options)
		{
			this.elementId = elementId;
			
			this.options = options;
			this.list = Array();
			this.listUnsorted = Array();
			this.childs = Array();
			this.currentSelectedElement = 0;
			this.visible = false;
			this.disabled = false;
			this.debug = false;
			this.mode = 'edit';
			this.limit = 40;
			this.limitCount = 0;
			
			/**
				Build the initial list
			*/
			this.first = true;			
			this.intIndexes = true;
			
			this.plugin = $(this.elementId).getProperty('plugin');
			
			if(this.plugin == null)
				return;
				
			if($(this.elementId).getProperty('debug') == 'true')
				this.debug = true;
				
			if($(this.elementId).getProperty('disabled') == true)
				this.disabled = true;
				
			if($(this.elementId).getProperty('mode') != null)
				this.mode = $(this.elementId).getProperty('mode');
			
			if(this.mode == 'edit')
			{
				
				this.searchInput = new Element('input');
				this.searchInput.setProperty('id', $(this.elementId).getProperty('id') + "_ajax"); 
				this.searchInput.setProperty('class', $(this.elementId).getProperty('class'));
				if(!this.disabled)
					this.searchInput.addClass('autoCompleteField');
				
				this.searchInput.addClass('text');
				this.searchInput.addClass('regular');
				if($(this.elementId).value != "0")
					this.searchInput.value = $(this.elementId).value;
				$(this.elementId).setProperty('type', 'hidden');
		
				if(!this.disabled)
				{
					this.searchInput.addListener('mousedown', this.handleFocus.bind(this));
				
					this.searchInput.addListener('click', this.stopEvent.bind(this));
					this.searchInput.addListener('keydown', this.handleSearch.bind(this));
					this.searchInput.addListener('keydown', this.disableEnter.bind(this));
				}
				else
				{
					this.searchInput.addClass('disabled');
					this.searchInput.setProperty('disabled', true);
				}
				this.searchResult = new Element('div');
	
				this.searchResult.addClass('searchResult');			
				if(!this.disabled)
					this.searchResult.addListener('click', this.stopEvent.bind(this));
			
				document.addListener('click', this.handleUnfocus.bind(this));
			
				this.searchInput.injectBefore($(this.elementId));
				this.searchResult.injectAfter(this.searchInput);
				this.searchValue = this.searchInput.value;
			}
			else
				this.searchValue = $(this.elementId).innerHTML;
			
			
			
			this.firstSearch = true;
			
			
			
			this.func = function() {
							if(this.searchValue != "" && this.searchValue != 0)
							{
								this.qsa = $(this.elementId).getProperty('arguments');
								if(this.qsa == null)
									this.qsa = '';
			
								var url = site_url + "server/reference_search/?plugin="+this.plugin+"&query=" + this.searchValue + this.qsa;

								new XHR({
									method: 'GET',
									onSuccess: this.loadXhr.bind(this)
								}).send(url, '');
							}
						}.bind(this);
			
			if(this.searchValue != "" && this.searchValue != 0)
				setTimeout(this.func, 0);
			else
				this.firstSearch = false;			
		},

		
		destroy: function(e)
		{
			if(!window.webkit)
			{
				if($defined(this.searchResult))
				{
					this.searchResult.removeEvents();
					this.searchResult.empty();
					this.searchResult = null;
				}
				
				if($defined(this.searchInput))
				{
					this.searchInput.empty();
					this.searchInput.removeEvents();
					this.searchInput = null;				
				}				
				
				this.childs.each(function (listItem, key) {
					this.childs[key] = null;
				}.bind(this) );		
				
				this.childs = null;
			}
		},		
		
		handleUnfocus: function(e)
		{
			this.visible = false;
			if($defined(this.searchResult))
				this.searchResult.setStyle('display', 'none');
		},
		
		handleFocus: function(e)
		{
			$$('.searchResult').each(function(element) { element.setStyle('display', 'none') } );
			this.searchInput.value = '';				
			if(this.first == true)
			{
				this.showList(null);		
				this.first = false;
				
			}	
			if(this.visible == false)
			{
				this.visible = true;
				this.searchResult.setStyle('display', 'block');
				//this.searchInput.selectRange(0,1000);
			}
			else
			{
				this.visible = false;
			}
		},
		
		showList: function(aList)
		{
			//clearTimeout(this.searchingnow);
			this.searchnow = false;
			
			this.childs = null;
			this.childs = Array();
			this.limitCount = 0;
			var first = null;
			
			if(this.mode == 'edit')
			{
				this.searchResult.empty();
				var keuzeElement = new SelectItem({'name' : 'Begin met typen om uw zoekresultaten te verfijnen.', 'key' : -1});
				keuzeElement.element.addClass('hulp');			
				this.searchResult.adopt(keuzeElement.element);	
			}
			
			if(aList != null)
			{
				aList.each(function (listItem, key) 
				{
					if(this.limitCount <= this.limit)
					{
						if(first === null)
							first = key;
						var name = listItem;
						if(name == '')
							name = '&nbsp;';
						
						var childItem = new SelectItem({'name' : name, 'key' : key});

						
						if(this.mode == 'edit')
						{
							// Select an item					
							childItem.element.addListener("click", function(e){
								$(this.elementId).value = key;
								$(this.elementId).fireEvent('onChange');
								this.searchInput.value = listItem;
								this.searchInput.fireEvent('onChange');
								this.handleUnfocus();
								this.searchInput.focus();
							}.bind(this));

							// Hover over element
							childItem.element.addListener("mouseover", function(e){
								childItem.element.removeClass("selectItem");
								childItem.element.addClass("selectItemHover");
								this.unfocusElement(this.currentSelectedElement);
								this.currentSelectedElement = key;
							}.bind(this));
					
							// Leave hover
							childItem.element.addListener("mouseleave", function(e){
								childItem.element.addClass("selectItem");
								childItem.element.removeClass("selectItemHover");
							}.bind(this));					
					
							this.searchResult.adopt(childItem.element);	
						}
						this.childs[key] = childItem;
						
						this.limitCount++;
					}
				
				}.bind(this) );
				
				if(this.mode == 'edit')
				{
					if(this.firstSearch)
					{
						this.searchInput.value = this.childs[first].options.name;
						this.firstSearch = false;
					}
					this.currentSelectedElement = first;
					$(this.elementId).value = first;
					$(this.elementId).fireEvent('onChange');
					this.focusElement(first);
				}
				else
				{
					$(this.elementId).setHTML(this.childs[first].options.name);
				}
				
			}
		},		

		focusElement: function(key)
		{
			if(!$defined(this.childs[key]) || !$defined(this.childs[key].element))
				return;
			
			this.childs[key].element.removeClass("selectItem");
			this.childs[key].element.addClass("selectItemHover");
		},

		unfocusElement: function(key)
		{
			if(!$defined(this.childs[key]))
				return;

			this.childs[key].element.addClass("selectItem");
			this.childs[key].element.removeClass("selectItemHover");
		},

		doNext: function()
		{
			previous = false;
			next = null;
			stop = false;
		
			this.childs.each(function (listItem, key) {
				if(!stop)
				{
					if(previous || this.currentSelectedElement == 0	)
					{
						next = key;
						previous = false;	
						stop = true;
					}
				
					if(key == this.currentSelectedElement)
						previous = true;
				
				}
			}.bind(this));
			
			if(next == null)
				return;

			this.unfocusElement(this.currentSelectedElement);
			this.focusElement(next);
			this.currentSelectedElement = next;
		},
		
		doPrevious: function()
		{
			prev = null;
			stop = false;
		
			this.childs.each(function (listItem, key) {
				if(!stop)
				{
					
					if(key == this.currentSelectedElement)
					{
						stop = true;
					}
					else
						prev = key;
				
				}
			}.bind(this));
			
			if(prev == null)
				return;

			this.unfocusElement(this.currentSelectedElement);
			this.focusElement(prev);
			this.currentSelectedElement = prev;
		},
		
		disableEnter: function(e)
		{
			if(e.key == 'enter')
				e = new Event(e).stop();
		},
		
		handleSearch: function(e)
		{
			e = new Event(e);
			
			searchValue = this.searchInput.getValue();

			if(e && e.key)
			{
				switch(e.key)
				{
					case 'left':
					case 'right':
					{
						break;
					}
					/*
						On tab and on enter the selection is accepted
					*/
					case 'enter':
					{
						e.stop();
					}
					case 'tab':
					{
						if(this.visible)
						{
							
							if(this.searchInput.value == "" && this.currentSelectedElement == 0)
							{
								this.doNext();
							}
							
							
							if($defined(this.childs[this.currentSelectedElement]))
							{
								$(this.elementId).setProperty('value', this.currentSelectedElement);
								this.searchInput.value = this.childs[this.currentSelectedElement].options.name;
								
								$(this.elementId).fireEvent('onChange');
								this.searchInput.fireEvent('onChange');
							}
						
						
							this.handleUnfocus();
							//e.stop();
						}
						// do nothing
						break;
					}
					case 'esc':
					{
						this.handleUnfocus();
					}
					case 'down':
					{
						// People tend to tab -> arrow down. This will make that work like expected
						if(!this.visible)
							this.handleFocus();
						this.doNext();
						break;				
					}
					case 'up':
					{
						this.doPrevious();
						break;
					}
					case 'backspace':
					{
						e.key = '';
						searchValue = searchValue.substr(0,searchValue.length-1);
					}
					default:
					{		
						if(!this.visible)
							this.handleFocus();

						if(searchValue == "" && this.currentSelectedElement == 0)
						{
							$(this.elementId).value = "";
							$(this.elementId).fireEvent('onChange');
						}						
					
						this.searchValue = searchValue + e.key;
						if(this.searchingnow)
						{
							clearTimeout(this.searchingnow);
							this.searchnow = false;
						}
						this.searchingnow = setTimeout(this.func, 300);
						break;
					}
				}
			}

		},
		
		


		
		loadXhr: function(text, xml) 
		{
			
			data = this.readXml(xml);
			this.showList(data);
		},
		
		readXml: function(xml)
		{
			n = xml.documentElement.childNodes;
			results = Array();
			for (var i=0; i<n.length; i++) if (n[i].tagName == 'node') {
				var opt = {data:{}};
				var a = n[i].attributes;
				var id = null;
				var label = '';
				for (var t=0; t<a.length; t++) {
					switch (a[t].name) {
						case 'id':
							id = a[t].value;
							break;
						case 'name':
							label = a[t].value;
							break;
						default:
							opt.data[a[t].name] = a[t].value;
					}
				}
		
				if(id != null && label != '')
				{
					results[id] = label;
				}
			}
			return results;	
		},
		
		stopEvent: function(e)
		{
			e = new Event(e).stop();
		}
	}
);

window.addEvent('load', function() {
	$$('.autoComplete').each(function(element)
	{
		if(element.id == null || element.id == '')
			element.id = 'autocompleteAjax' + AutoCompleteCountAjax;
		
		element.id = 'autocomplete' + AutoCompleteCount;
		AutoCompletes[AutoCompleteCount] = new AutocompleteSelect(element.id,null);
		AutoCompleteCount++;
	}
	);
});
