/*requires pozitron.js*/
function AutoComplete( dest, datasrc, params, target, onchangefunc, onclickfunc, options ){
	this.init(dest, datasrc, params, target, onchangefunc, onclickfunc, options );
}

AutoComplete.prototype = {
	lasttimerid: null,
	connector: null,
	filter: "",
	activeitem: 0,
	items: null,
	target: null,
	onchangefunc : null,
	STR : Str.autoComplete,	
	init: function(dest, datasrc, params, target, onchangefunc, onclickfunc, options )
	{
		this.standardText =  this.STR.standardText; //"Termék név / ISIN / Kibocsátó";
		this.input = $(dest);
		this.target = $(target);
		
		this.datasrc = datasrc;
		this.params = params;
		this.options = options;
		
		if ( !this.options ) {
			this.options = {};
		}
		
		if (!this.options.urlprefix){
			this.options.urlprefix = "";
		}

		this.input.value = this.standardText;
		this.input.onkeydown = this.initcompletion.bindAsEventListener(this);
		this.input.onclick = this.oninputclicked.bind( this );
		this.input.onblur = this.initclose.bind(this);
		this.input.autocomplete = "off";
		this.onchangefunc = onchangefunc;
		this.onclickfunc = onclickfunc;
		
		if ( this.options.inputwidth ) {
			this.input.style.width = this.options.inputwidth;
		} else {
			this.input.style.width = "200px";
		}	

		if ( !this.options.noproductlookup ) {		
			this.productlookup = document.createElement("img");
			this.productlookup.src = this.options.urlprefix + "img/nagyito.gif";
			this.productlookup.title = this.STR.prodBrowser;//"Termék böngésző";
			this.productlookup.style.cssText = "cursor: pointer; position: relative; top: 5px; left: 3px;";
			
			
			this.productlookup.onclick = this.onProductLookupClicked.bind( this );
			this.input.parentNode.insertBefore( this.productlookup, this.input.nextSibling );		
		}
	
		this.resultcontainer = document.createElement("div");
		this.resultcontainer.className = "autocompleteresults";
		this.resultcontainer.style.position = "absolute";
		this.resultcontainer.style.zIndex = 200002;
		this.resultcontainer.style.display = "none";
		if ( !this.options.resultContainerParent ) {
			this.input.parentNode.appendChild(this.resultcontainer);		
		} else {
			this.options.resultContainerParent.appendChild( this.resultcontainer );
		}
	},
	
	oninputclicked: function(evt) {
		this.input.select();
		this.initcompletion(evt);	
	},
	
	initcompletion: function(evt)
	{	
		var key = 0;
		try{key = evt.keyCode;} catch(ex){}
		switch(key)
		{
			case 38:	
					this.activateitem(this.activeitem-1); 
					this.resultcontainer.scrollTop = Math.floor((this.items[this.activeitem].offsetTop - this.resultcontainer.offsetHeight/2)) ;
					this.sleepMouse(150);
				break;
			case 40:	
					this.activateitem(this.activeitem+1); 
					this.resultcontainer.scrollTop = Math.floor((this.items[this.activeitem].offsetTop - this.resultcontainer.offsetHeight/2)) ;
					this.sleepMouse(150);
				break;
			case 33://pgup
					this.activateitem(0); 
					this.resultcontainer.scrollTop = Math.floor((this.items[this.activeitem].offsetTop - this.resultcontainer.offsetHeight/2)) ;
					this.sleepMouse(150);
				break;
			case 34://pgdown
					this.activateitem(this.items.length - 1); 
					this.resultcontainer.scrollTop = Math.floor((this.items[this.activeitem].offsetTop - this.resultcontainer.offsetHeight/2)) ;
					this.sleepMouse(150);
				break;
			case 13:	
					if(this.resultcontainer.style.display != "none")
					{
						this.input.value = this.data[this.activeitem].data[0].unescapeHTML();
						if (this.target!=null) {
							this.target.value = this.data[this.activeitem].id;
						}
						if (this.onchangefunc!=null) {
							this.onchangefunc( this.data[this.activeitem].id, this.data[this.activeitem] );
						}						
						this.close(); 
					}
					break;
			case 27: 
					this.initclose();
				break;
			default:	
					window.clearTimeout(this.lasttimerid);
					this.lasttimerid = window.setTimeout( this.getinput.bind(this), 500);		
				break;
		}
	},
	
	getinput: function()
	{	
		if(this.input.value.length > 0)
		{
			var datefilter = "";
			if (this.onclickfunc!=null) {
				datefilter = this.onclickfunc();			
			}
			this.connector = new Connector(this.datasrc, this.params + "&text=" + encodeURIComponent(this.input.value) + ("&filter=" + this.filter+"|"+datefilter), this.dataready.bind(this) );
		}	
	},
	
	onProductLookupClicked: function() {
		var param = {};
		param.url = this.options.urlprefix + "productbrowser.dialog";
		param.width = "800";
		param.modal = true;
		param.modalParent = this.target;
		param.createParams = {};
		param.createParams.returnFunc = this.gotProductFromLookup.bind(this);

		if (this.onclickfunc!=null) {
			param.createParams.dateFilter = this.onclickfunc();
		} else {
			param.createParams.dateFilter = getDateString( 0 );		
		}
		
		param.createParams.product_type_filter = this.filter;
				
		var dialog = new Dialog( param );
	},

	gotProductFromLookup: function( product_id, product, productlist ) {
		this.input.value = product.data[ 0 ].unescapeHTML();
		if (this.target!=null) {
			this.target.value = product_id;
		}				
		if (this.onchangefunc!=null) {
			this.onchangefunc( product_id, product, productlist );
		}
	},
	
	colorResult: function( fraction, original, fontSize ) {
		var fractionArray = fraction.split( " " );
		var originalArray = original.split( " " );
		
		var result = "";
		
		for ( var i = 0; i < originalArray.length; i++ ) {
			if ( i > 0 ) result += " ";		
			var colored = originalArray[ i ];
			for ( var j = 0; j < fractionArray.length; j++ ) {
				var newColored = this.colorOneResult( fractionArray[ j ], originalArray[ i ], fontSize );
				if ( newColored != colored ) {
					colored = newColored;
					break;
				}
			}
			result += colored;			
		}
		
		return result;
	
	},
	
	colorOneResult: function( fraction, original, fontSize ) {
		var fracLen = fraction.length;
		var bigOriginal = original.toLowerCase();
		var result = original;
		
		var idx = bigOriginal.indexOf( fraction.toLowerCase() );
		
		var fontSizeString = "";
		if ( fontSize ) {
			fontSizeString = "font-size:" + fontSize + "px;";
		}		
		
		if ( idx > -1 ) {
			result = original.substr(0, idx ) + "<span style='color:#ff0000;text-decoration:underline;"+fontSizeString+ "'>" + original.substr( idx, fracLen ) + "</span>" + original.substr( idx + fracLen, original.length );
		}		
		
		return result;
	},	
	
	dataready: function(data)
	{
		this.resultcontainer.innerHTML = "";
		this.resultcontainer.onfocus = function() { window.clearTimeout(this.lasttimerid); }.bind(this);
		this.resultcontainer.onblur = function() { this.lasttimerid = window.setTimeout(this.close.bind(this), 300); }.bind(this);
		try{
			//data: [ {id: <productid>, data: { <name>, <type> } }, ...   ]
			this.data = eval(data);
			this.items = new Array();
			if( this.data.length > 0 )
			{
				var table = document.createElement("table");
					table.style.width="400px";
					
					var tbody = document.createElement("tbody");
					tbody.style.width="400px";
	
						for(var i=0; i<this.data.length;i++)
						{
							var tr = document.createElement("tr");
								var td = document.createElement("td");
									td.style.cursor = "pointer";
									td.onmouseover = this.activateitem.bind(this, Number(i));
									td.onclick = this.resultclicked.bind(this, Number(i));
									td.innerHTML ="<span style='font-size:13px;font-weight:bold;color:#000066;'>" + this.colorResult( this.input.value, this.data[i].data[0].unescapeHTML(), 13 ) + "</span>";
									if (this.data[i].data[5]!=null) {
										td.innerHTML+="- <span style='font-style:italic;font-size:13px;'>" + this.colorResult( this.input.value, this.data[i].data[5].unescapeHTML(), 13 ) + "</span>";
									}
									td.innerHTML+="<br/>";
									td.innerHTML+=this.data[i].data[3]+ " " +this.colorResult( this.input.value, this.data[i].data[4] )+" - " +this.colorResult( this.input.value, this.data[i].data[2].unescapeHTML(), 13 );
								tr.appendChild(td);
								
							this.items[i] = tr;												
							tbody.appendChild(tr);
						}
						if (this.data.length==25) {					
							tr = document.createElement("tr");
							td = document.createElement("td");
							td.innerHTML = this.STR.tooMuchFound;//"Túl sok találat, pontosítsa a keresési feltételt!";
							td.style.textAlign = "center";
							td.style.color = "#ff0000";
							tr.appendChild(td);
							tbody.appendChild(tr);																	
						}
						
					table.appendChild(tbody);
					this.resultcontainer.style.display = "inline";
				var offsets = Position.positionedOffset(this.input);
				this.resultcontainer.style.left = offsets[0] + "px";
				this.resultcontainer.style.top = offsets[1] + this.input.offsetHeight + "px";
				
				
				this.activateitem(0);
				this.resultcontainer.appendChild(table);
				this.resultcontainer.style.overflowY = "auto";
				if( table.offsetHeight + 10 > document.body.clientHeight -  (/*a wintop-tol*/offsets[1] + this.input.offsetHeight - document.body.scrollTop)){
					this.resultcontainer.style.height = (document.body.clientHeight -  (/*a wintop-tol*/offsets[1] + this.input.offsetHeight - document.body.scrollTop) - 10) + "px"; 
				}
				else{
					this.resultcontainer.style.height = "";
				}
			}
			else{
				this.resultcontainer.style.display = "none";
			}
		}
		catch(err)
		{
			window.alert(err);
			this.close();
		}
		
		
		
	},
	
	resultclicked: function(num)
	{
		if (this.data!=null && this.data[num] != null && this.data[num].data!=null && this.data[num].data[0]!=null) {
			this.input.value = this.data[num].data[0].unescapeHTML();
			if (this.target!=null) {
				this.target.value=this.data[num].id;
			}		
			if (this.onchangefunc!=null) {
				this.onchangefunc( this.data[num].id, this.data[num] );
			}
		}
	},
	
	activateitem: function(num)
	{
		if( this.mouseSleeping ) return;
		if(num < 0) num = 0;
		if(num > this.data.length - 1) num = this.data.length - 1;
		if (this.items!=null && this.items[this.activeitem]!=null) {
			this.items[this.activeitem].className = "";
		}
		this.activeitem = num;
		this.items[this.activeitem].className = "activetr";
	},

	initclose: function()
	{
		window.clearTimeout(this.lasttimerid);
		this.lasttimerid = window.setTimeout( this.close.bind(this), 300);
	},

	close: function()
	{
		this.resultcontainer.style.display = "none";
	},
	
	sleepMouse: function( interval ){
		this.mouseSleeping = true;
		window.setTimeout(this.wakeMouse.bind(this), interval);
	},
	
	wakeMouse: function(){
		this.mouseSleeping = false;
	},
	
	msg: function(param)
	{
		//window.alert("Class:\tAutoComplete\nDatasrc:\t" + this.datasrc + "\nMessage:\t" + param);	
	}
}

