// ==UserScript==
// @name Improve middle click
// @description Fixes middle-clicking in links with javascript uris, and links that open windows
// @author Joćo Eiras 
// @version 1.0
// @encoding utf-8
// ==/UserScript==
/*
	Copyright © 2007 by Joćo Eiras 

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/*

	History:

	1.0 in 20-02-2007:
	 - Initial release.
 
*/

(function( opera ){
	var overrideTarget = false;
	
	window.open = (function( wopen ){
		return function(){
			if( overrideTarget ){
				arguments[1] = '_blank';
				var nwin = wopen.apply(this,arguments);
				nwin.blur();
				return nwin;
			}else
				return wopen.apply(this,arguments);
		}
	})( window.open );
	
	function isJavascriptURIAttr(attr){
		return attr&&(/^javascript:/).test(attr.nodeType==2?attr.value:attr);
	};
	function getAncestorLink(node){
		return node&&node.ownerDocument.evaluate(
			'ancestor-or-self::*[name()="a" or name()="area"][1]',
			node,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
	};
	function linkClick(e){
		var target = e.currentTarget;
		if( e.button == 1 && isJavascriptURIAttr(target.___href_backup) ){
			try{
				eval('(function(event){'+target.___href_backup.value.substring(11)+
					'}).call(target,e.event)');
			}catch(ex){
				setTimeout(function(){throw ex;},1);
			}
			e.preventDefault();
		};
	};
	
	opera.addEventListener('BeforeEvent.mousedown',function(e){
		if( e.event.button == 1 ){
			var target = e.event.target;
			var anchor = getAncestorLink(target);
			if( anchor && isJavascriptURIAttr(anchor.href) ){
				anchor.___href_backup = anchor.attributes.href;
				anchor.removeAttribute('href');
				if(!anchor.__has_middle_click_ev){
					anchor.addEventListener('mousedown',linkClick,false);
					anchor.__has_middle_click_ev = true;
				}
				overrideTarget = true;
			}
		}
	},false);
	opera.addEventListener('AfterEvent.mousedown',function(e){
		if( e.event.button == 1 ){
			var target = e.event.target;
			var anchor = getAncestorLink(target);
			if( anchor && anchor.___href_backup ){
				setTimeout(function(){
					anchor.setAttributeNode(anchor.___href_backup);
					anchor['___href_backup'] = undefined;
				},1);
			}
			overrideTarget = false;
		}
	},false);

})( window.opera );
