Event.observe(window, 'load', init, false);

var pos = new Array(2);//coordinates: left, top

function init() {
	$('submit').style.display = 'none';
	Event.observe('query', 'keyup', listtitles, false);
	
	var inputbox = document.getElementById('query');//Please refer to an element with attribute id="query"
	setNodeAttribute(inputbox, "autocomplete", "off");//Disable automatic completion from the browser
	pos = findPos(inputbox);//Save relative position in global var
	document.getElementById('target').style.visibility = "hidden";
	document.getElementById('target').style.left = pos[0] + "px";
	document.getElementById('target').style.top = inputbox.offsetHeight + pos[1] + "px";
	document.getElementById('target').style.width = (inputbox.offsetWidth - 2) + "px";//Or use *.style.pixelWidth;
}

function listtitles() {
	var url = 'mtitles.xml';
	var params = 'q='+escape($F('query'));
	var target = 'target';
	var myAjax = new Ajax.Updater(target, url, { method: 'get', parameters: params });
	//if (document.getElementById('query').value.length > 1)
		document.getElementById('target').style.visibility = "visible";
	//}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}

function popAlert() {
// For debugging purposes
	window.alert("Left: " + pos[0] + " Top: " + pos[1]);
	window.alert("Width: " + document.getElementById('query').offsetWidth);
//	var noPx = document.childNodes ? 'px' : 0;
}

/*
This works using the form id (fff) to disable autocomplete for all fields, 
or using individual ids of inputs (like sensitivedata)

<body onload="disableAutoComplete('sensitivedata');"> 
 <form action="#" method="get" id="fff"> 
  <div> 
   <input type="text" name="sensitivedata" id="sensitivedata"> 
   <input type="text" name="notsensitive" id="notsensitive"> 
   <input type="submit" name="submit" value="Submit"> 
  </div> 
 </form> 
</body> 
</html>
*/

function setNodeAttribute(nodeObj, attrName, attrVal) {
// No sanity checks here. Verify nodeObj before calling this.
// TODO: valid sanity checking of nodeObj
//	if (!nodeObj) {
		var attributeNode = nodeObj.getAttributeNode(attrName);
		if (attributeNode) {
			attributeNode.value = attrVal;
		} else {
			nodeObj.setAttribute(attrName, attrVal);
		}
//	}
}

function disableAutoComplete(idref) {
	var obj = document.getElementById(idref);
	if (!obj) return;
	setNodeAttribute(obj, "autocomplete", "off");
}

