/*
NSWorkspace: Open a URL in the background (10.2)
Original Source: <http://cocoa.karelia.com/AppKit_Categories/NSWorkspace__Open_a.m>
(See copyright notice at <http://cocoa.karelia.com>)
*/

/*" Attempt to open the given (web) URL, and complain if it couldn't be opened.
The in-background part of this code is adapted from some code that is
courtesy of Brent Simmons, Ranchero Software <http://www.ranchero.com/>

This method allows the user to retry the open if it failed; perhaps useful or not. The opening in background only
works for 10.2 and up, so if we're 10.1, just call the openURL method in NSWorkspace.
"*/

- (void)attemptToOpenWebURL:(NSURL *)inURL
{
BOOL retry = YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
while (retry)
{
BOOL success;
if ([defaults boolForKey:@"urls in background"] && (NSAppKitVersionNumber > NSAppKitVersionNumber10_1))
{
NSArray *urlsArray;
LSLaunchURLSpec urlSpec;

urlsArray = [NSArray arrayWithObject: [inURL absoluteURL]];

urlSpec.appURL = nil;
urlSpec.itemURLs = (CFArrayRef) urlsArray;
urlSpec.passThruParams = nil;

// This makes it stay in the background. Nil for regular behavior.
urlSpec.launchFlags = kLSLaunchDontSwitch;
// urlSpec.launchFlags = nil;

urlSpec.asyncRefCon = nil;

OSStatus status = LSOpenFromURLSpec (&urlSpec, nil);
success = (noErr == status);
}
else
{
success = [[NSWorkspace sharedWorkspace] openURL:[inURL absoluteURL]];
}

if (success)
{
retry = NO;
}
else
{
int button = NSRunCriticalAlertPanel(
NSLocalizedString(@"Unable to Open Web URL",@"Title of alert"),
NSLocalizedString(@"The following URL could not be opened:\n\n%@\n\nThis may be an invalid Web URL, or perhaps your Mac may not be configured properly to open Web URLs. (This is set in the System Preferences ÒInternetÓ section.) You can select and copy the URL above and paste it into your Web browser.",@"Message in alert"),
NSLocalizedString(@"Cancel",@""),
NSLocalizedString(@"Try Again",@""),
nil,
[inURL absoluteString]);

retry = (0 == button);
}
}
}