/** Dynamic XMLHttp lookups based on Google Suggest XMLRPC code. See: http://serversideguy.blogspot.com/2004/12/google-suggest-dissected.html http://www.fastbugtrack.com/misc/google/ac.js http://www.google.com/webhp?complete=1&hl=en This has been rewritten by SLF to use the prototype library. */ var queryField; var hidField; var selectedField; var divName; var ifName; var lastVal = ""; var lastPid = ""; var val = ""; var pid = ""; var lastKey; var cache = new Object(); var currentWidgets = new Object(); var lastWidgets = new Object(); // We do a little trick here to keep users from overtyping in our text // box. When a user is typing and we find only one matching search, // we autocomplete the box and then set the maxlength equal to the // length of the person's name. When the user does something to blank // out this result we return the maxlength back to the default set // here. IE has a bug that does not allow you to set maxlength // attributes for text boxes, so we have a hack here for defaultMaxLength. var defaultMaxLength = 55; var overallMaxLength = defaultMaxLength; var searching = false; var globalDiv; var divFormatted = false; var DIV_BG_COLOR = "#eeeeee"; var DIV_COLOR = "#000000"; var DIV_HIGHLIGHT_BGCOLOR = "#000000"; var DIV_HIGHLIGHT_COLOR = "#EEEEEE"; function resetInputMaxLength(el) { overallMaxLength = defaultMaxLength; el.setAttribute('maxlength', defaultMaxLength); // alert ('overall:' + overallMaxLength + // ' default:' + defaultMaxLength + // ' el: ' + el.value); } function getSel() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); } else if (document.selection) { txt = document.selection.createRange().text; } else return ''; return txt; } /**********************************************************************************/ /** This is the function that monitors the queryField, and calls the lookup functions when the queryField value changes. It also checks on other div elements to see if we have had any changes and need to update the output div. */ /**********************************************************************************/ mainLoop = function() { // Get the current value in the player name form box. val = escape(queryField.value); // if the field value has changed and we're not currently waiting for // a lookup result to be returned, do a lookup (or use the cache, if // we can) if(lastVal != val && searching == false){ var cacheResult = cache[val]; if (cacheResult) parseQueryInfo(val, cacheResult[0], cacheResult[1], cacheResult[2], cacheResult[0].length); else doRemoteQuery(val); lastVal = val; } setTimeout("mainLoop()", 100); return true; } ; /** parseQueryInfo This handles the arrays and determines how many results there are for this choice. If there are none or more than one we showQueryDiv. Otherwise we have only one selection we need to worry about. **/ function parseQueryInfo (queryString, resultArray1, resultArray2, resultArray3, resultsFound) { // Check to see how many results we have here. if ((resultsFound == 0) || (resultsFound > 1) || (lastKey == Event.KEY_BACKSPACE)) { hidField.value = ''; overallMaxLength = defaultMaxLength; queryField.setAttribute('maxlength', defaultMaxLength); showQueryDiv(queryString, resultArray1, resultArray2, resultArray3); if (selectedField) { selectedField.innerHTML = 'No unique player selected.'; selectedField.style.backgroundColor = '#ff9'; } } else { // Only one result, so we don't need the user to select anything. // Kill the selection div showDiv(false); // Enter the single id into the id form area. hidField.value = resultArray3[0]; queryField.value = resultArray1[0]; overallMaxLength = queryField.value.length; queryField.setAttribute('maxlength', queryField.value.length); if (selectedField) { selectedField.innerHTML = resultArray3[0] + ' selected.'; selectedField.style.backgroundColor = '#fff'; } // run the report. } } /** The InitQueryCode function should be called by the event, passing at least the queryFieldName and lookupURLPrefix parameters, where: queryFieldName = the name of the form field we're using for lookups hiddenFieldName = the div into which we stuff the player id for later use. For example: The above example will monitor the input box called "lookupField" on this page, and when it changes the contents of the field will be passed to lookupserver like: http://lookupserver/QueryHandler?q=fieldValue The http://lookupserver/QueryHandler will be expected to return a text response with a single line of text that calls the showQueryDiv function, in a format like: showQueryDiv("smi", new Array("John Smith", "Mary Smith"), new Array("555-1212", "555-1234")); */ function InitQueryCode (queryFieldName, hiddenFieldName, selectedFieldName) { queryField = $(queryFieldName); queryField.value = ""; queryField.focus(); queryField.onblur = hideDiv; queryField.onkeydown = keypressHandler; // for some reason, Firefox 1.0 doesn't allow us to set autocomplete to off // this way, so you should manually set autocomplete="off" in the input tag // if you can -- we'll try to set it here in case you forget queryField.setAttribute('autocomplete', 'off'); queryField.autocomplete = "off"; queryField.setAttribute('maxlength', defaultMaxLength); queryField.setAttribute('onmouseup', 'resetInputMaxLength(this);'); overallMaxLength = defaultMaxLength; hidField = $(hiddenFieldName); hidField.value = ''; if ($(selectedFieldName)) { selectedField = $(selectedFieldName); selectedField.style.backgroundColor = '#ff9'; selectedField.innerHTML = 'No unique player selected.'; } divName = "querydiv"; ifName = "queryiframe"; // alert(hidField.value + ":" + hidField + ":"); // add a blank value to the cache (so we don't try to do a lookup when the // field is empty) and start checking for changes to the input field addToCache("", new Array(), new Array(), new Array()); setTimeout("mainLoop()", 100); } /********************************************************************************/ /** This is a helper function that just adds results to our cache, to avoid repeat lookups. */ function addToCache (queryString, resultArray1, resultArray2, resultArray3) { cache[queryString] = new Array(resultArray1, resultArray2, resultArray3); } /********************************************************************************/ /** */ function currentWidgetsChange () { return false; } /** Get the
we're using to display the lookup results, and create the
if it doesn't already exist. */ function getDiv (divID) { if (!globalDiv) { // if the div doesn't exist on the page already, create it if (!document.getElementById(divID)) { var newNode = document.createElement("div"); newNode.setAttribute("id", divID); document.body.appendChild(newNode); } // set the globalDiv reference globalDiv = document.getElementById(divID); // figure out where the top corner of the div should be, based on the // bottom left corner of the input field var x = queryField.offsetLeft; var y = queryField.offsetTop + queryField.offsetHeight; var parent = queryField; while (parent.offsetParent) { parent = parent.offsetParent; x += parent.offsetLeft; y += parent.offsetTop; } // add some formatting to the div, if we haven't already if (!divFormatted) { globalDiv.style.backgroundColor = DIV_BG_COLOR; globalDiv.style.color = DIV_COLOR; globalDiv.style.fontFamily = "Verdana, Geneva, Arial, Helvetica, sans-serif"; globalDiv.style.padding = "4px"; globalDiv.style.border = "1px solid black"; globalDiv.style.fontSize = "90%"; globalDiv.style.position = "absolute"; globalDiv.style.left = x + "px"; globalDiv.style.top = y + "px"; globalDiv.style.visibility = "hidden"; globalDiv.style.zIndex = 10000; divFormatted = true; } } return globalDiv; } /** This is the function that should be returned by the XMLHTTP call. It will format and display the lookup results. */ function showQueryDiv (queryString, resultArray1, resultArray2, resultArray3) { var div = getDiv(divName); div.textAlign = "left"; // remove any results that are already there while (div.childNodes.length > 0) div.removeChild(div.childNodes[0]); // Add an admonishment to select something here. var result = document.createElement("div"); result.innerHTML = "Select a Player"; result.style.cursor = "pointer"; result.style.borderBottom = "1px solid #777777"; result.style.padding = "3px 0px 3px 0px"; _unhighlightResult(result); div.appendChild(result); // add an entry for each of the results in the resultArray for (var i = 0; i < resultArray1.length; i++) { // each result will be contained within its own div var result = document.createElement("div"); result.style.cursor = "pointer"; result.style.borderBottom = "1px solid #777777"; result.style.padding = "3px 0px 3px 0px"; _unhighlightResult(result); result.onmousedown = selectResult; result.onmouseover = highlightResult; result.onmouseout = unhighlightResult; var result1 = document.createElement("span"); result1.className = "result1"; result1.style.textAlign = "left"; result1.style.fontWeight = "bold"; result1.innerHTML = resultArray1[i]; var result2 = document.createElement("span"); result2.style.textAlign = "right"; result2.style.fontWeight = "normal"; result2.style.paddingLeft = "1em"; // result2.style.display = "none"; result2.innerHTML = resultArray2[i]; var result3 = document.createElement("span"); result3.className = "result3"; result3.style.textAlign = "right"; result3.style.fontWeight = "normal"; result3.style.paddingLeft = "1em"; // Element.hide(result3); result3.innerHTML = resultArray3[i]; result.appendChild(result1); result.appendChild(result2); result.appendChild(result3); div.appendChild(result); } // if this resultset isn't already in our cache, add it var isCached = cache[queryString]; if (!isCached) addToCache(queryString, resultArray1, resultArray2, resultArray3); // display the div if we had at least one result showDiv(resultArray1.length > 0); } /** This is called whenever the user clicks one of the lookup results. It puts the value of the result in the queryField and hides the lookup div. */ function selectResult() { _selectResult(this); } /** This actually fills the field with the selected result and hides the div. This is done this way because a mouseclick uses the onclick command, while a KEY_RETURN uses this command directly. */ function _selectResult(selectedDiv) { var selectedSpans = selectedDiv.getElementsByTagName("span"); if (selectedSpans) { for (var i = 0; i < selectedSpans.length; i++) { if (selectedSpans[i].className == "result1") { // Set the text box value to the desired result. queryField.value = selectedSpans[i].innerHTML; // Don't allow further typing in the input text box overallMaxLength = queryField.value.length; queryField.setAttribute('maxlength', queryField.value.length); } if (selectedSpans[i].className == "result3") { hidField.value = selectedSpans[i].innerHTML; if (selectedField) { selectedField.innerHTML = selectedSpans[i].innerHTML + ' selected.'; selectedField.style.backgroundColor = '#fff'; } } //alert(hidField.value + ":" + hidField + ":"); } // Set the player id div to the next spans value. lastVal = val = escape(queryField.value); searching = false; mainLoop(); showDiv(false); return; } } /** This is called when a user mouses over a lookup result */ function highlightResult() { _highlightResult(this); } /** This actually highlights the selected result */ function _highlightResult(item) { item.style.backgroundColor = DIV_HIGHLIGHT_BGCOLOR; item.style.color = DIV_HIGHLIGHT_COLOR; } /** This is called when a user mouses away from a lookup result */ function unhighlightResult() { _unhighlightResult(this); } /** This actually unhighlights the selected result */ function _unhighlightResult(item) { item.style.backgroundColor = DIV_BG_COLOR; item.style.color = DIV_COLOR; } /** This either shows or hides the lookup div, depending on the value of the "show" parameter. */ function showDiv (show) { var div = getDiv(divName); if (show) div.style.visibility = "visible"; else div.style.visibility = "hidden"; adjustiFrame(); } /** We originally used showDiv as the function that was called by the onBlur event of the field, but it turns out that Firefox will pass an event as the first parameter of the function, which would cause the div to always be visible. So onBlur now calls hideDiv instead. */ function hideDiv () { showDiv(false); } /** Use an "iFrame shim" to deal with problems where the lookup div shows up behind selection list elements, if they're below the queryField. The problem and solution are described at: http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx */ function adjustiFrame() { if (!document.getElementById(ifName)) { var newNode = document.createElement("iFrame"); newNode.setAttribute("id", ifName); newNode.setAttribute("src", "javascript:false;"); newNode.setAttribute("scrolling", "no"); newNode.setAttribute("frameborder", "0"); document.body.appendChild(newNode); } iFrameDiv = document.getElementById(ifName); var div = getDiv(divName); try { iFrameDiv.style.position = "absolute"; iFrameDiv.style.width = div.offsetWidth; iFrameDiv.style.height = div.offsetHeight; iFrameDiv.style.top = div.style.top; iFrameDiv.style.left = div.style.left; iFrameDiv.style.zIndex = div.style.zIndex - 1; iFrameDiv.style.visibility = div.style.visibility; } catch(e) { } } /** This actually sends the lookup request (as a URL with a query string) to a server in the background. When a response comes back from the server, the function attached to the onReadyStateChange event is fired off. */ function doRemoteQuery(queryString) { var url = '/ps_suggest.cgi'; searching = true; var newAjax = new Ajax.Request( url, { method: 'get', parameters: 'search=' + queryString + '&lim=10', onComplete: showResponse }); } // What we do when we get the response from the server. function showResponse(originalRequest) { searching = false; // This sets up the three arrays (name, pid, and years played) and // sets the value of the resultsFound // alert ('resultsFound ' + resultsFound); eval(originalRequest.responseText); parseQueryInfo(qt, resultNames, resultYears, resultIds,resultsFound); } /** This is the key handler function, for when a user presses the up arrow, down arrow, tab key, or enter key from the input field. */ function keypressHandler (evt) { // don't do anything if the div is hidden var largeDiv = getDiv(divName); // make sure we have a valid event variable if(!evt && window.event) { evt = window.event; } var key = evt.keyCode; lastKey = key; // Check to see if we should allow this key to be entered. // We allow it if the length of the field is shorter than the maxLength. // or if the key is a backspace key and the selection is not part if ((queryField.value.length >= overallMaxLength) && (key != Event.KEY_BACKSPACE) && (key != Event.KEY_TAB) && (key != Event.KEY_RETURN) && (getSel() == '')) { evt.cancelBubble = true; return false; } if (largeDiv.style.visibility == "hidden") return true; // In the case of a non-arrow key, carry on. if ((key != Event.KEY_UP) && (key != Event.KEY_DOWN) && (key != Event.KEY_RETURN) && (key != Event.KEY_TAB)) return true; // get the span that's currently selected, and perform an appropriate action var selNum = getSelectedSpanNum(largeDiv); var selSpan = setSelectedSpan(largeDiv, selNum); if ((key == Event.KEY_RETURN) || (key == Event.KEY_TAB)) { if (selSpan) _selectResult(selSpan); evt.cancelBubble=true; return false; } else { if (key == Event.KEY_UP) selSpan = setSelectedSpan(largeDiv, selNum - 1); if (key == Event.KEY_DOWN) selSpan = setSelectedSpan(largeDiv, selNum + 1); if (selSpan) _highlightResult(selSpan); } showDiv(true); return true; } /** Get the number of the result that's currently selected/highlighted (the first result is 0, the second is 1, etc.) The results appear in separate divs and this reads through all of the divs to find a matching one. */ function getSelectedSpanNum (div) { var count = -1; var resultDivs = div.getElementsByTagName("div"); if (resultDivs) { for (var i = 0; i < resultDivs.length; i++) { count++; if (resultDivs[i].style.backgroundColor != div.style.backgroundColor) return count; } } return -1; } /** Select/highlight the result at the given position */ function setSelectedSpan (div, spanNum) { var count = -1; var thisSpan; var spans = div.getElementsByTagName("div"); if (spans) { for (var i = 0; i < spans.length; i++) { if (++count == spanNum) { _highlightResult(spans[i]); thisSpan = spans[i]; } else { _unhighlightResult(spans[i]); } } } return thisSpan; }