/*
    ABOUT:
    =======================================
    
    Yet Another Autocomplete Script (YAACS)
    Written by Bill Lindmeier for Ma.gnolia
    Copyright (c) 2006, Gnolia Inc.
    Email bill@ma.gnolia.com for questions or suggestions 

    INSTRUCTIONS FOR USE:
    =======================================
    
    1) This class assumes the presence of the Prototype JS library
    To download, or for more information, visit http://prototype.conio.net/
    
    2) Insert this tag into your page UNDER the input field and suggestion node:
    
        new Autocomplete('tag_input', 'tag_suggestions', tags);
    
    Where 'tag_input' is the id of your input field, and 'tag_suggestions' is the
    element which displays tag suggestions (usually the div under text input field).
    The last parameter `tags` is an array of tags (strings) to be used for lookup. 
    
    Here are some suggested styles for autocomplete:
    
    <style>
        #tag_suggestions, #tag_input{
    		width: 400px;
    	}
    	#tag_suggestions{
    		background-color: #eeeeff;
    		position: absolute;
    		z-index: 9999999;
    		overflow: auto;
    		max-height: 200px;    
    	}
    	* html #tag_suggestions{
    		background-color: transparent;
    		height: 200px;    
    	}
    	#tag_suggestions a{
    		text-decoration:none;
    		color: #000;
    		display: block;
    		padding: .2em .5em;
    	}
    	* html #tag_suggestions a{
    		background-color: #eeeeff;
    	}
    	#tag_suggestions a.selected, #tag_suggestions a:hover{
    		background-color: #ffff00;
    	}
    </style>
    
    If the autocomplete is being instantiated more than once on the same
    page, the selectors above should be changed to class names, rather 
    than id names.


    LICENSE AND STUFF
    =======================================
    
    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:
    
    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    
*/

var Autocomplete = Class.create();
Autocomplete.prototype = {
	initialize:function(textfieldId, suggestField, tags){
		this.active = false;
		this.keepActive = false;
		this.textfield = $(textfieldId);
		this.textfield.onfocus = function(){
		    this.keepActive = false;
		    this.active = true;
		}.bind(this);
		this.textfield.onblur = function(){
		    if(!this.keepActive){
    		    this.suggestionField.innerHTML = '';
    		    this.active = false;		        
		    }
		}.bind(this);
		this.textfield.setAttribute('autocomplete', 'off');
		this.suggestionField = $(suggestField);
		this.suggestionField.onmousedown = function(){
		    this.keepActive = true;
		}.bind(this);
		this.listIndex = -1;
		this.mytags = tags;
		this.suggestions = [];
		new Form.Element.Observer(textfieldId, 0.1, function(element, value){this.getSuggestions(value)}.bind(this));
		// Ugly hack to use onkeypress for Firefox
		if(navigator.userAgent.toLowerCase().indexOf('msie') != -1 || navigator.userAgent.toLowerCase().indexOf('safari') != -1){
			$(textfieldId).onkeydown = function(event){this.tagSelection(event);return this.selectKeys(event);}.bind(this);
		}else{
			$(textfieldId).onkeypress = function(event){this.tagSelection(event);return this.selectKeys(event);}.bind(this);
		}	
	},
	selectKeys:function(event){
	    if(!event){
			event=window.event;
		}
		if((event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40 || event.keyCode == 13 || event.keyCode == 9) && this.listIndex > -1){
			return false;
		}else{
			return true;
		}
	},
	selectionSuggestion:function(num){	
		if(this.suggestions[this.listIndex]){
			Element.removeClassName(this.suggestionField.childNodes[this.listIndex], "selected");
		}
		if(this.suggestions[num]){
			Element.addClassName(this.suggestionField.childNodes[num], "selected");
			this.listIndex = num;		
		}else{
			this.listIndex = -1;
		}
	},
	tagSelection:function(event){
		if(!event){
			event=window.event;
		}
		if(event.keyCode==38){//up
			this.selectionSuggestion(this.listIndex-1);
		}else if(event.keyCode==40){//down
			if(this.listIndex < this.suggestions.length-1){
				this.selectionSuggestion(this.listIndex+1);
			}
		}else if((event.keyCode==13 || event.keyCode==9 || event.keyCode==39) && this.listIndex > -1){
			if(this.suggestions[this.listIndex]){
				this.appendTag(this.suggestions[this.listIndex]);			
			}
			this.textfield.focus();
		}
	},
	selectText:function(begin, end) {
	    if (this.textfield.setSelectionRange) {
	        this.textfield.setSelectionRange(begin,end);
	    }
	    else if (this.textfield.createTextRange) {
	        var textrange = this.textfield.createTextRange();
	        textrange.moveStart("character", begin);
	        textrange.moveEnd("character", end-this.textfield.value.length);
	        textrange.select();
	    }
	    else {
	        this.textfield.select();
	    }
		this.textfield.focus();
	},
	appendTag:function(tag){
		var partial = this.textfield.value.match(/[^,]*$/)[0].replace(/^\s+/, '');
		var partialRE = new RegExp(partial+"$", "i");
		input = this.textfield.value;
		newValue = input.replace(partialRE, tag+"");
		this.textfield.value = newValue;
		this.selectText(newValue.length, newValue.length);
		listIndex = -1;
	},
	getSuggestions:function(input){
	    if(this.active){
    		if(!input.match(/^\s+$/)){
    			var partial = input.match(/[^,]*$/)[0].replace(/^\s+/, '');
    			var partialRE = new RegExp("^"+partial, "i")
    			this.suggestions = [];
    			if(partial != ''){
    				this.suggestionField.innerHTML = "";
    				this.mytags.each(function(tag, index){
    					if(tag.match(partialRE)){
    						var tagMatch = document.createElement('a');
    						tagMatch.href="search.php?xSearch=" + tag;
    						tagMatch.onclick = function(){this.appendTag(tag)}.bind(this);
    						tagMatch.innerHTML = tag;
    						this.suggestionField.appendChild(tagMatch);
    						this.suggestions.push(tag);
    					}
    				}.bind(this));
    			}else{
    				this.suggestionField.innerHTML = '';
    			}
    		}else{
    			this.suggestionField.innerHTML = '';
    		}
    		this.listIndex = -1;
    	}
	}
};