Monday, April 25, 2005

Chris Justus clean code (and a little modified)

var submitted = false;
var _oldInputFieldValue = ""; // previous inputField value (set during call to google...)...
var _currentInputFieldValue= ""; // also inputField value
var G = "";
var _highlightedSuggestionIndex = -1; // currently hightlighted suggestion index
var _highlightedSuggestionDiv = null; // currently highlisted suggestion div...
var _completeDiv = null; // document.completeDiv
var _completeDivRows = -1; // completeDiv rows at time of keypress...
var _completeDivRows2 = 5; // initially 5? not sure difference between this and _completeDivRows...
var _completeDivList = null; // completeDiv div list at time of keypress
var _documentForm = null; // Form on html page...
var _inputField = null; // Input field on form...
var _cursorUpDownPressed = false;
var _resultCache = new Object(); // This is a cache of results from google...
var leftRightBorderWidth = 1;
var topBottomBorderWidth = 1;
var _hasXMLHTTP = false; // Gets set to true if XMLHTTP Supported
var _xmlHttp = null; // This is the XMLHttp Object...
var _completeSearchString = null; // Gets set to "/complete/search"
var _completeSearchEnString = null; // Gets set to "/complete/search/?hl=en"
var _completeFrame = null;
var _timeoutAdjustment = 0; // timeout adjustment... gets adjusted over time...
var firstInit = true;

InstallAC = function(form, field) {
_documentForm = form;
_inputField = field;
installACPartTwo();
}
;

function installACPartTwo() {
if(firstInit) {
if(getXMLHTTP()) {
_hasXMLHTTP = true;
}
else {
_hasXMLHTTP = false;
}

_completeSearchString = "/complete/search";
_completeSearchEnString = _completeSearchString + "?hl=" + escapeURI("en");

if(!_hasXMLHTTP) {
document.cookie = "qu="+(_completeSearchString?";path="+_completeSearchString:"");
}
}

_documentForm.onsubmit = Fa;
_inputField.onsubmit = Fa;
_inputField.autocomplete = "off";
_inputField.onblur = onBlurHandler;
if(_inputField.createTextRange) {
_inputField.onkeyup = new Function("return onKeyUpHandler(event);");
}
else {
_inputField.onkeyup = onKeyUpHandler;
}
_currentInputFieldValue = _inputField.value;
_oldInputFieldValue = _currentInputFieldValue;
if(firstInit) {
_completeDiv = document.createElement("DIV");
_completeDiv.id = "completeDiv";
_completeDiv.style.borderRight = "black " + leftRightBorderWidth + "px solid";
_completeDiv.style.borderLeft = "black " + leftRightBorderWidth + "px solid";
_completeDiv.style.borderTop = "black " + topBottomBorderWidth + "px solid";
_completeDiv.style.borderBottom = "black " + topBottomBorderWidth + "px solid";
_completeDiv.style.zIndex = "1";
_completeDiv.style.paddingRight = "0";
_completeDiv.style.paddingLeft = "0";
_completeDiv.style.paddingTop = "0";
_completeDiv.style.paddingBottom = "0";
document.body.appendChild(_completeDiv);
cacheResults("",new Array());
var s = document.createElement("DIV");
s.style.visibility="hidden";
s.style.position="absolute";
s.style.left="-10000";
s.style.top="-10000";
s.style.width="0";
s.style.height="0";
var M = document.createElement("IFRAME");
M.completeDiv = _completeDiv;
M.name = "completionFrame";
M.id = "completionFrame";
M.src = _completeSearchEnString;
// the following lines are for covering dropdownlists behind div (IE zindex bug)
M.style.display = "block";
M.style.position = "absolute";
M.style.frameBorder = "0";
M.scrolling = "no";
s.appendChild(M);
document.body.appendChild(s);
document.body.appendChild(M);
if(frames && frames["completionFrame"] && frames["completionFrame"].frameElement) {
_completeFrame=frames["completionFrame"].frameElement;
}
else {
_completeFrame=document.getElementById("completionFrame");
}
window.onresize = setCompleteDivSize;
document.onkeydown = keyDownHandler;
}
setCompleteDivSize();
_completeFrame.style.visibility = "hidden";
_completeDiv.style.visibility = "hidden";
_completeDiv.style.position = "absolute";
_completeDiv.style.backgroundColor = "white";
setStyleForElement(_completeDiv,"mAutoComplete")
firstInit = false;
}

function keyDownHandler(event) {
if(!event && window.event) {
event = window.event;
}
// We are backspacing here...
if(event && event.keyCode == 8) {
if(event.srcElement == _inputField && positionOfSelectionStart(_inputField) == 0 && lengthOfSelection(_inputField) == 0) {
if(_inputField.createTextRange) {
var t = _inputField.createTextRange();
t.moveStart("character", _inputField.value.length);
t.select();
}
else if(_inputField.setSelectionRange) {
_inputField.setSelectionRange(_inputField.value.length, _inputField.value.length)
}
event.cancelBubble = true;
event.returnValue = false;
return false;
}
}
}

function setCompleteDivSize() {
if(_completeDiv) {
_completeDiv.style.left = calculateOffset(_inputField, "offsetLeft") + "px";
_completeDiv.style.top = calculateOffset(_inputField, "offsetTop") + _inputField.offsetHeight - 1 + "px";
_completeDiv.style.width = calculateWidth() + "px";
if(_completeFrame) {
_completeFrame.style.left = _completeDiv.style.left;
_completeFrame.style.top = _completeDiv.style.top;
_completeFrame.style.width = _completeDiv.style.width;
}
}
}

function calculateOffset(r, attr) {
var kb = 0;
while(r) {
kb += r[attr];
r = r.offsetParent;
}
return kb;
}

// calculate width of inputField... Note browser specific adjustments...
function calculateWidth() {
if(navigator && navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
return _inputField.offsetWidth - leftRightBorderWidth * 2
}
else {
return _inputField.offsetWidth;
}
}

function onBlurHandler(event) {
if(!event && window.event) {
event = window.event;
}
if(!_cursorUpDownPressed) {
hideCompleteDiv();
}
_cursorUpDownPressed = false;
}

onKeyUpHandler=function(e) {
// 38 is up cursor key, 40 is down cursor key...
if(e.keyCode == 40 || e.keyCode == 38) {
_cursorUpDownPressed = true;
_inputField.blur();
setTimeout("_inputField.focus();",10);
return;
}
var N = lengthOfSelection(_inputField);
var v = positionOfSelectionStart(_inputField);
var V = _inputField.value;
if(e.keyCode != 0) {
if(N > 0 && v != -1) {
V = V.substring(0, v);
}
if(e.keyCode == 13 || e.keyCode == 3) {
var d = _inputField;
if(d.createTextRange) {
var t = d.createTextRange();
t.moveStart("character", d.value.length);
t.select();
}
else if (d.setSelectionRange) {
d.setSelectionRange(d.value.length, d.value.length);
}
}
else {
if(_inputField.value != V) {
_inputField.value = V;
}
}
}
_currentInputFieldValue = V;
if(e.keyCode == 40) { // cursor up
highlightNewValue(_highlightedSuggestionIndex + 1);
}
else if(e.keyCode == 38) { // cursor down
highlightNewValue(_highlightedSuggestionIndex - 1);
}
else if(e.keyCode != 13 && e.keyCode != 3 && e.keyCode != 0){ // if not enter
loadDiv(_completeDiv);
}
}
;

// Return null if i undefined...
// otherwise return value of span (c|d)AutoComplete...
function valueOfAutoComplete(i, type) {
if(!i) {
return null;
}
var ga = i.getElementsByTagName("span");
if(ga) {
for(var f = 0; f < ga.length; ++f) {
if(ga[f].className == type) {
var value = ga[f].innerHTML;
if(value==" ") {
return "";
}
else {
// strip CR from string...
for(var f = 0, fFinal = "", cr = "\n\r"; f < value.length; f++) {
if(cr.indexOf(value.charAt(f))==-1) {
fFinal += value.charAt(f);
} else {
fFinal += " ";
}
}
return fFinal;
}
}
}
}
else {
return "";
}
}

function hideCompleteDiv() {
document.getElementById("completeDiv").style.visibility = "hidden";
document.getElementById("completionFrame").style.visibility = "hidden";
}

function showCompleteDiv() {
document.getElementById("completeDiv").style.visibility = "visible";
document.getElementById("completionFrame").style.visibility = "visible";
setCompleteDivSize()
}

// This is a result caching mechanism...
function cacheResults(is, cs){
_resultCache[is] = cs;
}

// We get the following javascript code dynamically returned from google:
// sendRPCDone(frameElement, "fast bug", new Array("fast bug track", "fast bugs", "fast bug", "fast bugtrack"), new Array("793,000 results", "2,040,000 results", "6,000,000 results", "7,910 results"), new Array(""));
sendRPCDone = function(fr, is, cs) { //,ds,pr) {
if(_timeoutAdjustment > 0) {
_timeoutAdjustment--;
}
if(!fr) {
fr = _completeFrame;
}
cacheResults(is, cs);
var b = fr.completeDiv;
b.completeStrings = cs;
//b.displayStrings = ds;
//b.prefixStrings = pr;
while(b.childNodes.length > 0) {
b.removeChild(b.childNodes[0]);
}
// For each element in our list, we create:
//

//
//
// bug tracking
//

//
// 500,000 results
//

//

//

for(var f = 0; f < b.completeStrings.length; ++f) {
var u = document.createElement("DIV");
setStyleForElement(u, "aAutoComplete");
u.onmousedown = mouseDownHandle;
u.onmouseover = mouseOverHandle;
u.onmouseout = mouseOutHandle;
var ka = document.createElement("SPAN");
setStyleForElement(ka,"lAutoComplete");
var ua = document.createElement("SPAN");
setStyleForElement(ua,"cAutoComplete");
ua.innerHTML = b.completeStrings[f]; // the text for the suggested result...
//var ea = document.createElement("SPAN");
//setStyleForElement(ea,"dAutoComplete");
//ea.innerHTML = b.displayStrings[f]; // the text for # results for suggested result...
//u.displaySpan = ea;
u.displaySpan = ua; // Eyal's change
ka.appendChild(ua);
//ka.appendChild(ea);
u.appendChild(ka);
b.appendChild(u);
}
loadDiv(b);
if(_completeDivRows2 > 0) {
b.height = 16 * _completeDivRows2 + 4;
fr.style.height = b.height;
}
else {
hideCompleteDiv();
}
}

function Fa() {
submitted = true;
if(!_hasXMLHTTP) {
document.cookie = "qu="+(_completeSearchString?";path="+_completeSearchString:"");
}
hideCompleteDiv();
//_documentForm.submit();
return true;
}

function escapeURI(URI) {
if(encodeURIComponent) {
return encodeURIComponent(URI);
}
if(escape) {
return escape(URI);
}
}

function recalculateTimeout(timeoutAdjustment) {
var H = 100;
for(var o = 1; o <= (timeoutAdjustment-2)/2; o++) {
H = H * 2;
}
return H + 50;
}

// This function sets itself up and gets called over and over (timeout driven)
mainLoop = function() {
if(_oldInputFieldValue != _currentInputFieldValue) {
if(!submitted) {
var formattedCurrentInputFieldValue = escapeURI(_currentInputFieldValue);
var ma = _resultCache[_currentInputFieldValue];
if(ma) {
// Found in our cache...
sendRPCDone(_completeFrame, _currentInputFieldValue, ma);
}
else {
_timeoutAdjustment++;
if(_hasXMLHTTP) {
// This function uses the xmlHttp object to send a message back to google...
// This is the primary function that dynamically communicates with google.
// This is the call:
// http://www.google.com/complete/search?hl=en&js=true&qu=fast%20bug
// And we get back:
// sendRPCDone(frameElement, "fast bug", new Array("fast bug track", "fast bugs", "fast bug", "fast bugtrack"), new Array("793,000 results", "2,040,000 results", "6,000,000 results", "7,910 results"), new Array(""));
if(_xmlHttp && _xmlHttp.readyState != 0) {
_xmlHttp.abort();
}
_xmlHttp=getXMLHTTP();
if(_xmlHttp) {
// We end up calling:
// /complete/search?hl=en&js=true&qu= ...
_xmlHttp.open("GET","http://localhost/STARSeating/PersonHint.aspx?qu="+formattedCurrentInputFieldValue,true);
// Note that this function will ONLY be called when we get a complete
// response back from google!!
_xmlHttp.onreadystatechange = function() {
if(_xmlHttp.readyState == 4) {
if(_xmlHttp.responseText) {
//alert(_xmlHttp.responseText);
if(_xmlHttp.responseText.charAt(0) == "<") {
_timeoutAdjustment--;
}
else {
// The response text gets executed as javascript...
eval(_xmlHttp.responseText);
}
}
else {
//alert("LDAP didn't return results: " + _xmlHttp.statusText);
}
}
}
;
// EYAL DON'T FORGET ABOUT THIS
// DON'T TRY TO TALK WHEN WE'RE LOCAL...
// Comment out when running from a local file...
_xmlHttp.send(null);
}
}
else {
document.cookie = "qu="+formattedCurrentInputFieldValue+(_completeSearchString?";path="+_completeSearchString:"");
frames["completionFrame"].document.location.reload(true);
}
}
_inputField.focus();
}
submitted = false;
}
_oldInputFieldValue = _currentInputFieldValue;
setTimeout("mainLoop()", recalculateTimeout(_timeoutAdjustment));
return true;
}
;
// Call mainLoop() after 10 milliseconds...
setTimeout("mainLoop()", 10);

// This is onMouseDown function...
var mouseDownHandle = function() {
_inputField.value = valueOfAutoComplete(this, "cAutoComplete");
Fa();
}
;

// on mouseover...
var mouseOverHandle = function() {
if(_highlightedSuggestionDiv) {
setStyleForElement(_highlightedSuggestionDiv,"aAutoComplete");
}
setStyleForElement(this,"bAutoComplete");
}
;

// On Mouse out...
var mouseOutHandle = function() {
setStyleForElement(this,"aAutoComplete")
}
;

// Called when cursor up/down pressed... selects new entry in completeDiv...
function highlightNewValue(C) {
_currentInputFieldValue = G;
_inputField.value = G;
if(!_completeDivList || _completeDivRows <= 0) {
return;
}
showCompleteDiv();
if(C >= _completeDivRows) {
C = _completeDivRows - 1;
}
if(_highlightedSuggestionIndex != -1 && C != _highlightedSuggestionIndex) {
setStyleForElement(_highlightedSuggestionDiv, "aAutoComplete");
_highlightedSuggestionIndex = -1;
}
if(C < 0) {
_highlightedSuggestionIndex = -1;
_inputField.focus();
return;
}
_highlightedSuggestionIndex = C;
_highlightedSuggestionDiv = _completeDivList.item(C);
setStyleForElement(_highlightedSuggestionDiv, "bAutoComplete");
_inputField.value = valueOfAutoComplete(_highlightedSuggestionDiv, "cAutoComplete");
}

function loadDiv(localCompleteDiv) {
var localInputField = _inputField;
// This becomes the rows in our suggestion list...
_completeDivList = localCompleteDiv.getElementsByTagName("div");
// # of rows in list...
_completeDivRows = _completeDivList.length;
_completeDivRows2 = _completeDivList.length;
G = _currentInputFieldValue;
if(_currentInputFieldValue == "" || _completeDivList.length == 0) {
hideCompleteDiv()
} else {
showCompleteDiv()
}
for(var f = 0; f < _completeDivList.length; f++) {
setStyleForElement(_completeDivList.item(f), "aAutoComplete");
}
_highlightedSuggestionIndex = -1;
_highlightedSuggestionDiv = null
}

function lengthOfSelection(n) {
var v = -1;
if(n.createTextRange) {
var fa = document.selection.createRange().duplicate();
v = fa.text.length;
}
else if(n.setSelectionRange) {
v = n.selectionEnd - n.selectionStart;
}
return v;
}

function positionOfSelectionStart(n) {
var v = -1;
if(n.createTextRange) {
var fa = document.selection.createRange().duplicate();
fa.moveEnd("textedit", 1);
v = n.value.length - fa.text.length;
}
else if(n.setSelectionRange) {
v = n.selectionStart;
}
return v;
}

function setStyleForElement(element, name) {
var Sa=calculateWidth();
var spanRefWidth = (Sa-110)/Sa*100;
element.className = name;
switch(name.charAt(0)) {
case "m":
element.style.fontSize="13px";
element.style.fontFamily="arial,sans-serif";
element.style.wordWrap="break-word";
break;
case "l":
element.style.display="block";
element.style.paddingLeft="3";
element.style.paddingRight="3";
element.style.height="16px";
element.style.overflow="hidden";
break;
case "a":
element.style.backgroundColor="white";
element.style.color="black";
if(element.displaySpan) {
element.displaySpan.style.color="green";
}
break;
case "b":
element.style.backgroundColor="#3366cc";
element.style.color="white";
if(element.displaySpan) {
element.displaySpan.style.color="white";
}
break;
case "c":
element.style.width=spanRefWidth+"%";
element.style.cssFloat="left";
break;
case "d":
element.style.cssFloat="right";
element.style.width=100-spanRefWidth+"%";
element.style.fontSize="10px";
element.style.textAlign="right";
element.style.color="green";
element.style.paddingTop="3px"
break;
}
}

function getXMLHTTP() {
var xmlHttpObj = null;
try{
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(err) {
try {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
} catch(err2) {
xmlHttpObj = null;
}
}
if(!xmlHttpObj && typeof XMLHttpRequest != "undefined") {
xmlHttpObj = new XMLHttpRequest();
}
return xmlHttpObj;
}

0 Comments:

Post a Comment

<< Home