2 * author: Timothy Groves - http://www.brandspankingnew.net
3 * version: 1.2 - 2006-11-17
13 if (typeof(bsn) == "undefined")
17 if (typeof(_b.Autosuggest) == "undefined")
20 alert("Autosuggest is already set!");
33 _b.AutoSuggest = function (id, param)
37 if (!document.getElementById)
45 this.fld = _b.DOM.gE(id);
65 this.oP = param ? param : {};
69 var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:500, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 25};
72 if (typeof(this.oP[k]) != typeof(def[k]))
77 // set keyup handler for field
78 // and prevent autocomplete from client
82 // NOTE: not using addEventListener because UpArrow fired twice in Safari
83 //_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
85 this.fld.onkeypress = function(ev){ return p.onKeyPress(ev); };
86 this.fld.onkeyup = function(ev){ return p.onKeyUp(ev); };
88 this.fld.setAttribute("autocomplete","off");
106 _b.AutoSuggest.prototype.onKeyPress = function(ev)
109 var key = (window.event) ? window.event.keyCode : ev.keyCode;
113 // set responses to keydown events in the field
114 // this allows the user to use the arrow keys to scroll through the results
115 // ESCAPE clears the list
116 // TAB sets the current highlighted value
127 this.setHighlightedValue();
132 this.clearSuggestions();
141 _b.AutoSuggest.prototype.onKeyUp = function(ev)
143 var key = (window.event) ? window.event.keyCode : ev.keyCode;
147 // set responses to keydown events in the field
148 // this allows the user to use the arrow keys to scroll through the results
149 // ESCAPE clears the list
150 // TAB sets the current highlighted value
163 this.changeHighlight(key);
169 this.changeHighlight(key);
175 this.getSuggestions(this.fld.value);
190 _b.AutoSuggest.prototype.getSuggestions = function (val)
193 // if input stays the same, do nothing
195 if (val == this.sInp)
201 _b.DOM.remE(this.idAs);
207 // input length is less than the min required to trigger a request
210 if (val.length < this.oP.minchars)
213 this.nInpC = val.length;
220 var ol = this.nInpC; // old length
221 this.nInpC = val.length ? val.length : 0;
225 // if caching enabled, and user is typing (ie. length of input is increasing)
226 // filter results out of aSuggestions from last request
228 var l = this.aSug.length;
229 if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
232 for (var i=0;i<l;i++)
234 if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
235 arr.push( this.aSug[i] );
239 this.createList(this.aSug);
250 var input = this.sInp;
251 clearTimeout(this.ajID);
252 this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
262 _b.AutoSuggest.prototype.doAjaxRequest = function (input)
264 // check that saved input is still the value of the field
266 if (input != this.fld.value)
273 // create ajax request
275 if (typeof(this.oP.script) == "function")
276 var url = this.oP.script(encodeURIComponent(this.sInp));
278 var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
283 var meth = this.oP.meth;
284 var input = this.sInp;
286 var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
287 var onErrorFunc = function (status) { alert("AJAX error: "+status); };
289 var myAjax = new _b.Ajax();
290 myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
297 _b.AutoSuggest.prototype.setSuggestions = function (req, input)
299 // if field input no longer matches what was passed to the request
300 // don't show the suggestions
302 if (input != this.fld.value)
311 var jsondata = eval('(' + req.responseText + ')');
313 for (var i=0;i<jsondata.results.length;i++)
315 this.aSug.push( { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info } );
321 var xml = req.responseXML;
325 var results = xml.getElementsByTagName('results')[0].childNodes;
327 for (var i=0;i<results.length;i++)
329 if (results[i].hasChildNodes())
330 this.aSug.push( { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') } );
335 this.idAs = "as_"+this.fld.id;
338 this.createList(this.aSug);
355 _b.AutoSuggest.prototype.createList = function(arr)
362 // get rid of old list
363 // and clear the list removal timeout
365 _b.DOM.remE(this.idAs);
369 // if no results, and shownoresults is false, do nothing
371 if (arr.length == 0 && !this.oP.shownoresults)
375 // create holding div
377 var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});
379 var hcorner = _b.DOM.cE("div", {className:"as_corner"});
380 var hbar = _b.DOM.cE("div", {className:"as_bar"});
381 var header = _b.DOM.cE("div", {className:"as_header"});
382 header.appendChild(hcorner);
383 header.appendChild(hbar);
384 div.appendChild(header);
389 // create and populate ul
391 var ul = _b.DOM.cE("ul", {id:"as_ul"});
396 // loop throught arr of suggestions
397 // creating an LI element for each suggestion
399 for (var i=0;i<arr.length;i++)
401 // format output with the input enclosed in a EM element
402 // (as HTML, not DOM)
404 var val = arr[i].value;
405 var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
406 var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
409 var span = _b.DOM.cE("span", {}, output, true);
410 if (arr[i].info != "")
412 var br = _b.DOM.cE("br", {});
413 span.appendChild(br);
414 var small = _b.DOM.cE("small", {}, arr[i].info);
415 span.appendChild(small);
418 var a = _b.DOM.cE("a", { href:"#" });
420 var tl = _b.DOM.cE("span", {className:"tl"}, " ");
421 var tr = _b.DOM.cE("span", {className:"tr"}, " ");
428 a.onclick = function () { pointer.setHighlightedValue(); return false; };
429 a.onmouseover = function () { pointer.setHighlight(this.name); };
431 var li = _b.DOM.cE( "li", {}, a );
433 ul.appendChild( li );
439 if (arr.length == 0 && this.oP.shownoresults)
441 var li = _b.DOM.cE( "li", {className:"as_warning"}, this.oP.noresults );
442 ul.appendChild( li );
446 div.appendChild( ul );
449 var fcorner = _b.DOM.cE("div", {className:"as_corner"});
450 var fbar = _b.DOM.cE("div", {className:"as_bar"});
451 var footer = _b.DOM.cE("div", {className:"as_footer"});
452 footer.appendChild(fcorner);
453 footer.appendChild(fbar);
454 div.appendChild(footer);
458 // get position of target textfield
459 // position holding div below it
460 // set width of holding div to width of field
462 var pos = _b.DOM.getPos(this.fld);
464 div.style.left = pos.x + "px";
465 div.style.top = ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
466 div.style.width = this.fld.offsetWidth + "px";
470 // set mouseover functions for div
471 // when mouse pointer leaves div, set a timeout to remove the list after an interval
472 // when mouse enters div, kill the timeout so the list won't be removed
474 div.onmouseover = function(){ pointer.killTimeout() };
475 div.onmouseout = function(){ pointer.resetTimeout() };
478 // add DIV to document
480 document.getElementsByTagName("body")[0].appendChild(div);
484 // currently no item is highlighted
493 // remove list after an interval
496 this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
513 _b.AutoSuggest.prototype.changeHighlight = function(key)
515 var list = _b.DOM.gE("as_ul");
527 if (n > list.childNodes.length)
528 n = list.childNodes.length;
533 this.setHighlight(n);
538 _b.AutoSuggest.prototype.setHighlight = function(n)
540 var list = _b.DOM.gE("as_ul");
545 this.clearHighlight();
547 this.iHigh = Number(n);
549 list.childNodes[this.iHigh-1].className = "as_highlight";
556 _b.AutoSuggest.prototype.clearHighlight = function()
558 var list = _b.DOM.gE("as_ul");
564 list.childNodes[this.iHigh-1].className = "";
570 _b.AutoSuggest.prototype.setHighlightedValue = function ()
574 this.sInp = this.fld.value = this.aSug[ this.iHigh-1 ].value;
576 // move cursor to end of input (safari)
579 if (this.fld.selectionStart)
580 this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
583 this.clearSuggestions();
585 // pass selected object to callback function, if exists
587 if (typeof(this.oP.callback) == "function")
588 this.oP.callback( this.aSug[this.iHigh-1] );
604 _b.AutoSuggest.prototype.killTimeout = function()
606 clearTimeout(this.toID);
609 _b.AutoSuggest.prototype.resetTimeout = function()
611 clearTimeout(this.toID);
613 this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
622 _b.AutoSuggest.prototype.clearSuggestions = function ()
627 var ele = _b.DOM.gE(this.idAs);
631 var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
644 // AJAX PROTOTYPE _____________________________________________
647 if (typeof(_b.Ajax) == "undefined")
652 _b.Ajax = function ()
660 _b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
666 this.onComplete = onComp;
667 this.onError = onErr;
671 // branch for native XMLHttpRequest object
672 if (window.XMLHttpRequest)
674 this.req = new XMLHttpRequest();
675 this.req.onreadystatechange = function () { pointer.processReqChange() };
676 this.req.open("GET", url, true); //
678 // branch for IE/Windows ActiveX version
680 else if (window.ActiveXObject)
682 this.req = new ActiveXObject("Microsoft.XMLHTTP");
685 this.req.onreadystatechange = function () { pointer.processReqChange() };
686 this.req.open(meth, url, true);
693 _b.Ajax.prototype.processReqChange = function()
696 // only if req shows "loaded"
697 if (this.req.readyState == 4) {
699 if (this.req.status == 200)
701 this.onComplete( this.req );
703 this.onError( this.req.status );
717 // DOM PROTOTYPE _____________________________________________
720 if (typeof(_b.DOM) == "undefined")
726 _b.DOM.cE = function ( type, attr, cont, html )
728 var ne = document.createElement( type );
735 var t = typeof(cont);
737 if (t == "string" && !html)
738 ne.appendChild( document.createTextNode(cont) );
739 else if (t == "string" && html)
741 else if (t == "object")
742 ne.appendChild( cont );
750 _b.DOM.gE = function ( e )
753 if (t == "undefined")
755 else if (t == "string")
757 var re = document.getElementById( e );
760 else if (typeof(re.appendChild) != "undefined" )
765 else if (typeof(e.appendChild) != "undefined")
774 _b.DOM.remE = function ( ele )
776 var e = this.gE(ele);
780 else if (e.parentNode.removeChild(e))
789 _b.DOM.getPos = function ( e )
796 if (obj.offsetParent)
798 while (obj.offsetParent)
800 curleft += obj.offsetLeft;
801 obj = obj.offsetParent;
810 if (obj.offsetParent)
812 while (obj.offsetParent)
814 curtop += obj.offsetTop;
815 obj = obj.offsetParent;
821 return {x:curleft, y:curtop};
833 // FADER PROTOTYPE _____________________________________________
837 if (typeof(_b.Fader) == "undefined")
844 _b.Fader = function (ele, from, to, fadetime, callback)
856 this.nDur = fadetime;
862 this.nID = setInterval(function() { p._fade() }, this.nInt);
868 _b.Fader.prototype._fade = function()
870 this.nTime += this.nInt;
872 var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
875 if (this.e.filters) // internet explorer
879 this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
881 // If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
882 this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
885 else // other browsers
887 this.e.style.opacity = op;
891 if (this.nTime == this.nDur)
893 clearInterval( this.nID );
894 if (this.cb != undefined)
901 _b.Fader.prototype._tween = function(t,b,c,d)
903 return b + ( (c-b) * (t/d) );