/**
 * @author Kenneth.priisholm
 */
var NN;
if(NN == null || typeof NN == "undefined"){
	NN = {};
}

NN.Suggest = function(props){
	var _this;
	var _inputContainer;
	var _xhr;
	this.input;
	this.suggestContainer;
	this.requestURL;
	this.requestMethod;
	this.searchParam;
	this.interval;
	this.timerHandle;
	if(props){
	    this.init(props);
	}
	this.cachedSearchString;
}
NN.Suggest.prototype = {
	init : function(props){
		this.id = props.input.id;
		this.input = document.getElementById(this.id);
		if(!this.input){
		    return false;
		}
		this.cachedSearchString = "";
		_inputContainer = this.input.parentNode;
//		_inputContainer.style.position = "relative";
		this.suggestContainer = document.createElement("div");
		this.suggestContainer.id = props.suggestContainer.id || "sc_" + props.input.id;
		this.interval = props.interval;
		if (props.suggestContainer.className){
			this.suggestContainer.className = props.suggestContainer.className;
		}
		if(props.suggestContainer.style){
			for(x in props.suggestContainer.style){
				this.suggestContainer.style[x] = props.suggestContainer.style[x];
			}
		}
		if(!props.suggestContainer.style.width){
			var sWidth = this.input.offsetWidth + "px";
			this.suggestContainer.style.width = sWidth;
		}
		if(!props.suggestContainer.style.left && !props.suggestContainer.style.right){
			var sLeft = this.input.offsetLeft + "px";
			this.suggestContainer.style.left = sLeft;
		}
		this.suggestContainer.style.display = "none";
		_inputContainer.appendChild(this.suggestContainer);
		
		this.requestURL = props.request ? props.request.url : null;
		this.requestMethod = props.request && props.request.method ? props.request.method : "GET";
		this.searchParam = props.request && props.request.searchParam ? props.request.searchParam : "search";
		if(!this.requestURL){
			alert("no URL for service provided!");
		}
		this.terms = [];
		this.termsIndex = 0;
		if(props.showSuggest){
			this.showSuggest = props.showSuggest;
		}	        
		_xhr = AjaxUtils.xmlHttpRequest();
		VEvent.addListener(this.input, "keyup", this.textChanged, this);
		return true;
	},
	textChanged : function(e, c){
		e = e || window.event;
		var keyCode = e.which || e.keyCode;
		var tmpString = c.input.value.trim();
		var wrapper;
		
		switch(keyCode){
			case 38: //arrow up
				if(tmpString != ""){
					c.findNext(-1);
				}
 				break;
 			case 40: //arrow down
 				if(tmpString != ""){
					c.findNext(1);
				}
				break;
 			default:
 				if(tmpString != c.cachedSearchString && (keyCode > 47 && keyCode < 223 || keyCode == 8 || keyCode == 32)){
					c.cachedSearchString = tmpString;
					if(c.timerHandle){
						window.clearTimeout(c.timerHandle);
					}
					wrapper = function(){
						c.get(tmpString, c);
					};
					c.timerHandle = window.setTimeout(wrapper, c.interval);
				}
 				break;
 		}
	},
	findNext : function(step){
		var tEnd;
		if(!this.terms || this.terms.length < 1){
			return false;
		}
		if(this.termsIndex === null){
			this.termsIndex = 0;
		}
		else {
			this.terms[this.termsIndex].className = "term";
			tEnd = this.terms.length - 1;
			this.termsIndex += step;
			this.termsIndex = this.termsIndex > tEnd ? 0 : this.termsIndex < 0 ? tEnd : this.termsIndex;
		}
		this.terms[this.termsIndex].className = "term focused";
		this.input.value = this.terms[this.termsIndex].title;
		this.cachedSearchString = this.input.value;
 	},
 	toggleVisible : function(e, c){
		if(c.suggestContainer.innerHTML != ""){
			c.suggestContainer.style.display = c.suggestContainer.style.display == "" ? "block" : "";
		}
		else {
			c.suggestContainer.style.display = "";
		}
 	},
	get : function(searchString, c){
		if(_xhr.readyState != 0 && _xhr.readyState != 4){ // if a request is active, abort it
			_xhr.abort();
		}
		if(searchString.length > 0){
			var url = AjaxUtils.addURLParam(c.requestURL, c.searchParam, searchString);
			_xhr.onreadystatechange = function(){
				if(_xhr.readyState == 4){
					if(_xhr.status == 200){
						c.input.setAttribute("tabIndex", "1");
						c.suggestContainer.innerHTML = "";
						c.terms = [];
						c.termsIndex = null;						
						var terms = _xhr.responseXML.documentElement.getElementsByTagName("term");						
						for(var i = 0, l = terms.length; i < l; i++){
							var term = terms[i].firstChild.nodeValue;
							var re = new RegExp("("+ c.input.value +")");
							var termX = term.replace(re, "<span class=\"match\">$1</span>");
							var count = terms[i].getAttribute("count");
							var itemA = document.createElement("a");
							itemA.href = "javascript://";
							itemA.className = "term";
							itemA.setAttribute("tabIndex", (2 + i).toString());
							itemA.setAttribute("title", term);
							var countSpan = document.createElement("span");
							countSpan.className = "counter";
							//itemA.appendChild(document.createTextNode(term));
							itemA.innerHTML = termX;
							countSpan.appendChild(document.createTextNode(count));
							itemA.appendChild(countSpan);
							VEvent.addListener(itemA, "click", parse, c);
							c.suggestContainer.appendChild(itemA);
							c.terms.push(itemA);
						}				
						                        						
						var ie7div = document.createElement("div");
						ie7div.id = "ie6frame";                        
						var ie7iframe = document.createElement("iframe");
						ie7div.appendChild(ie7iframe);	
																	
                        c.suggestContainer.appendChild(ie7div);                        
						c.suggestContainer.style.display = c.suggestContainer.innerHTML == "" ? "none" : "block";
					}
					else {
					    // NO - No alert on the live site  - BHLL
						//alert(_xhr.status + ": " + _xhr.statusText);
					}
				}
				function parse(e, c){
					e = e || window.event;
					var target = DOMUtils.findTarget(e);
					c.transfer(target.title);
				}
			};
			
			
			_xhr.open(c.requestMethod, url, true);
			_xhr.send(null);
		}
		else {
			c.suggestContainer.innerHTML = "";
			c.suggestContainer.style.display = "none";
		}
	},
	showSuggest : function(){
		var that = this;
		var parse = function (e) {
			e = e || window.event;
			var target = DOMUtils.findTarget(e);
			that.transfer(target.title);
		};
		if(_xhr.readyState == 4){
			if(_xhr.status == 200){
				this.input.setAttribute("tabIndex", "1");
				this.suggestContainer.innerHTML = "";
				var terms = _xhr.responseXML.documentElement.getElementsByTagName("term");
				for(var i = 0, l = terms.length; i < l; i++){
					var term = terms[i].firstChild.nodeValue;
					var re = new RegExp("("+ this.input.value +")");
					var termX = term.replace(re, "<span class=\"match\">$1</span>");
					var count = terms[i].getAttribute("count");
					var itemA = document.createElement("a");
					itemA.href = "javascript://";
					itemA.className = "term";
					itemA.setAttribute("tabIndex", (2 + i).toString());
					itemA.setAttribute("title", term);
					var countSpan = document.createElement("span");
					countSpan.className = "counter";
					//itemA.appendChild(document.createTextNode(term));
					itemA.innerHTML = termX;
					countSpan.appendChild(document.createTextNode(count));
					itemA.appendChild(countSpan);
					VEvent.addListener(itemA, "click", parse);
					this.suggestContainer.appendChild(itemA);
				}
										                        						
				var ie7div = document.createElement("div");
				ie7div.id = "ie6frame";                        
				var ie7iframe = document.createElement("iframe");
				ie7div.appendChild(ie7iframe);	
															
                c.suggestContainer.appendChild(ie7div);				
				this.suggestContainer.style.display = "block";
			}
			else {
			    // NO - No alert on the live site  - BHLL
				//alert(_xhr.status + ": " + _xhr.statusText);
			}
		}
	},
	transfer : function(suggestion){
		this.input.value = suggestion;
		this.cachedSearchString = suggestion;
		this.suggestContainer.style.display ="none";
	}
}
