
/**
 * Retrofitted attribution from distribution sites:
 * Copyright (C) Dylan Verheul
 * Licensed like jQuery, see http://docs.jquery.com/License.
 */

$.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");;

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	// Set default values for results
	var pos = findPos(input);
	$results.hide().addClass(options.resultsClass).css({
		position: "absolute",
		top: (pos.y + input.offsetHeight + 4) + "px",
		left: pos.x + "px"
	});	
	// Add to body element	
	$("body").append(results);
	
	// determine other result set viewer		
	var $searchsuggestcontent = null;	
	
	var searchsuggestcontent = null;	
	var searchsuggestcontenttable = null;	
	// different behaviour for ApplicationFinder
	if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
	{
		if(options.viewResultInTable) {
			$searchsuggestcontent = $('#searchsuggestcontent');
			$searchsuggestcontent.hide().css({
				visibility:"hidden", 
				"z-index":0,
				"display":"none",
				position: "absolute",
				// FF top: (pos.y + input.offsetHeight -88) + "px",
				top: (pos.y + input.offsetHeight -37) + "px",
				left: pos.x-202 + "px"
			});	
			searchsuggestcontent = document.getElementById("searchsuggestcontent");
			searchsuggestcontent.className="searchsuggestbox";
			searchsuggestcontenttable = document.getElementById("searchsuggestcontenttable");
		}
	
	}// ApplicationFinder
	else
	{
	if(options.viewResultInTable) {
			$searchsuggestcontent = $('#searchsuggestcontentApplicationFinder');
			$searchsuggestcontent.hide().css({
				visibility:"hidden", 
				"z-index":0,
				"display":"none",
				position: "absolute",
				top: (pos.y + input.offsetHeight +2) + "px",
				left: pos.x-0 + "px"
			});	
			searchsuggestcontent = document.getElementById("searchsuggestcontentApplicationFinder");
			searchsuggestcontent.className="searchsuggestbox";
			searchsuggestcontenttable = document.getElementById("searchsuggestcontenttableApplicationFinder");
		}
	}
			
	input.autocompleter = me;
	input.lastSelected = $input.val();
	input.href = "";

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
    var emptyQ = null; // Last query that got empty results.
    var pending = null; // Currently pending query.

	$input
	.keydown(function(e) {
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if (selectCurrent()) {
					e.preventDefault();
				}
                if (timeout) {
                    clearTimeout(timeout);
                }
				if(input.lastSelected != null && input.lastSelected != "") {
					if(options.viewResultInTable && input.href != "") {
						log("a.hover.enter: HREF="+ input.href); 
						document.location.href = input.href;
					} else {
						log("li.hover.enter:"+ e); 
						document.forms[0].submit();
					}
				}
				break;
			default:
				active = -1;
				if (timeout) 
					clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	})
	.blur(function(e) {
		hideResults(e);
	});
	
	hideResultsNow();

	function onChange() {
		var v = $input.val();
		if (v == prev) return;
        prev = v;
        if (emptyQ && v.indexOf(emptyQ) == 0) {
            // A prefix of v already found no results, so v won't find any.
            hideResultsNow();
            return;
        }
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			if(options.viewResultInTable) {
				$searchsuggestcontent.hide().css({visibility:"hidden", "z-index":0, "display":"none" });
				$('#ContactForm_Title').css({visibility:"visible"});
				// to view select box in application finder
				if (isNaN(document.getElementById("filter_documenttype"))) {
					document.getElementById("filter_documenttype").style.visibility = "visible";
				} 
			} else {
				$results.hide();
			}
		}
	};

 	function moveSelect(step) {
		var lis = null; 
		if(options.viewResultInTable) {
			lis = $("a", searchsuggestcontenttable);
		} else {
			lis = $("li", results);
		}
		
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("over");

		$(lis[active]).addClass("over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = null;
		if(options.viewResultInTable) {
			li = $("a.over", searchsuggestcontenttable)[0];
			if (!li) {
				var $li = $("a.over", searchsuggestcontenttable);
				if (options.selectOnly) {
					if ($li.length == 1) li = $li[0];
				} else if (options.selectFirst) {
					li = $li[0];
				}
			}
		} else {
			li = $("li.over", results)[0];
			if (!li) {
				var $li = $("li", results);
				if (options.selectOnly) {
					if ($li.length == 1) li = $li[0];
				} else if (options.selectFirst) {
					li = $li[0];
				}
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {		
		if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
		{
			var v =  "";		
			if(options.viewResultInTable) {
				if (!li) {
				
					li = document.createElement("a");
					li.extra = [];
					li.selectValue = "";
					li.href = "";
				}
				// member target URL of search hit
				input.href = li.getAttribute('href');
			} else {
				if (!li) {
					li = document.createElement("li");
					li.extra = [];
					li.selectValue = "";
				}
			}
			
			v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
			// remove HTML tags from input
			v = v.replace(/\<.*?\>/g,'');
			// remove special character definition from input
			v = v.replace(/\&.*?\;/g,'');
			input.lastSelected = v;
			prev = v;
			// reset to empty
			if(options.viewResultInTable) {
				// clear table caption
				var caption=null;
				if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
				{
					caption = $('#searchsuggestcontenttable caption')[0];
				}//Appfinder
				else
				{
					caption = $('#searchsuggestcontenttableApplicationFinder caption')[0];
				}
				if( caption != null ) {				
					caption.innerHTML = caption.innerHTML.replace(/(.*:).*/, "$1");
				}
				// clear table content
				var tbody=null;
				if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
				{
					tbody = $("#searchsuggestcontenttable tbody")[0];
				}//Appfinder
				else
				{
					tbody = $("#searchsuggestcontenttableApplicationFinder tbody")[0];
				}			
				while (tbody != null && tbody.childNodes.length > 0) {
					tbody.removeChild(tbody.childNodes[0]);
				}
			} else {
				$results.html("");
			}		
			$input.val(v);		
			hideResultsNow();
			if (options.onItemSelect) 
				setTimeout(function() { options.onItemSelect(li) }, 1);
		}//appfinder
		else
		{
			if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
			}
			var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
			input.lastSelected = v;
			prev = v;
			$results.html("");
			$input.val(v);
			hideResultsNow();
			if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
				
		}		
	};

	function hideResults(e) {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
		if(options.viewResultInTable) {
			if ($searchsuggestcontent.is(":visible")) {
				$searchsuggestcontent.hide().css({visibility:"hidden", "z-index":0, "display":"none" });
				// to show select box in application finder
				if (isNaN(document.getElementById("filter_documenttype"))) {
					document.getElementById("filter_documenttype").style.visibility = "visible";
				} 
			}	
		} else {
			if ($results.is(":visible")) {
				$results.hide();
			}
		}
		$('#ContactForm_Title').css({visibility:"visible"});
	};
	
	function receiveData(q, data) {
        pending = null;
		if ( q != null ) {
			var caption=null;
			if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
			{
				caption = $('#searchsuggestcontenttable caption')[0];
			}//Appfinder
			else
			{
				caption = $('#searchsuggestcontenttableApplicationFinder caption')[0];
			}			
			if( caption != null ) {
				caption.innerHTML = caption.innerHTML.replace(/(.*:).*/i, "$1 " + q);
			}
		}
		if (null != data && data.length > 0) {
			$input.removeClass(options.loadingClass);
			var ifrm = null;	
			if(options.viewResultInTable) {
				var tableContent = dataToDom(data);
				searchsuggestcontent.appendChild(tableContent);
				for (var i in options.extraParams) {
					if (options.extraParams[i] == "aaf_substance") {
						$searchsuggestcontent.hide().css({
						top: (pos.y + input.offsetHeight +2) + "px"
						});
					}
					if (options.extraParams[i] == "aaf_sample") {
						$searchsuggestcontent.hide().css({
						top: (pos.y + input.offsetHeight +2) + "px"
						});
					}
				}
				// to hide select box in application finder
				if (isNaN(document.getElementById("filter_documenttype"))) {
					document.getElementById("filter_documenttype").style.visibility = "hidden";
				} 
				$searchsuggestcontent.show().css({visibility:"visible", "z-index":101, "display":"block" });
				$('#ContactForm_Title').css({visibility:"hidden"});
			} else {
				results.innerHTML = "";
				if ($.browser.msie) {
					// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
					ifrm = document.createElement('iframe');				
					ifrm.style.height = (input.offsetHeight * data.length) +"px";
					$results.append(ifrm);
				}
				results.appendChild(dataToDom(data));
				$results.show();
			}
		} else {
            emptyQ = q;
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data || data.length == 0) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if ( row != null && row != "" ) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		
			if(options.viewResultInTable) {
				// reset table content
				var tbody = null;
				if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
				{
					tbody =$("#searchsuggestcontenttable tbody")[0];
				}
				else
				{//ApplicationFinder
					tbody =$("#searchsuggestcontenttableApplicationFinder tbody")[0];
				}					
				while (tbody != null && tbody.childNodes.length > 0) {
					tbody.removeChild(tbody.childNodes[0]);
				}
				var adiv = null;
				if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
				{
					adiv = $("#searchsuggestcontent");
				}
				else
				{//ApplicationFinder
					adiv = $("#searchsuggestcontentApplicationFinder");
				}	
				//adiv.css('overflow', 'hidden');		
				// suggest line
				var hr = document.createElement("hr");
				hr.setAttribute('id', 'searchsuggestline');
				var f_td = document.createElement("td");
				f_td.appendChild(hr);
				var f_tr = document.createElement("tr");
				f_tr.appendChild(f_td);			
				tbody.appendChild(f_tr);	
				// suggest content
				for (var i=0; i < data.length; i++) {	
					var a=null;
					if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
					{				
						a = document.createElement("a");
					}
					else
					{	
						a = document.createElement("span");//it shouldn't be a link						
					}
					if (options.formatItem) {
						a.innerHTML = options.formatItem(data[i], i, data.length);
						a.selectValue = data[i][1];
					} else {
						a.innerHTML = data[i][1];
					}
					if( options.anchorUrl != null && data[i][0] != null ) {
						a.setAttribute('href', options.anchorUrl + data[i][0]);
					}
					var td = document.createElement("td");
		//			td.setAttribute('style', 'white-space:pre');
					td.setAttribute('style', 'white-space:nowrap');
					var nobreak = document.createElement("nobr");
					td.appendChild(nobreak);
					
					var ifrm = null;
					if ($.browser.msie) {
						// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
						ifrm = document.createElement('iframe');
						/*
						ifrm.appendChild(a);
						td.appendChild(ifrm);
						*/
		//				td.appendChild(a);
						nobreak.appendChild(a);
					}
					else {
		//				td.appendChild(a);				
						nobreak.appendChild(a);
					}
						var tr = document.createElement("tr");
						tr.appendChild(td);
						tbody.appendChild(tr);
						if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
						{
							$(a).hover(
								function() { $("a", td).removeClass("over"); $(this).addClass("over"); },
								function() { $(this).removeClass("over"); }
							).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this); log("a.hover.click:HREF="+ this.getAttribute('href')); document.location.href = this.getAttribute('href'); });
						}
						else
						{	//appfinder just fill the field, nothing else
							$(a).hover(
								function() { $("a", td).removeClass("over"); $(this).addClass("over"); },
								function() { $(this).removeClass("over"); }
							).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this); log("a.hover.click:HREF="+ this.getAttribute('href')); });
						}
					}
					return searchsuggestcontenttable;
			}
			else {
				var ul = document.createElement("ul");		
				var num = data.length;
				for (var i=0; i < num; i++) {
					
					var row = data[i];
					if (!row || row.length == 0 || row == "") continue;			
					var li = document.createElement("li");
					if (options.formatItem) {
						li.innerHTML = options.formatItem(row, i, num);
						li.selectValue = row[0];
					} else {
						li.innerHTML = row[0];
					}			
					var extra = null;
					if (row.length > 1) {
						extra = [];
						for (var j=1; j < row.length; j++) {
							extra[extra.length] = row[j];
						}
					}
					li.extra = extra;
					ul.appendChild(li);
					$(li).hover(
						function() { $("li", ul).removeClass("over"); $(this).addClass("over"); },
						function() { $(this).removeClass("over"); }
					).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this); log("li.hover.click:"+ e); document.forms[0].submit(); });
				}
				return ul;
			}
		
		};

	/**
	@param q the query term
	*/
	function requestData(q) {
		// log("func requestData: args[0]=" +q );
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;		
		if (null != data && data.lenght > 0 ) {
			// log("func requestData: load cache data=" +data );
			receiveData(q, data);
		} else {
    	    if (pending) {
                pending.abort();
            }
			pending = $.get(makeUrl(q), function(data) {
				data = parseData(data);
				// log("func requestData parseData data=" +data );
				addToCache(q, data);				
				receiveData(q, data);
				// log("func requestData receive data=" +data );
			});			
		}
	};

	/**
	the url of suggest request
	@param q the query term
	*/
	function makeUrl(q) {
		if(q.charAt(q.length-1) != '*')
		{
			q=q+'*';
		}		
		if (options.url.indexOf('ViewApplicationFinder-GetSuggestions')==-1)
		{
			var url = options.url + "?WFSimpleSearch_NameOrID=" + encodeURIComponent(q);
		}
		else
		{
			var url = options.url
                + "?suggestSearchValue=" + encodeURIComponent(q)
			    + "&method=" + encodeURIComponent(getApplicationFinderMethod());
		}
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURIComponent(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache[q]) return cache[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		cache = {};
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	function addToCache(q, data) {
		if (!data || data.length == 0 || !q || !options.cacheLength || options.cacheLength == 0) return;
		if (!cache.length || cache.length > options.cacheLength) {
			cache = {};
			cache.length = 1; // we know we're adding something
		} else if (!cache[q]) {
			cache.length++;
		}
		cache[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
	
		
	/* debuging utils */
	function benchmark(s,d) {
		log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
	}
	
	this.benchmark = benchmark;
			
	function log(s) {
		if(options.debug == true) {
			if (typeof console != "undefined" && typeof console.debug != "undefined") {
				console.log(s);
			} else {
				alert(s);
			}
		}
	}
}

$.fn.autocomplete = function(url, options) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|\n";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 0;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.debug = options.debug || false;
	options.viewResultInTable = options.viewResultInTable || false;
	options.anchorUrl = options.anchorUrl || "";

	this.each(function() {
		var input = this;
		new $.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}