var searchproduct = {
	ajaxobj:undefined,ajaxmsg:undefined,autocompleteobj:undefined,
	keylatencyinterval:undefined,keylatencylaunched:undefined,keytime:undefined,keylatencytime:10,keylimitlatency:800,	//milisegundos, control de keygrabber
	url:undefined,lastajaxtime:undefined,

	init:function(){addlistener(window,"load",this.onload.bindAsEventListener(this));},

	onload:function()
	{	this.ajaxmsg=document.getElementById("ajaxmsg");
		this.autocompleteobj=document.getElementById("search");
		this.autocomplete=document.getElementById("ajaxautocomplete");
		this.ajaxinfo=document.getElementById("ajaxinfo");  this.ajaxinfo.style.display="none";
		this.ajaxerror=document.getElementById("ajaxerror"); this.ajaxerror.style.display="none";
		this.ajaxloading=document.getElementById("ajaxloading"); this.ajaxloading.style.display="none";
		addlistener(this.autocompleteobj, 'keypress', this.keycontrol.bindAsEventListener(this));
		addlistener(this.autocompleteobj, 'focus', this.focus.bindAsEventListener(this));

		this.autocompleteobj.disabled=false;
	},

	initajax:function()
	{	delete this.ajaxobj;
		if (window.XMLHttpRequest) { this.ajaxobj = new XMLHttpRequest (); } // Si es Mozilla, Safari etc
		else if (window.ActiveXObject)
		{	try { this.ajaxobj = new ActiveXObject ("Msxml2.XMLHTTP"); } //pero si es IE
			catch (e){ try { this.ajaxobj = new ActiveXObject ("Microsoft.XMLHTTP"); } catch(e) { }  } // en caso que sea una versión antigua
		}
		else return false;
		if(this.ajaxobj) return true; else return false;
	},

	msg:function(s){ this.showloading(false); if(this.ajaxmsg) {this.ajaxmsg.innerHTML=s; this.showmsg(true);} },
	info:function(s){ this.showall(false); this.showinfo(true); this.msg(s); },
	error:function(s){ this.showall(false); this.showerror(true); this.msg(s); },

	showmsg:function(v)				{d="none";if(v)d="block"; this.ajaxmsg.style.display=d;},
	showloading:function(v)			{d="none";if(v)d="block"; this.ajaxloading.style.display=d;},
	showinfo:function(v)				{d="none";if(v)d="block"; this.ajaxinfo.style.display=d;},
	showerror:function(v)			{d="none";if(v)d="block"; this.ajaxerror.style.display=d;},
	showautocomplete:function(v)	{d="none";if(v)d="block"; this.autocomplete.style.display=d;},
	showall:function(v) 				{this.showloading(v); this.showinfo(v); this.showerror(v);this.showautocomplete(v);},

	focus:function(evt){evt=evt||window.event;	target= evt.target || evt.srcElement;	target.value='';this.showall(false);},

	keycontrol:function(evt)
	{	evt=evt||window.event; 	key=(evt.which ||evt.keyCode);	//this.msg(key);
		this.showall(false);this.msg(' ');
     	switch(key)
		{  case 37:case 38:case 39:case 40: case 46: case 36: case 35: case 18: return; break; //left,up,right,down,delete,home,end,alt
			case 27: 	this.autocompleteobj.value='';return;		break;/*ESC*/
			case 13:	  this.launch_search();return;	break;/*ENTER*/
		}
		this.keytime=new Date().getTime(); //si pulsa rapidamente el teclado mejor esperar a que acabe....
		if(!this.keylatencylaunched) this.keylatencyinterval = setInterval(this.keylatency.bindAsEventListener(this),  this.keylatencytime);
	   this.keylatencylaunched=true;
	},

	keylatency:function()	//si pulsa rapidamente el teclado mejor esperar a que acabe....
	{	try
		{	var diff=(new Date().getTime())-this.keytime;
			if( diff>this.keylimitlatency)
			{	clearInterval(this.keylatencyinterval);
				this.keytime=null;  this.keylatencylaunched=false; /*	trace("keylatency"+field,true);*/
				this.launch_search();
			}
		}
		catch(e){this.error("js:"+e.message);}
	},


	launch_search:function()
	{	try
		{	if(this.autocompleteobj.value.length <= 0) return;
			this.initajax();
			this.lastajaxtime=Math.floor(new Date());
			this.url='/templates/default/modules/catalogo/search_db.php?time='+this.lastajaxtime+'&op=search&value='+this.autocompleteobj.value;
			//trace(url.replace(/&/g,"&amp;"));//return;
			this.ajaxobj.onreadystatechange = this.process_search.bindAsEventListener(this);
			this.showall(false);this.msg('');this.showloading(true);
	      this.ajaxobj.open('GET', this.url, true); // asignamos los métodos open y send
	   	this.ajaxobj.send(null);
			return;
      }
		catch(e){this.error("js:"+e.message);}
	},

	process_search:function(ajaxobj)
	{  try
		{	ajax=this.ajaxobj;
			if(!(ajax.readyState == 4 && (ajax.status==200|| window.location.href.indexOf("http")==- 1))) return;
			if(!ajax.responseXML || ajax.responseXML==null) { this.error("Not XML response"); /*alert(ajax.responseText);*/return;}

        	var xml  = ajax.responseXML;
			var error=eval(xml.getElementsByTagName("error"));
			var info=xml.getElementsByTagName("info");
			var ok=xml.getElementsByTagName("ok");
			var time=eval(xml.getElementsByTagName("time")); if(time && time.length>0) time=time[0].firstChild.data; else time=undefined;

			if(time && time!=this.lastajaxtime) { /* alert("ajax jurasica");*/ return; }

         if(info && info.length>0){ switch(info[0].firstChild.data)
			{	case "NOTFOUND" : this.info("No encontrado"); break;
				default : this.info(info[0].firstChild.data); break;
			} return; }

			if(ok && ok.length>0)
			{	var op=eval(xml.getElementsByTagName("op")); 			if(op && op.length>0) 			op=op[0].firstChild.data; 			else op=undefined;
				var result=eval(xml.getElementsByTagName("result")); 	if(result && result.length>0)	result=result[0]; 					else result=undefined;

				size=result.getAttribute("size")
				productos=result.getElementsByTagName("producto");
				var s="";
				for (i = 0; i < productos.length && i<100; i++)
		      {	codigo=productos[i].getAttribute("codigo");
					name=productos[i].firstChild.data.replace(/&/g,"&amp;");	//por problemas del firefox javascript con el &
					link=productos[i].getAttribute("codigo");
					s=s+"<li><a href='"+link+"'>"+(name)+"</a></li>\n";
				}
				//ojo no debe haber espacios en blanco entre divs y spans
				this.autocomplete.childNodes[0].childNodes[0].innerHTML=result.getAttribute("size");
				this.autocomplete.childNodes[1].innerHTML="<ul>"+s+"</ul>";
				this.showautocomplete(true);this.showloading(false);
				//alert(s);
				return;
			}
			this.error("bad XML resp.format"); alert(ajax.responseText);
      }
		catch(e){this.error("js:"+e.message);}
	}

};

searchproduct.init();