// ==UserScript==
// @name           Scroll Search Engines
// @namespace      http://www.xuldev.org/
// @description    Scrolling mouse wheel on 'Search <engine> for <selection>' menu to change the engine.
// @include        main
// @compatibility  Firefox 3.0, 3.5, 3.6b4
// @author         Gomita
// @version        1.0.20080201
// @homepage       http://www.xuldev.org/misc/ucjs.php
// @note           Does not work if you don't place the search bar.
// ==/UserScript==

(function() {
	var searchMenu = document.getElementById("context-searchselect");
	searchMenu.className = "menuitem-iconic";
	// update icon when opening context menu
	document.getElementById("contentAreaContextMenu").addEventListener("popupshowing", function(event) {
		if (!gContextMenu || !gContextMenu.isTextSelected)
			return;
		var ss = Cc["@mozilla.org/browser/search-service;1"]
		         .getService(Ci.nsIBrowserSearchService);
		var engine = document.getElementById("searchbar") ? 
		             ss.currentEngine : ss.defaultEngine;
		if (engine.iconURI)
			document.getElementById("context-searchselect").setAttribute("src", engine.iconURI.spec);
	}, false);
	// enable to change the engine with scroll wheel
	searchMenu.addEventListener("DOMMouseScroll", function(event) {
		var searchBar = document.getElementById("searchbar");
		if (!searchBar)
			return;
		searchBar.selectEngine(event, event.detail > 0);
		// update label
		var menu = event.originalTarget;
		var label = gNavigatorBundle.getFormattedString(
			"contextMenuSearchText",
			[searchBar.currentEngine.name, getBrowserSelection(16)]
		);
		menu.setAttribute("label", label);
		// update icon
		var iconURI = searchBar.currentEngine.iconURI;
		if (iconURI)
			menu.setAttribute("src", iconURI.spec);
		else
			menu.removeAttribute("src");
	}, false);
	// enables to search with middle-click on menu
	searchMenu.addEventListener("click", function(event) {
		if (event.button == 1) {
			event.target.doCommand();
			event.target.parentNode.hidePopup();
		}
	}, false);
}());
