if (typeof Function.prototype.bind == "undefined"){
	Function.prototype.bind = function() {
		var __method = this, args, object = arguments[0];
		return function() { return __method.apply(object, arguments); }
	}
}
if (typeof String.prototype.trim == "undefined"){
	String.prototype.trim = function(chr) {
		if (chr){
			chr = chr.replace(' ','');
			chr = chr.replace(/(.)/g,'\\\$1');
			chr = '['+chr+']';
		}else chr = '\\\s';
		var reg = new RegExp('^'+chr+'+|'+chr+'+$','g');
		return this.replace(reg,'');
	}
}

var Autocomplete = {
	//settings
	verbose : false,											//(true|false) warnings on/off
	autocomplete_rel_value : "autocomplete",								//(string) rel value for parsing inputs
	search_break_char : " ",										//(char) explode char
	AutocompleteReplaceOnLoad : false,									//(true|false) repalce all inputs with rel=#autocomplete_rel_value# on page load

	//properties for replaceInputs()
	AutocompleteDefaultAnswerText : "(Nici un raspuns)",							//(string) default answer
	AutocompleteAutoSearch : true,      									//(true|false) make auto request if no action for #AutocompleteAutoSearchTimeout# seconds
	AutocompleteAutoSearchTimeout : 3,      								//(int) seconds
	AutocompleteFollowLinkOnEnter : false,      								//(true|false) redirect to link on enter
	AutocompleteDefaultLink : 'jucarii/?search=$1',										//(string) default link in case of no result
	AutocompleteRequestFile : 'lib/get_auto_search.php',
	//AutocompleteDefaultText : 'Adauga acesta intrebare!',							//(string) default text in case of no result
	AutocompleteAjaxRequest : 1,

	//private vars
        ajax : new sack(),
        can_put_autocomplete : Object.prototype != undefined,
        maxAutocompletes : 1000,
        paramNames : ["AutocompleteDefaultAnswerText", "AutocompleteAutoSearch", "AutocompleteAutoSearchTimeout", "AutocompleteFollowLinkOnEnter", "AutocompleteDefaultLink", "AutocompleteDefaultText", "AutocompleteAjaxRequest","AutocompleteRequestFile", "AutocompleteIE6Hover"],

        replaceInputs : function(){
		var targetInputs = new Array();
		var inputs = document.getElementsByTagName("input");
		var rel = '';
		for (var i=0; i<inputs.length; i++){
                	rel = inputs[i].getAttribute("rel");
                	if (rel != null){
				if (rel.toString().toLowerCase() == Autocomplete.autocomplete_rel_value){
					targetInputs.push(inputs[i]);
				}
			}
		}
		for (var i=0; i<targetInputs.length; i++){
			Autocomplete.replaceInput(targetInputs[i], {
				AutocompleteDefaultAnswerText 	: Autocomplete.AutocompleteDefaultAnswerText,
				AutocompleteAutoSearch		: Autocomplete.AutocompleteAutoSearch,
				AutocompleteAutoSearchTimeout 	: Autocomplete.AutocompleteAutoSearchTimeout,
				AutocompleteFollowLinkOnEnter 	: Autocomplete.AutocompleteFollowLinkOnEnter,
				AutocompleteDefaultLink 	: Autocomplete.AutocompleteDefaultLink,
				AutocompleteDefaultText 	: Autocomplete.AutocompleteDefaultText,
				AutocompleteIE6Hover 		: Autocomplete.AutocompleteIE6Hover
			});
		}
	},
	replaceInput : function(el, params){
		if (!Autocomplete.can_put_autocomplete){
			return;
		}
		var a;
		if (typeof el == "string" && el != ''){
			if (a = document.getElementById(el)){
				el = a;
			}else{
				el = null;
			}
		}else if (typeof el != "object"){
                        el = null;
		}
		if (el != null){
			var inputWidth = parseInt(whi.getElementWidth(el)) || 0;
			var inputHeight = parseInt(whi.getElementHeight(el)) || 0;
			var elementFocusedBefore = !!(el.focused);

			var autoInput;
			autoInput = document.createElement("div");

			autoInput.style.zIndex = this.maxAutocompletes--;

			autoInput.className = "autocomplete_container";
			autoInput.showResults = Autocomplete.showResults.bind(autoInput);
			autoInput.hideResults = Autocomplete.hideResults.bind(autoInput);
			autoInput.putSearchTerm = Autocomplete.putSearchTerm.bind(autoInput);
			autoInput.getSelectKeys = Autocomplete.getSelectKeys.bind(autoInput);
			autoInput.getSearchResults = Autocomplete.getSearchResults.bind(autoInput);
			//autoInput.highlightSearch = Autocomplete.highlightSearch.bind(autoInput);
			//autoInput.addHightlightElement = Autocomplete.addHightlightElement.bind(autoInput);
			//autoInput.putHightlight = Autocomplete.putHightlight.bind(autoInput);
			autoInput.selectResult = Autocomplete.selectResult.bind(autoInput);
			autoInput.clearSelectedResult = Autocomplete.clearSelectedResult.bind(autoInput);
			autoInput.startAutoTimer = Autocomplete.startAutoTimer.bind(autoInput);
			autoInput.clearAutoTimer = Autocomplete.clearAutoTimer.bind(autoInput);
			autoInput.putAutoSearch = Autocomplete.putAutoSearch.bind(autoInput);
			autoInput.calcLink = Autocomplete.calcLink.bind(autoInput);

                        autoInput.searchResults = [];
                        autoInput.hightlightElements = new Array();
			autoInput.selectedResult = -1;
			autoInput.nrResults = 0;
			autoInput.resultsShowem = false;
			autoInput.autoTimeout = -1;
			autoInput.inputFontSize = 0;
			autoInput.searchTerm = '';
			autoInput.lastSearchedValue = '';
			autoInput.IEFlicker = whi.browser.IE;
			autoInput.keepMoving = true;
			autoInput.lastKeyNormal = false;
			autoInput.justAfterInit = true;

			var crdom = window.location.href.replace(/^http\:\/\//,"");
			crdom = crdom.split("/");
			autoInput.crDomain = "http://"+crdom[0];

			for (var k=0; k<Autocomplete.paramNames.length; k++){
				autoInput[Autocomplete.paramNames[k]] = typeof params[Autocomplete.paramNames[k]] == "undefined" ? Autocomplete[Autocomplete.paramNames[k]] : params[Autocomplete.paramNames[k]];
			}
			
			if (autoInput.AutocompleteIE6Hover != '' && whi.browser.IE6){
				autoInput.AutocompleteIE6HoverElement = document.getElementById(autoInput.AutocompleteIE6Hover) || null;
			}

			var fontGetter = document.createElement("div");
			fontGetter.style.fontSize = "1em";
			fontGetter.style.width = "1em";
			fontGetter.style.margin = "0";
			fontGetter.style.padding = "0";
                        el.parentNode.insertBefore(fontGetter, el);

                        autoInput.inputFontSize = 10;
                        fontGetter.parentNode.removeChild(fontGetter);

			var inputMargin = new Array();
			inputMargin.push(whi.getStyle(el,'margin-top'));
			inputMargin.push(whi.getStyle(el,'margin-bottom'));
			for (var i=0; i<inputMargin.length; i++){
				var isEm = inputMargin[i].indexOf('em') > 0;
				var isPx = inputMargin[i].indexOf('px') > 0;
				var crMargin = parseFloat(inputMargin[i]);
				if (isNaN(crMargin)) crMargin = 0;
				if (isPx) crMargin = crMargin / autoInput.inputFontSize;
				inputMargin[i] = crMargin;
			}

			el.parentNode.insertBefore(autoInput, el);
			
			autoInput.targetInput = el;
			autoInput.targetInput.lastValue = '';
			autoInput.targetInput.typedValue = '';
			autoInput.targetInput.parentInput = autoInput;
			whi.events.addEvent(autoInput.targetInput,'focus',autoInput.showResults);
			whi.events.addEvent(autoInput.targetInput,'blur',function(){setTimeout(this.parentInput.hideResults,100);});
			whi.events.addEvent(autoInput.targetInput,'keydown',autoInput.getSelectKeys);
			whi.events.addEvent(autoInput.targetInput,'keyup',autoInput.getSelectKeys);
			whi.events.addEvent(autoInput.targetInput,'keyup',autoInput.putSearchTerm);
   			whi.events.addEvent(autoInput.targetInput,'change',autoInput.putSearchTerm);

			autoInput.appendChild(autoInput.targetInput);

			autoInput.targetResults = document.createElement("div");
			autoInput.appendChild(autoInput.targetResults);

			var divWidth = parseInt(whi.getElementWidth(autoInput)) || 0;

			autoInput.style.width = (inputWidth/autoInput.inputFontSize)+"em";

			autoInput.style.height = (inputHeight/autoInput.inputFontSize)+"em";
			autoInput.style.marginTop = inputMargin[0]+"em";
			autoInput.style.marginBottom = inputMargin[1]+"em";
			autoInput.targetInput.style.margin = "0";
			autoInput.targetResults.style.top = (inputHeight/autoInput.inputFontSize)+"em";
			autoInput.targetInput.setAttribute("autocomplete","off");

			autoInput.searchLabel = document.createElement("div");
			autoInput.searchLabel.className = "autoLabel";
			autoInput.searchLabel.innerHTML = "Sugestii de cautare&nbsp;";
			autoInput.targetResults.appendChild(autoInput.searchLabel);

			for (var i=0; i<10; i++){
				var resultContainer = document.createElement("div");
				resultContainer.ind = i;
				resultContainer.res = {};
				resultContainer.resElement = autoInput;
				resultContainer.onmouseover = function(){
					this.resElement.selectResult(this.ind);
				}
				resultContainer.onmousedown = function(){
					this.resElement.value = this.res["res_name"];
					this.resElement.searchTerm = this.res["res_name"];

					window.location.href = this.resElement.calcLink();
				}
				if (i==0){
					resultContainer.className = "autoFirstResult";
				}
				resultContainer.style.display = "none";

				resultContainer.resultLink = document.createElement("a");
				resultContainer.resultLink.innerHTML = "";
				resultContainer.resultLink.initialValue = "";
				resultContainer.resultLink.setAttribute("tabIndex","-1");
				resultContainer.appendChild(resultContainer.resultLink);

				autoInput.searchResults.push(resultContainer);
				autoInput.targetResults.appendChild(resultContainer);
			}

			if (autoInput.scriptReplace){
				var script = autoInput.nextSibling;
				if (script){
					script.parentNode.removeChild(script);
				}
                                autoInput.targetInput.id = autoInput.replaceId;
			}
			if (elementFocusedBefore == true){
				autoInput.targetInput.focus();
			}
		}else{
			if (Autocomplete.verbose){
				alert("Nothing to replace");
			}
		}
	},
	showResults : function(e){
		if (this.nrResults>0){
			this.resultsShowem = true;
			this.targetResults.style.display = 'block';
			if (this.IEFlicker == true){
				this.IEFlicker = false;
				setTimeout(this.hideResults,10);
				setTimeout(this.showResults,10);
			}
			if (this.AutocompleteIE6HoverElement){
				this.AutocompleteIE6HoverElement.style.height = whi.getElementHeight(this.targetResults)+"px";
				this.AutocompleteIE6HoverElement.style.display = "";
			}
		}else{
			this.hideResults();
		}
	},
	hideResults : function(){
		this.targetResults.style.display = 'none';
		this.resultsShowem = false;
		if (this.AutocompleteIE6HoverElement){
			this.AutocompleteIE6HoverElement.style.display = "none";
		}
	},
	putSearchTerm : function(e){
		if (this.lastKeyNormal == false){
			return true;
		}
		var selStart = whi.getSelectionStart(this.targetInput);

		var term = this.targetInput.value.toString();
		if ((term != this.targetInput.lastValue)){
			this.targetInput.lastValue = term;

			var wrds = term;

			if ((this.searchTerm.toLowerCase() != wrds.toLowerCase())){

				var initSearch = this.searchTerm;

				this.hightlightElements = new Array();
				this.clearSelectedResult();

				if (term.trim() == ''){
					this.getSearchResults();
				}else{
					this.searchTerm = wrds;
					this.clearAutoTimer();

					this.lastSearchedValue = this.searchTerm;

					sendToActionScript(this.searchTerm);
				}
			}
		}
		this.showResults();
		return true;
	},
	getSelectKeys : function(e){
		var code;
		if (!e) var e = window.event;
		if (!e) return true;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		else return true;
		
		this.lastKeyNormal = false;
		

		switch(code){
			case 40 :
					if (e.type == 'keydown'){
						var sel_ind = this.resultsShowem ? this.selectedResult+1 : this.selectedResult;
						this.selectResult(sel_ind, true);
						whi.events.stopEvent(e);
						if (this.targetInput.value != '' && this.justAfterInit){
							this.justAfterInit = false;
							this.lastKeyNormal = true;
						}
						return false;
					}
					break;
			case 38 :
					if (e.type == 'keydown'){
						var sel_ind = this.resultsShowem ? this.selectedResult-1 : this.selectedResult;
						this.selectResult(sel_ind, true);
						whi.events.stopEvent(e);
						if (this.targetInput.value != '' && this.justAfterInit){
							this.justAfterInit = false;
							this.lastKeyNormal = true;
						}
						return false;
					}
					break;
			case 27 :
			//escape
					if (e.type == 'keydown'){
						this.targetInput.value = this.targetInput.typedValue;
						this.targetInput.typedValue = '';

						this.hideResults();
					}
					break;
			default :
					if (e.type == 'keyup'){
						if (this.justAfterInit || (this.targetInput.value != this.targetInput.typedValue && this.targetInput.value != this.targetInput.lastValue)){
	                                        	this.lastKeyNormal = true;
	     					}else if (code == 8 || code == 46){
							this.lastKeyNormal = true;
						}
					}else{
						this.lastKeyNormal = true;
					}
					break;
		}
		return true;
	},
	clearSelectedResult : function(){
		if (this.selectedResult >= 0){
			whi.remove_class(this.searchResults[this.selectedResult],'autocomplete_hover');
			this.selectedResult = -1;
		}
	},
	selectResult : function(ind, put_value){
		//alert(ind);
		if (this.searchResults[ind] && this.searchResults[ind].style.display != "none"){
			this.clearSelectedResult();

			this.selectedResult = ind;
			whi.add_class(this.searchResults[this.selectedResult],'autocomplete_hover');
			if (!this.resultsShowem){
				this.showResults();
			}
			if (put_value == true){
				if (!this.targetInput.typedValue){
					this.targetInput.typedValue = this.targetInput.value;
				}
				this.targetInput.value = this.searchResults[this.selectedResult].res.res_name;
				this.targetInput.lastValue = this.targetInput.value;
			}
		}
	},
	getSearchResults : function(resFromDaemon){
		if (this.lastKeyNormal == false){
			return;
		}
		var emptyXML = true;
		var destroyObject = false;

		this.clearSelectedResult();

                this.nrResults = 0;

		resFromDaemon = resFromDaemon ? resFromDaemon : "";
		resFromDaemon = resFromDaemon.trim();

		if (resFromDaemon == '' && this.lastSearchedValue.indexOf(" ",this.lastSearchedValue.length-1) == this.lastSearchedValue.length-1){
			this.lastSearchedValue = this.searchTerm.trim();
			sendToActionScript(this.lastSearchedValue);
		}

		var items = resFromDaemon.split("\n");

		this.searchLabel.style.display = items.length > 0 ? "" : "none";
		
		var search_length = this.searchTerm.length;
		var highlighted_str = '<span>'+this.searchTerm+'</span>';

		for (var i=0; i<10; i++){
			if (i < items.length && items[i] != ''){
				var str = highlighted_str+(items[i].substr(search_length));

				this.searchResults[i].res["res_name"] = items[i];
				this.searchResults[i].style.display = "";
				this.searchResults[i].resultLink.innerHTML = str;

				this.nrResults++;
			}else{
				this.searchResults[i].style.display = "none";
			}
		}
		
		this.showResults();
	},
	putDefaultResult : function(){
		this.hideResults();
	},
	startAutoTimer : function(){
		if ((this.AutocompleteAutoSearch == true) && (this.AutocompleteAutoSearchTimeout >0)){
			this.clearAutoTimer();
			this.autoTimeout = setTimeout(this.putAutoSearch,this.AutocompleteAutoSearchTimeout * 1000);
		}
	},
	clearAutoTimer : function(){
		//this.autoSearch = false;
		if (this.autoTimeout >0){
			clearTimeout(this.autoTimeout);
			this.autoTimeout = -1;
		}
	},
	putAutoSearch : function(){
		//this.autoSearch = true;
		this.putSearchTerm();
	},
	calcLink : function(){
		var searchStr = this.searchTerm.trim();
		/* searchStr = searchStr.replace(/[^a-zA-Z0-9]/g,'-');
		searchStr = searchStr.replace(/[\-]+/g,' '); */
		return this.crDomain + "/" +this.AutocompleteDefaultLink.replace('$1',escape(searchStr));
	}
}

function key_hideDefaultValue(){
	if (this.value == key_default_value){
		this.value = '';
	}
}

function key_showDefaultValue(){
	if (this.value == ''){
		this.value = key_default_value;
	}
}


jsRules.addRule("#auto_top_search",function(){
	whi.events.addEvent(this,'submit',function(){
		var a;
		if (a = document.getElementById('key')){
			if (a.value != key_default_value){
				return true;
			}
		}
		return false;
	});
});

jsRules.addRule("#auto_top_search #key",function(){
	whi.events.addEvent(this,'focus',key_hideDefaultValue);
	whi.events.addEvent(this,'blur',key_showDefaultValue);

	Autocomplete.replaceInput(this, {
		AutocompleteAutoSearch		: true,
		AutocompleteAutoSearchTimeout 	: Autocomplete.AutocompleteAutoSearchTimeout,
		AutocompleteFollowLinkOnEnter 	: false,
		AutocompleteIE6Hover	 	: "ie6_autocomplete_hover_iframe"
	});
});




