/* The code in this file is designed to be called when an error occurs in
 *  the application.  Call the "NavigateTopLevelAndClose" function and pass
 *  it the name of the error page that you wish to navigate to.  It then
 *  ensures that the "_top" frame (of the parent page, if one exists) is
 *  navigated to the specified location.  It also closes the current window
 *  if it is a popup one.
 * 
 * This code does not handle popups of popups, it is designed to work based
 *  on the assumption that there will only ever be one level of popup window
 *  open at one time, and that popup windows will never have their own popup
 *  windows.
 */

// This function loops to locate the top level frame within this window...
function LocateTopFrame( win )
{
	// Variable storing the previous window, just incase we somehow end up with
	//  null as the 'win'.
	var prevWin;
	try
	{
		prevWin = win;
		while( win.location != win.parent.location )
		{
			win = win.parent;
		}
		return win;
	}
	catch(e)
	{
		if( win == null )
		{
			return prevWin;
		}
		else
		{
			return win;
		}
	}
}

// This function loops to locate the top level window of this window...
function LocateTopWindow( win )
{
	// Variable storing the previous window, just incase we somehow end up with
	//  null as the 'win'.
	var prevWin = win;
	try
	{
		while( win.opener != null && win.opener.closed == false )
		{
			win = win.opener;
		}
		return win;
	}
	catch(e)
	{
		if( win == null )
		{
			return prevWin;
		}
		else
		{
			return win;
		}
	}
}

// This function navigates the top level page to the specified destination
//  page and closes the current page if it is not the top level page...
void function NavigateTopLevelAndClose( destination )
{
	try
	{
		// Get executing windows top frame...
		var thisWin = LocateTopFrame( window );
		// Get that ones top window...
		var top = LocateTopWindow( thisWin );
		// Get that ones top frame...
		top = LocateTopFrame( top );

		// If the current url doesn't end with the destination url then navigate...
		if( top.location.pathname.substr( top.location.pathname.length-destination.length, destination.length) != destination )
			top.location.href = destination;
		if( top != thisWin )
			thisWin.close();
	}
	catch(e)
	{
		window.location.href = destination;
	}
}