var OpenBookmarksInNewTab = {
	init : function()
	{
		if (!('PlacesUIUtils' in window))
			return;

		if (!PlacesUIUtils.__openbookmarkintab__done) {
			eval('PlacesUIUtils.openNodeWithEvent = '+
				PlacesUIUtils.openNodeWithEvent.toSource().replace(
					/(([^\s]*)whereToOpenLink\(aEvent\))/,
					'OpenBookmarksInNewTab.convertWhereToOpenLink($1, null, aNode)'
				)
			);

			eval('PlacesUIUtils._openTabset = '+
				PlacesUIUtils._openTabset.toSource().replace(
					'if (where == "window") {',
					<![CDATA[
						where = browserWindow.OpenBookmarksInNewTab.convertWhereToOpenLink(where, aEvent, null, urls);
						$&
					]]>
				)
			);

			PlacesUIUtils.__openbookmarkintab__done = true;
		}

		document.getElementById('placesContext_open').removeAttribute('default');
		document.getElementById('placesContext_open:newtab').setAttribute('default', true);
	},

	convertWhereToOpenLink : function(aWhere, aEvent, aNode, urls)
	{
		var currentTab = gBrowser.getBrowserAtIndex(gBrowser.mTabContainer.selectedIndex);
		if ( currentTab.currentURI.spec == "about:blank" || currentTab.currentURI.spec == "about:ntab")
		{
			return aWhere;
		}
		if(aNode != null && currentTab.currentURI.spec == aNode.uri)
		{
			return aWhere;
		}
		var homepage_urls = gHomeButton.getHomePage().split("|");
		for( var i = 0; i < homepage_urls.length; ++i )
		{
			if( currentTab.currentURI.equals( makeURI( homepage_urls[i] ) ) )
			{
				return aWhere;		
			}				
		}
		return 'tab' ;
	},

	handleEvent : function(aEvent)
	{
		switch (aEvent.type)
		{
			case 'load':
				window.removeEventListener('load', this, false);
				this.init();
				return;
		}
	}
};

window.addEventListener('load', OpenBookmarksInNewTab, false);
