// ==UserScript==
// @name           浮动Google搜索栏
// @namespace      http://www.otchy.com/
// @include        http://www.google.*/search*
// @include        http://127.0.0.1:4664/search*
// ==/UserScript==

(function() {
	var xpath = '//table[@class="tb"]';
	var res = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
	if (!res.singleNodeValue) {
		xpath = '//table';
		res = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		if (!res.singleNodeValue) return;
	}
	var ele = res.singleNodeValue;
	document.body.style.marginTop = ele.offsetHeight+ 'px';
	ele.style.backgroundColor = '#fff';
	ele.style.position = 'absolute';
	ele.style.top = '0px';
	ele.id = 'query_form';
	setInterval(function() {
		var form = document.getElementById('query_form');
		var scroll = window.scrollY;
		var offset = form.offsetTop;
		if (scroll == offset) {
			form.style.opacity = 1;
			return;
		}
		var from = scroll > offset ? scroll : offset;
		var to = scroll > offset ? offset : scroll;
		var adjust = scroll > offset ? 0.5 : -0.5;
		var newOffset = Math.floor((from - to)*0.7 + adjust + to);
		form.style.opacity = 0.8;
		form.style.top = newOffset + 'px';
	}, 50);

	xpath = '//input[@name="q"]';
	res = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
	if (!res.singleNodeValue) return;
	ele = res.singleNodeValue;
	ele.id = 'query_string';
	document.body.addEventListener('dblclick', function (event) {
		document.getElementById('query_string').select();
	}, false);
})();
