/* **************************************************************************

  $Archive: /njcl_v2/src/com/novell/service/security/protocols/XplatProtocolProxyGUI.java $
  $Revision: 9 $
  $Modtime: 5/05/00 5:12p $

  Copyright (c) 1997 Novell, Inc.  All Rights Reserved.

  THIS WORK IS AN UNPUBLISHED WORK AND CONTAINS CONFIDENTIAL PROPRIETARY
  AND TRADE SECRET INFORMATION OF NOVELL, INC. ACCESS  TO  THIS  WORK IS
  RESTRICTED TO (I) NOVELL, INC.  EMPLOYEES WHO HAVE A NEED TO  KNOW HOW
  TO  PERFORM  TASKS WITHIN  THE SCOPE  OF  THEIR   ASSIGNMENTS AND (II)
  ENTITIES OTHER  THAN  NOVELL, INC.  WHO  HAVE ENTERED INTO APPROPRIATE
  LICENSE   AGREEMENTS.  NO  PART  OF  THIS WORK MAY BE USED, PRACTICED,
  PERFORMED COPIED, DISTRIBUTED, REVISED, MODIFIED, TRANSLATED, ABRIDGED,
  CONDENSED, EXPANDED, COLLECTED, COMPILED, LINKED,  RECAST, TRANSFORMED
  OR ADAPTED  WITHOUT THE PRIOR WRITTEN CONSENT OF NOVELL, INC.  ANY USE
  OR EXPLOITATION  OF  THIS WORK WITHOUT AUTHORIZATION COULD SUBJECT THE
  PERPETRATOR  TO CRIMINAL AND CIVIL LIABILITY.

****************************************************************************/

package com.novell.service.security.protocols;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.IOException;
import java.lang.StringBuffer;
import java.net.URL;
import java.util.*;

import javax.swing.*;
import javax.help.*;

import com.novell.java.lang.*;
import com.novell.java.security.*;
import com.novell.service.session.util.Debug;
import com.novell.service.security.*;
import com.novell.service.security.protocols.nls.I2L;
import com.novell.service.security.protocols.nls.LF;
import com.novell.service.session.*;

/** @internal
 * The Xplat authenticator protocol proxy.
 */
class XplatProtocolProxyGUI
   implements AuthenticatorProtocol
{
   // Always access debug via final static...hopefully a final static of
   // false will be optimized out by the compiler
   final static private boolean  DEBUG = false;

   private XplatProtocolProxy delegate;
   
   XplatProtocolProxyGUI(XplatProtocolProxy delegate)
   {
   		if (delegate != null)
			this.delegate = delegate;
		else throw new NullPointerException("Illegal Construction");
   }
	
   /**
    * configure the protocol
    */
   public void configure (
         Properties properties,
         String baseKey)
      throws ConfigurationException
   {
   }


   /**
    * set the channel for the protocol and identity
    */
   public void init (
         AuthenticatorChannel channel)
   {
   }

   public AuthenticatorChannel getChannel()
   {
      return null;
   }

   public Identity[] getIdentities(Identity in)
      throws AuthenticatorException
   {
   	 return delegate.getIdentities(in);
   }

   /**
    * perform the authentication protocol
    */
   public void login (Identity in)
      throws LoginException
   {
      try
      {
        JFrame frame;
        try
        {
           frame = new JFrame ();
        }
        catch (Throwable x)
        {
           throw new ConfigurationException (
              com.novell.java.security.I2L.getString (XMsg.JFC_IS_REQUIRED));
        }
	        BasicUserInterface ui = new LoginUserInterface (in,frame);
        ui.show ();
        if (!ui.isReady ())
           throw ui.getException ();
      }
      catch(AuthenticatorException x)
      {
         throw x;
      }
      catch (java.lang.Throwable x)
      {
         throw new LoginException(x);
      }
   }

	/**
	 * @deprecated See AuthenticatorProtocols for details...
	 */
   public void createTokens (
         Identity in)
      throws CreateTokensException
   {
   	  createTokens(in, in);
   }

   public void createTokens (
         Identity admin, Identity user)
      throws CreateTokensException
   {
      try
      {
            JFrame frame;
            try
            {
               frame = new JFrame();
            }
            catch(java.lang.Throwable x)
            {
               throw new ConfigurationException(
                  com.novell.java.security.I2L.getString(XMsg.JFC_IS_REQUIRED));
            }
            BasicUserInterface ui = new CreateTokensUserInterface(admin, user, frame);
            ui.show();
            if(!ui.isReady())
               throw ui.getException();
      }
      catch(AuthenticatorException x)
      {
         throw x;
      }
      catch (java.lang.Throwable x)
      {
         throw new CreateTokensException(x);
      }
   }

   public void verifyTokens (
         Identity in)
      throws VerifyTokensException
   {
      try
      {
            JFrame frame;
            try
            {
               frame = new JFrame();
            }
            catch(java.lang.Throwable x)
            {
               throw new ConfigurationException(
                  com.novell.java.security.I2L.getString(XMsg.JFC_IS_REQUIRED));
            }
            BasicUserInterface ui = new VerifyTokensUserInterface(in,frame);
            ui.show();
            if(!ui.isReady())
               throw ui.getException();
      }
      catch(AuthenticatorException x)
      {
         throw x;
      }
      catch (java.lang.Throwable x)
      {
         throw new VerifyTokensException(x);
      }
   }

   public void modifyTokens(Identity in)
      throws ModifyTokensException
   {
      try
      {
            JFrame frame;
            try
            {
               frame = new JFrame();
            }
            catch(java.lang.Throwable x)
            {
               throw new ConfigurationException(
                  com.novell.java.security.I2L.getString(XMsg.JFC_IS_REQUIRED));
            }
            BasicUserInterface ui = new ModifyTokensUserInterface(in,frame);
            ui.show();
            if(!ui.isReady())
               throw ui.getException();
      }
      catch(AuthenticatorException x)
      {
         throw x;
      }
      catch (java.lang.Throwable x)
      {
         throw new ModifyTokensException(x);
      }
   }

   public void logout(Identity in)
      throws LogoutException
   {
      try
      {
            JFrame frame;
            try
            {
               frame = new JFrame();
            }
            catch(java.lang.Throwable x)
            {
               throw new ConfigurationException(
                  com.novell.java.security.I2L.getString(XMsg.JFC_IS_REQUIRED));
            }
            BasicUserInterface ui = new LogoutUserInterface(in,frame);
            ui.show();
            if(!ui.isReady())
               throw ui.getException();
      }
      catch(AuthenticatorException x)
      {
         throw x;
      }
      catch (java.lang.Throwable x)
      {
         throw new LogoutException(x);
      }
   }

} // class XplatProtocolProxyGUI

//============================================================================
//                              GUI
//============================================================================

/**
 * BasicUserInterface
 */
abstract class BasicUserInterface
   extends JDialog
   implements  ActionListener, KeyListener, NameDomainPasswordReady
{
   String title = null;
   JFrame frame = null;
   JTabbedPane tabPane = null;

   JButton okayButton;
   JButton cancelButton;
   JButton helpButton;
   Thread currentThread;

	// This is specific to the subclass
	protected String helpId;
	String helpError;

   boolean isReady = true;
   AuthenticatorException exception;
   boolean removeDialog = true;

// htmlHelpFrame helpFrame;

   Identity identity;

   boolean firstTime = true;
   public BasicUserInterface(Identity identity,JFrame frame,String title)
   {
      super(frame,title,true);
      this.identity = identity;
      this.frame = frame;
      this.title = title;
 
      currentThread = Thread.currentThread();
      
      setResizable(false);
      Container content = getContentPane();

      tabPane = new JTabbedPane();
      tabPane.addKeyListener(this);

      tabPanels(identity);

      // tab panel
      final JPanel tabPanel = new JPanel(true);
//    tabPanel.setRequestFocusEnabled(true);
//    tabPanel.requestFocus();

      tabPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
      tabPanel.add(tabPane);

      okayButton = new JButton(I2L.getString(LF.OK));
//    okayButton.setMnemonic(I2L.getString(LF.OK_MNEMONIC).charAt(0));
//    okayButton.setToolTipText(I2L.getString(LF.OK_TOOLTIP));
      okayButton.addActionListener(this);
      okayButton.addKeyListener(this);

      cancelButton = new JButton(I2L.getString(LF.CANCEL));
//    cancelButton.setMnemonic(I2L.getString(LF.CANCEL_MNEMONIC).charAt(0));
//    cancelButton.setToolTipText(I2L.getString(LF.CANCEL_TOOLTIP));
      cancelButton.addActionListener(this);
      cancelButton.addKeyListener(this);

    // hide button until the help files are ready...
      helpButton = new JButton(I2L.getString(LF.HELP));
	  addHelpToButton(helpButton);
//    helpButton.setMnemonic(I2L.getString(LF.HELP_MNEMONIC).charAt(0));
//    helpButton.setToolTipText(I2L.getString(LF.HELP_TOOLTIP));
//    helpButton.addActionListener(this);
      helpButton.addKeyListener(this);
      resizeButtons(new JButton[] {okayButton, cancelButton, helpButton});

      // button panel
      JPanel buttonPanel = new JPanel(false);
      buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
      buttonPanel.add(okayButton);
      buttonPanel.add(cancelButton);
      buttonPanel.add(helpButton);

      // outer panel
      JPanel outerPanel = new JPanel(false);
      outerPanel.setLayout(new BoxLayout(outerPanel,BoxLayout.Y_AXIS));
      outerPanel.add(tabPanel);
      outerPanel.add(buttonPanel);


      // set the location of the dialog
      content.setLayout(new BoxLayout(content,BoxLayout.Y_AXIS));

      Dimension opSize = new BoxLayout(outerPanel,BoxLayout.Y_AXIS).preferredLayoutSize(outerPanel);
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      setLocation(screenSize.width/2 -    opSize.width/2,
                  screenSize.height/2 -   opSize.height/2);

      outerPanel.addKeyListener(this);

      content.add(outerPanel);

      addWindowListener(new WindowAdapter()
      {
         public void windowActivated(WindowEvent event)
         {
            if(firstTime)
            {
               ((BasePanel)(tabPane.getSelectedComponent())).getFirstFocusComponent().requestFocus();
               firstTime = false;
            }
         }

         public void windowClosing(WindowEvent event)
         {
            cancelPressed();
         }
      });
      pack();
   }

   public Dimension getPreferredSize()
   {
      Dimension d = super.getPreferredSize();

      Container content = getContentPane();

      // size so the full title is always shown + room for Java cup and X
      FontMetrics fm = content.getFontMetrics(content.getFont());
      int hSize = fm.stringWidth(getTitle()) + 50;

      if(hSize > d.width)
         d.width = hSize;

      content.setSize(d);

      return d;
   }

   public String getTitle()
   {
      return title;
   }

   /**
    * Set the size of the buttons equal to the preferred size of the largest
    */
   void resizeButtons(JButton[] buttons)
   {
      Dimension max = buttons[0].getPreferredSize();
      Dimension d;

      for (int i=1; i<buttons.length; i++) {
         d = buttons[i].getPreferredSize();
         if ((d.width > max.width) || (d.height > max.height))
            max = d;
      }

      for (int i=0; i<buttons.length; i++) {
         buttons[i].setPreferredSize(max);
      }
   }


   void tabPanels(Identity identity)
   {
   }

   public void actionPerformed(ActionEvent event)
   {
      Object src = event.getSource();
      if (src == okayButton) {
         Cursor old = getCursor();
         setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
         try {
            okayPressed ();
         }
         finally {
            setCursor(old);
         }
      }
      else if (src == cancelButton)
         cancelPressed ();
      else if(src == helpButton)
         helpPressed();
   }

   public void keyPressed(KeyEvent event)
   {
      switch(event.getKeyCode())
      {
      case KeyEvent.VK_ENTER:
         if(cancelButton.hasFocus())
            cancelButton.doClick();    // cancelPressed ();
         else if(helpButton.hasFocus())
            helpButton.doClick();    
         else // if(okayButton.hasFocus()) // This is the default
            okayButton.doClick();   // okayPressed ();
         break;
      case KeyEvent.VK_ESCAPE:
         cancelButton.doClick();    // cancelPressed ();
         break;
      //case KeyEvent.VK_TAB:
      	//if (okayButton
      default:
         break;
      }
   }

   public void keyReleased(KeyEvent event)
   {
   }

   public void keyTyped(KeyEvent event)
   {
   }

   /*
    * should be over-ridden to perform specific action
    */
   abstract void okayPressed ();

   /*
    * should be over-ridden to throw specific "CancelledException"
    */
   abstract void cancelPressed();

   void helpPressed() 
   {
		Point p = getLocation();
		Dimension d = getPreferredSize();
		p.x += d.width/2;
		p.y += d.height/2;

		ErrorOkDialog eod = new ErrorOkDialog (this,frame,I2L.getString(LF.HELP_ERROR_TITLE),helpError,p)
		{
		   void okayPressed ()
		   {
		      this.dispose ();
		   }
		};
		eod.pack ();
		eod.show ();
	}   

   void addHelpToButton(JButton helpButton) {
		try {
		URL hsURL = HelpSet.findHelpSet(null, "com/novell/service/security/protocols/help/novellauthenticator.hs");
		HelpSet hs = new HelpSet(null, hsURL);
		HelpBroker hb = hs.createHelpBroker();
		hb.enableHelpOnButton(helpButton, helpId, null);
		} catch (java.lang.Error ee) {
			//helpButton.setEnabled(false);
			helpError = I2L.getString(LF.HELP_ERROR_CLASS_NOT_FOUND);
			helpButton.addActionListener(this);
		} catch (java.lang.Exception ee) {
			//helpButton.setEnabled(false);
			helpError = I2L.getString(LF.HELP_ERROR_HELP_FILES_NOT_FOUND);
			helpButton.addActionListener(this);
		} catch (java.lang.Throwable ee) {
			//helpButton.setEnabled(false);
			helpError = I2L.getString(LF.HELP_ERROR_INITIALIZATION);
			helpButton.addActionListener(this);
		}
		return;
   }
   
   public String getName()
   {
      return ((NameDomainPasswordReady)tabPane.getSelectedComponent()).getName();
   }

   public String getDomain()
   {
      return ((NameDomainPasswordReady)tabPane.getSelectedComponent()).getDomain();
   }

   public Password getPassword()
   {
      return ((NameDomainPasswordReady)tabPane.getSelectedComponent()).getPassword();
   }

   public Password getNewPassword()
   {
      return ((NameDomainPasswordReady)tabPane.getSelectedComponent()).getNewPassword();
   }

   public boolean isReady()
   {
      return isReady;
   }

   public AuthenticatorException getException()
   {
      return exception;
   }

   abstract class ErrorOkDialog extends JDialog
   {
      JLabel label = null;
      JButton okayButton = new JButton(I2L.getString(LF.OK));

      JPanel panel = new JPanel();
      JPanel buttonPanel = new JPanel();
      Point location = null;
      BasicUserInterface dialog = null;

      public ErrorOkDialog(BasicUserInterface dialog,JFrame frame, String title, String message, Point location)
      {
         super(frame,title,true);
         this.dialog = dialog;
         this.location = location;
         this.label = new JLabel(message);

         buttonPanel.add(okayButton);

         okayButton.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               okayPressed ();
            }
         });

         this.addKeyListener(new KeyAdapter()
         {
            public void keyPressed(KeyEvent event)
            {
               switch(event.getKeyCode())
               {
               case KeyEvent.VK_ENTER:
               case KeyEvent.VK_ESCAPE:
                  okayButton.doClick();
               }
            }

            public void keyReleased(KeyEvent event)
            {
            }

            public void keyTyped(KeyEvent event)
            {
            }
         });

//       addButtons();

         // find max width of title and message
         FontMetrics fm = label.getFontMetrics(label.getFont());
         int width = Math.max(fm.stringWidth(title)+20,fm.stringWidth(message)+10);

         // layout panel
         panel.add(label);
         panel.add(buttonPanel);
         getContentPane().add(panel);
         panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
         Dimension opSize = new BoxLayout(panel,BoxLayout.Y_AXIS).preferredLayoutSize(panel);

         // find max width of panel and previously calculated width
         width = Math.max(opSize.width,width);
         Dimension d = new Dimension(width,opSize.height);

         // set the preferred size
         label.setPreferredSize(d);

         // set location
         setLocation(location.x - d.width/2, location.y - d.height/2);
      }

      void addButtons()
      {
      }

      abstract void okayPressed ();
   }

   abstract class ErrorOkCancelDialog extends ErrorOkDialog
   {
      JButton cancelButton = null;
      public ErrorOkCancelDialog(BasicUserInterface dialog, JFrame frame, String title, String message, Point location)
      {
         super(dialog,frame,title,message,location);

         cancelButton = new JButton(I2L.getString(LF.CANCEL));
         buttonPanel.add(cancelButton);

         cancelButton.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               cancelPressed();
            }
         });

         cancelButton.addKeyListener(new KeyAdapter()
         {
            public void keyPressed(KeyEvent event)
            {
               switch(event.getKeyCode())
               {
               case KeyEvent.VK_ENTER:
               case KeyEvent.VK_ESCAPE:
                  cancelButton.doClick();
               }
            }

            public void keyReleased(KeyEvent event)
            {
            }

            public void keyTyped(KeyEvent event)
            {
            }
         });
      }

      // called in the super constructor
      void addButtons()
      {
         cancelButton = new JButton(I2L.getString(LF.CANCEL));
         buttonPanel.add(cancelButton);
      }

      abstract void cancelPressed();
   }
} // class BasicUserInterface

/**
 * LoginUserInterface
 */
class LoginUserInterface
   extends BasicUserInterface
{
//   boolean ldap = false;

   public LoginUserInterface (
         Identity identity,
         JFrame frame)
   {
      super(identity,frame,I2L.getString(LF.LOGIN_DIALOG_TITLE));
   } // LoginUserInterface ()

   void tabPanels (
         Identity identity)
   {
      if (identity instanceof NdsIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.NDS_NAME),
                     null,
                     new NdsLoginPanel (identity, this));
         helpId = "loginnds";      
      } else if (identity instanceof BinderyIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.BINDERY_NAME),
                     null,
                     new BinderyLoginPanel (identity, this));
         helpId = "loginbindery";      
      }
/*
      else if (identity instanceof LdapIdentity)
      {
         ldap = true;
         tabPane.addTab (
                     I2L.getString (LF.LDAP_NAME),
                     null,
                     new LdapLoginPanel (identity, this));
         helpId = "loginnds";      
      }
*/
   } // tabPanels ()

   void okayPressed ()
   {
      removeDialog = true;

      try
      {
/*
         if (identity instanceof LdapIdentity)
         {
            XplatProtocolProxy.performLdapLogin (
                                    (LdapIdentity)identity,
                                    getName (),
                                    getPassword ());
         }
         else
*/
            XplatProtocolProxy.performLogin (
                                    identity,
                                    getName (),
                                    getDomain (),
                                    getPassword (),
                                    currentThread);
      }
      catch (com.novell.service.jncp.NSIException x)
      {
         int ccode = x.getCCode ();
         switch (ccode)
         {
            // previously authenticated different identity is authenticated for this resource
            case 0x8890:
            case 0x89FF:
               alreadyAuthenticated();
               break;
            // previously authenticated identity exists for this resource
            case 0x8899:
            case 0x897B:
               alreadyAuthenticated();
               break;
            default:
               isReady = false;
               exception = new LoginException(x);
         }
      }
      catch (com.novell.service.session.AlreadyAuthenticatedException x)
      {
         alreadyAuthenticated ();
      }
      catch (SessionException x)
      {
         isReady = false;
         exception = new LoginException (x);
      }
      catch (Exception x)
      {
         isReady = false;
         exception = new LoginException (x);
      }
      finally
      {
         if (removeDialog)
            dispose ();
      }
   } // okayPressed ()

   void cancelPressed ()
   {
      isReady = false;
      exception = new LoginCancelledException ();
      dispose ();
   } // cancelPressed ()

/*
   void errorOkayPressed ()
   {
      try
      {
//         if (!ldap)
            XplatProtocolProxy.performLogout (
                                    identity,
                                    getName (),
                                    getDomain (),
                                    currentThread);
         isReady = true;
      }
      catch (Exception x)
      {
         isReady = false;
         exception = new LoginException (x);
         removeDialog = true;
      }
   } // errorOkayPressed ()

   void aiiaErrorOkayPressed ()
   {
      try
      {
         BasePanel bp = (BasePanel)tabPane.getSelectedComponent();
         String domainName = bp.parseDomain(identity);
         Identity[] identities = Authenticator.getIdentities();
         Identity currentIdentity = null;
         for(int i=0; i<identities.length; i++)
         {
            if(bp.parseDomain(identities[i]).equalsIgnoreCase(domainName))
            {
               currentIdentity = identities[i];
               break;
            }
         }

         if(currentIdentity != null)
         {
            if(bp instanceof BinderyPanel)
               XplatProtocolProxy.performLogout(
                  identity,
                  bp.parseName(currentIdentity),
                  bp.parseDomain(currentIdentity),
                  currentThread);
            else
            {
               String name = ((NdsPanel)bp).parseName(currentIdentity);
               if(name.equals(""))
                  XplatProtocolProxy.performLogout(
                     identity,
                     ((NdsPanel)bp).parseContext(currentIdentity),
                     bp.parseDomain(currentIdentity),
                     currentThread);
               else
                  XplatProtocolProxy.performLogout(
                     identity,
                     ((NdsPanel)bp).parseName(currentIdentity)+"."+((NdsPanel)bp).parseContext(currentIdentity),
                     bp.parseDomain(currentIdentity),
                     currentThread);
            }
            isReady = true;
            removeDialog = false;
         }
         else
         {
            isReady = false;
            exception = new LoginException();
            removeDialog = true;
         }
      }
      catch(java.lang.Exception x)
      {
         isReady = false;
         exception = new LoginException(x);
         removeDialog = true;
      }
   } // aiiaErrorOkayPressed ()
*/
   void logoutAndLogin ()
   {
      try
      {
//         if (!ldap)
            XplatProtocolProxy.performLogout (
                                    identity,
                                    getName (),
                                    getDomain (),
                                    currentThread);
            isReady = true;
            okayPressed();
      }
      catch (Exception x)
      {
         isReady = false;
         exception = new LoginException (x);
         removeDialog = true;
      }
   } // errorOkayPressed ()

    private static String substString(String Str, String Var, String Value) {
        int Index = Str.indexOf(Var);
        if (Index >= 0)
            Str = Str.substring(0, Index) + Value + Str.substring(Index + Var.length());
        return Str;
    }
    
   void alreadyAuthenticated ()
   {
      isReady = false;
      exception = null;
      removeDialog = false;

      Point p = getLocation();
      Dimension d = getPreferredSize();
      p.x += d.width/2;
      p.y += d.height/2;
      
//      System.out.println("Getting the scope that has the tree or server");
      String CurrentlyLoggedIn = "";
      
      String Domain = getDomain();
      String Name = getName();
      String AdminDomain = "";
      
      if (identity instanceof NdsIdentity)
        AdminDomain = NdsIdentityScope.ADMINISTRATIVE_DOMAIN_NAME;
      else if (identity instanceof BinderyIdentity)
        AdminDomain = BinderyIdentityScope.ADMINISTRATIVE_DOMAIN_NAME;

      try {
        Identity[] Ident = Authenticator.getIdentities();
        for (int i = 0; i < Ident.length; i++) {
            if (((XplatIdentity) Ident[i]).getUserDomain().equals(Domain) && ((XplatIdentity) Ident[i]).getAdministrativeDomain().equals(AdminDomain)) {
                CurrentlyLoggedIn = Ident[i].getName();
                break;
            }
        }
      }
      catch (Exception e) {
        e.printStackTrace();
      }

      String Msg = I2L.getString(LF.PREVIOUSLY_AUTHENTICATED);
      Msg = substString(Msg, "$t", Domain);
      Msg = substString(Msg, "$n", Name);
      Msg = substString(Msg, "$c", CurrentlyLoggedIn);
      
      ErrorOkDialog eod = new ErrorOkCancelDialog(this,frame,I2L.getString(LF.PREVIOUSLY_AUTHENTICATED_TITLE),Msg,p)
      {
         void okayPressed()
         {
            ((LoginUserInterface) dialog).logoutAndLogin();
         }

         void cancelPressed()
         {
            this.dispose();
         }
      };
      eod.pack();
      eod.show();
   }
/*
   void anotherIdentityIsAuthenticated()
   {
      isReady = false;
      exception = null;
      removeDialog = false;

      Point p = getLocation();
      Dimension d = getPreferredSize();
      p.x += d.width/2;
      p.y += d.height/2;
      ErrorOkDialog eod = new ErrorOkCancelDialog(this,frame,I2L.getString(LF.ANOTHER_AUTHENTICATED_TITLE),I2L.getString(LF.ANOTHER_AUTHENTICATED),p)
      {
         // logout identity
         void okayPressed()
         {
            ((LoginUserInterface) dialog).aiiaErrorOkayPressed ();
            this.dispose ();
         }

         void cancelPressed ()
         {
            this.dispose ();
         }
      };
      eod.pack ();
      eod.show ();
   }
*/
} // class LoginUserInterface

/**
 * CreateTokensUserInterface
 */
class CreateTokensUserInterface
   extends BasicUserInterface
{
   private Identity admin;
   
   public CreateTokensUserInterface (
   		 Identity admin,
         Identity user,
         JFrame frame)
   {
      super (user, frame, I2L.getString (LF.CREATETOKENS_DIALOG_TITLE));
      this.admin = admin;
   } // CreateTokensUserInterface ()

   void tabPanels (
         Identity user)
   {
      if (user instanceof NdsIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.NDS_NAME),
                     null,
                     new NdsCreateTokensPanel (user, this));
         helpId = "createndstokens";                           
      } else if (user instanceof BinderyIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.BINDERY_NAME),
                     null,
                     new BinderyCreateTokensPanel (user, this));
	     helpId = "createbinderytokens";                           
      }
   } // tabPanels ()

   void okayPressed ()
   {
      try
      {
         NameDomainPasswordReady ndpr;
         ndpr = (NameDomainPasswordReady) tabPane.getSelectedComponent ();
         if (ndpr.isReady ())
         {
         XplatProtocolProxy.performCreateTokens (
                                 admin, 
                                 getName (),
                                 getDomain (),
                                 getPassword (),
                                 currentThread);
         removeDialog = true;
         }
         else
         {
            isReady = true;
            exception = null;
            removeDialog = false;

            Point p = getLocation();
            Dimension d = getPreferredSize();
            p.x += d.width/2;
            p.y += d.height/2;
            ErrorOkDialog eod = new ErrorOkDialog (this,frame,I2L.getString(LF.CREDENTIAL_INFO_ERROR_TITLE),I2L.getString(LF.CREDENTIAL_INFO_ERROR),p)
            {
               void okayPressed ()
               {
                  this.dispose ();
               }
            };
            eod.pack ();
            eod.show ();
         }
      }
      catch (Exception x)
      {
         isReady = false;
         exception = new CreateTokensException (x);
         removeDialog = true;
      }
      finally
      {
         if (removeDialog)
            dispose ();
      }
   } // okayPressed ()

   void cancelPressed ()
   {
      isReady = false;
      exception = new CreateTokensCancelledException ();
      dispose ();
   } // cancelPressed ()
} // class CreateTokensUserInterface


/**
 * VerifyTokensUserInterface
 */
class VerifyTokensUserInterface
   extends BasicUserInterface
{
   public VerifyTokensUserInterface (
         Identity identity,
         JFrame frame)
   {
      super (identity, frame, I2L.getString (LF.VERIFYTOKENS_DIALOG_TITLE));
   } // VerifyTokensUserInterface ()

   void tabPanels (
         Identity identity)
   {
      if (identity instanceof NdsIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.NDS_NAME),
                     null,
                     new NdsVerifyTokensPanel (identity, this));
         helpId = "verifyndstokens";               
      } else if (identity instanceof BinderyIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.BINDERY_NAME),
                     null,
                     new BinderyVerifyTokensPanel (identity, this));
         helpId = "verifybinderytokens";               
	  }         
   } // tabPanels ()

   void okayPressed ()
   {
      try
      {
         XplatProtocolProxy.performVerifyTokens (
                                 identity,getName (),
                                 getDomain (),
                                 getPassword (),
                                 currentThread);
      }
      catch (java.lang.Exception x)
      {
         isReady = false;
         exception = new VerifyTokensException (x);
      }
      finally
      {
         dispose ();
      }
   } // okayPressed ()

   void cancelPressed ()
   {
      isReady = false;
      exception = new VerifyTokensCancelledException ();
      dispose ();
   } // cancelPressed ()
} // class VerifyTokensUserInterface


/**
 * ModifyTokensUserInterface
 */
class ModifyTokensUserInterface
   extends BasicUserInterface
{
   public ModifyTokensUserInterface (
         Identity identity,
         JFrame frame)
   {
      super(identity,frame,I2L.getString(LF.MODIFYTOKENS_DIALOG_TITLE));
   } // ModifyTokensUserInterface ()

   void tabPanels(Identity identity)
   {
      if (identity instanceof NdsIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.NDS_NAME),
                     null,
                     new NdsModifyTokensPanel (identity, this));
         helpId = "modifyndstokens";               
      } else if (identity instanceof BinderyIdentity) {
         tabPane.addTab (
               I2L.getString (LF.BINDERY_NAME),
               null,
               new BinderyModifyTokensPanel (identity, this));
         helpId = "modifybinderytokens";               
	  }         
   } // tabPanels ()

   void okayPressed ()
   {
      try
      {
         NameDomainPasswordReady ndpr;
         ndpr = (NameDomainPasswordReady) tabPane.getSelectedComponent ();
         if (ndpr.isReady ())
         {
            XplatProtocolProxy.performModifyTokens (
                                    identity,
                                    getName (),
                                    getDomain (),
                                    getPassword(),
                                    getNewPassword (),
                                    currentThread);
         removeDialog = true;
         }
         else
         {
            isReady = true;
            exception = null;
            removeDialog = false;

            Point p = getLocation();
            Dimension d = getPreferredSize();
            p.x += d.width/2;
            p.y += d.height/2;
            ErrorOkDialog eod = new ErrorOkDialog (this,frame,I2L.getString(LF.CREDENTIAL_INFO_ERROR_TITLE),I2L.getString(LF.CREDENTIAL_INFO_ERROR),p)
            {
               void okayPressed ()
               {
                  this.dispose ();
               }
            };
            eod.pack ();
            eod.show ();
         }
      }
      catch (Exception x)
      {
         isReady = false;
         exception = new ModifyTokensException (x);
         removeDialog = true;
      }
      finally
      {
         if (removeDialog)
            dispose ();
      }
   } // okayPressed ()

   void cancelPressed ()
   {
      isReady = false;
      exception = new ModifyTokensCancelledException ();
      dispose ();
   } // cancelPressed ()
} // class ModifyTokensUserInterface

/**
 * LogoutUserInterface
 */
class LogoutUserInterface
   extends BasicUserInterface
{
   public LogoutUserInterface (
         Identity identity,
         JFrame frame)
   {
      super(identity,frame,I2L.getString(LF.LOGOUT_DIALOG_TITLE));
   } // LogoutUserInterface ()

   void tabPanels (
         Identity identity)
   {
      if (identity instanceof NdsIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.NDS_NAME),
                     null,
                     new NdsLogoutPanel (identity, this));
         helpId = "logoutnds";               		                   
      } else if (identity instanceof BinderyIdentity) {
         tabPane.addTab (
                     I2L.getString (LF.BINDERY_NAME),
                     null,
                     new BinderyLogoutPanel (identity, this));
         helpId = "logoutbindery";               
      }         
   } // tabPanels ()

   void okayPressed ()
   {
      try
      {
         XplatProtocolProxy.performLogout (
                                 identity,
                                 getName (),
                                 getDomain (),
                                 currentThread);
      }
      catch (java.lang.Exception x)
      {
         isReady = false;
         exception = new LogoutException (x);
      }
      finally
      {
         dispose ();
      }
   } // okayPressed ()

   void cancelPressed ()
   {
      isReady = false;
      exception = new LogoutCancelledException ();
      dispose ();
   } // cancelPressed ()
} // class LogoutUserInterface

/**
 * NameDomainPasswordReady
 */
interface NameDomainPasswordReady
{
   String getName();
   String getDomain();
   Password getPassword();
   Password getNewPassword();
   boolean isReady();
   AuthenticatorException getException();
} // interface NameDomainPasswordReady

/**
 * BasePanel
 */
abstract class BasePanel
   extends JPanel
   implements NameDomainPasswordReady
{
   JLabel      graphic                    = null;

   JLabel      labels[]                   = null;
   JTextField   fields[]                  = null;

   final int TOP_BORDER                   = 55;
   final int BOTTOM_BORDER                = 33;
   final int LEFT_BORDER                  = 40;
   final int RIGHT_BORDER                 = 50;

   final int VERTICAL_SPACING_FOR_INPUT   = 8;
   final int NUMBER_OF_CELLS              = 6;

   BasicUserInterface bui;

   abstract public int getLastField();

   int getFirstFocusFieldNumber()
   {
      // default is the last field in dialog
      int focusField = getLastField();

      // find first empty field
      for(int i=0;i<fields.length;i++)
      {
         // find first empty string and put focus there
         if(fields[i].getText().length() == 0)
         {
            focusField = i;
            break;
         }
      }
      return focusField;
   }

   public java.awt.Component getFirstFocusComponent()
   {
      return fields[getFirstFocusFieldNumber()];
   }

   /*
    * JFC requestFocus() bug workaround.
    */
   public boolean isFocusTraversible()
   {
      return true;
   }

   private int maxMessageSize(String messages[][])
   {
      int max = 0;
      for(int i=0; i<messages.length; i++)
      {
         if(messages[i][0].length() > max)
         {
            max = messages[i][0].length();
         }
      }
      return max;
   }

   private String getMaxSizeMessage(String messages[][])
   {
      String max = null;
      for(int i=0; i<messages.length; i++)
      {
         if(I2L.getString(messages[i][0]).length() > ((max!=null)?max.length():0) )
         {
            max = I2L.getString(messages[i][0]);
         }
      }
      return max;
   }

   public BasePanel(BasicUserInterface bui, String graphicsPath,String labelTitles[][])
   {
      super(false);
      this.bui = bui;

      // layout manager
//      GridLayout layout = new GridLayout(NUMBER_OF_CELLS,2);
      GridBagLayout layout = new GridBagLayout();
      GridBagConstraints Const = new GridBagConstraints();
      Const.insets.bottom = Const.insets.top = VERTICAL_SPACING_FOR_INPUT / 2;
      Const.anchor = GridBagConstraints.WEST;
      
//      layout.setVgap(VERTICAL_SPACING_FOR_INPUT);

      JPanel panel = new JPanel(layout);
      Dimension d;
      try
      {
         graphic = new JLabel(new ImageIcon(getImage(I2L.getString(graphicsPath))));

         // assume these are positive...
         d = graphic.getPreferredSize();
         d.height = d.height-TOP_BORDER-BOTTOM_BORDER;
         d.width = d.width-LEFT_BORDER-RIGHT_BORDER;

         panel.setSize(d);
         Point p = graphic.getLocation();
         p.x = p.x+LEFT_BORDER;
         p.y = p.y+TOP_BORDER;
         panel.setLocation(p);
      }
      catch(NullPointerException x)
      {
         // the image is not present, so create a blank label
         graphic = new JLabel();

         // display is split in half with a string (JLabel) on one side and
         // a text field (JTextField) on the other, separated by a small space.
         // HACK!!! - "small space" is hardcoded
         FontMetrics fm = graphic.getFontMetrics(graphic.getFont());
         int size = 2*fm.stringWidth(getMaxSizeMessage(labelTitles)) + 10;

         // display size should be the larger of the title bar size and
         // the field string size calculated above
         // HACK!!! - add space for the Java cup and X on title bar
         int tSize = fm.stringWidth(bui.getTitle()) + 20;

         if(tSize > size)
            size = tSize;

         d = new Dimension(size,150);
         graphic.setPreferredSize(d);

         panel.setSize(d);
         Point p = graphic.getLocation();
         p.x = p.x + 3;
         p.y = p.y + 3;
         panel.setLocation(p);
      }

      JLabel blankLabel = new JLabel();
      blankLabel.setVisible(false);
      JTextField blankField = new JTextField();
      blankField.setVisible(false);
      blankField.setEnabled(false);

      labels = new JLabel[NUMBER_OF_CELLS];
      fields = new JTextField[NUMBER_OF_CELLS];
      for(int i=0; i<NUMBER_OF_CELLS;i++)
      {
         // create labels and text fields
         if(i<labelTitles.length)
         {
            labels[i] = new JLabel(I2L.getString(labelTitles[i][0]));
            labels[i].setDisplayedMnemonic(I2L.getString(labelTitles[i][1]).charAt(0));
//          labels[i].setToolTipText(I2L.getString(labelTitles[i][2]));

            if(labelTitles[i][0].indexOf(LF.PASSWORD) != -1)
            {
               fields[i] = new JPasswordField();
//             fields[i].setEchoChar('*');
               /*
                * JFC bug work-around.
                */
               // SPD 192335:  Swing 1.0.2 cursor on JDK 1.1.5 tracks with
               // proportional font sized key not the size of the echoChar,
               // thus the cursor may trail or lead the entered key
               //
               // NOTE:  This is probably not the best way since the font
               // and point size must be present on the system.
               fields[i].setFont(new java.awt.Font("Courier",java.awt.Font.PLAIN,12));
            }
            else
               fields[i] = new JTextField();

            labels[i].setLabelFor(fields[i]);

            labels[i].setOpaque(false);
//          fields[i].setOpaque(true);

            fields[i].addKeyListener(bui);
         }
         else
         {
            labels[i] = blankLabel;
            fields[i] = blankField;
         }

         // add to panel
         Const.fill = Const.NONE;
         Const.gridwidth = Const.RELATIVE;
         Const.weightx = 0.0;
         Const.insets.right = 5;
         layout.setConstraints(labels[i], Const);
         panel.add(labels[i]);
         
         Const.fill = Const.HORIZONTAL;
         Const.gridwidth = Const.REMAINDER;
         Const.weightx = 1.0;
         Const.insets.right = 0;
         layout.setConstraints(fields[i], Const);
         panel.add(fields[i]);
      }
      panel.setOpaque(false);

      graphic.add(panel);
      add(graphic);
   }

   public Image getImage(String imagePath)
   {
      Image image = null;

      URL url = this.getClass().getResource(imagePath);

       // Create a URL for it.
      try
      {
         image = Toolkit.getDefaultToolkit().createImage((ImageProducer) url.getContent());
      }
      catch (Exception ex)
      {
         return null;
      }

      // Let's try forcing a wait until the image is loaded...
      ImageObserver o = new ImageObserver()
      {
         public boolean imageUpdate( Image image, int flags, int x, int y, int width, int height)
         {
            // If there was an error or abort indicated,
            // return false, telling the caller that we are all done requesting info
            return !((flags & (ERROR | ABORT )) > 0);
         }
      };

      while( (image != null) && (!Toolkit.getDefaultToolkit().prepareImage( image, -1, -1, o )))
      {
         try
          {
            // 15 is actually very important here.  Any larger number here and images can take too long to load.
            // Any shorter and this thread hogs the CPU.
            Thread.sleep(15);
         } catch( InterruptedException e ){}
      }
      return image;
   }

   /*
    * administrative domains are either [NDS], [BINDERY],[undefined].
    */
   static boolean isAdministrativeDomain(String name)
   {
      if (name == null)
         return false;

      if(name.equalsIgnoreCase(NdsIdentityScope.ADMINISTRATIVE_DOMAIN_NAME)||name.equalsIgnoreCase(BinderyIdentityScope.ADMINISTRATIVE_DOMAIN_NAME))
         return true;
      return false;
   }

   /*
    * administrative domains are either [NDS], [BINDERY],[undefined]
    *
    * e.g. jsnielsen.java.prv.novell.NOVELL_INC.[NDS]
    * administrative domain   - [NDS]
    * domain                  - NOVELL_INC
    * name                    - jsnielsen.java.prv.novell
    *
    * e.g. jsnielsen.java.prv.novell.NOVELL_INC
    * administrative domain   - [undefined]
    * domain                  - NOVELL_INC
    * name                    - jsnielsen.java.prv.novell
    *
    * e.g. NOVELL_INC
    * administrative domain   - [undefined]
    * domain                  - NOVELL_INC
    * name                    -
    *
    * e.g. STILLWATERS.[BINDERY]
    * administrative domain   - [BINDERY]
    * domain                  - NOVELL_INC
    * name                    -
    */
    
   static String parseDomain(Identity identity)
   {
      IdentityScope scope = identity.getScope();
      if(scope == null)
      {
         String name = identity.getName();
         if(isAdministrativeDomain(name))
            return "";     // this should never happen
         else
            return name;
      }

      IdentityScope nextScope = scope.getScope();
      if(nextScope == null)
      {
         String name = scope.getName();
         if(isAdministrativeDomain(name))
            return identity.getName();
         else
            return name;
      }
      // recurse
      return parseDomain(scope);
   }

   public abstract String getName();
   public abstract String getDomain();
   public abstract Password getPassword();
   public abstract Password getNewPassword();
   public abstract boolean isReady();
   public AuthenticatorException getException()
   {
      return bui.exception;
   }

   abstract String parseName(Identity identity);
} // class BasePanel

/**
 * BasePanel
 *
 * e.g. jsnielsen.java.prv.novell.NOVELL_INC.[NDS]
 * administrative domain   - [NDS]
 * domain                  - NOVELL_INC
 * name                    - jsnielsen.java.prv.novell
 *
 * e.g. jsnielsen.java.prv.novell.NOVELL_INC
 * administrative domain   - [undefined]
 * domain                  - NOVELL_INC
 * name                    - jsnielsen.java.prv.novell
 *
 * e.g. NOVELL_INC
 * administrative domain   - [undefined]
 * domain                  - NOVELL_INC
 * name                    -
 *
 * e.g. STILLWATERS.[BINDERY]
 * administrative domain   - [BINDERY]
 * domain                  - NOVELL_INC
 * name                    -
 */
class NdsPanel
   extends BasePanel
{
   Identity identity;

   NdsPanel(Identity identity,BasicUserInterface bui,String graphicsPath,String labelTitles[][])
   {
      super(bui,graphicsPath,labelTitles);
      this.identity = identity;
      fields[0].setText(parseDomain(identity));
      fields[1].setText(parseContext(identity));
      fields[2].setText(parseName(identity));
   }

   public int getLastField()
   {
      return 2;
   }

   String parseName(Identity identity)
   {
      IdentityScope scope = identity.getScope();
      if(scope == null)
         return "";

      IdentityScope nextScope = scope.getScope();
      if(nextScope == null)
         return "";

      IdentityScope nextNextScope = nextScope.getScope();
      if(nextNextScope == null)
         if(isAdministrativeDomain(nextScope.getName()))
            return "";

      return identity.getName();
   }

   boolean firstTime = true;
   String parseContext(Identity identity)
   {
      if(firstTime)
      {
         // context
         IdentityScope scope = identity.getScope();
         if(scope != null)
         {
            // domain
            IdentityScope nextScope = scope.getScope();
            if(nextScope != null)
            {
               // non-administrative domain
               if(!isAdministrativeDomain(nextScope.getName()))
               {
                  firstTime = false;
                  return parseContext(scope);
               }
            }
         }
      }

      IdentityScope scope = identity.getScope();
      if(scope == null)
         return "";

      IdentityScope nextScope = scope.getScope();
      if(nextScope == null)
      {
         String name = scope.getName();
         if(isAdministrativeDomain(name))
            return "";
         else
            return identity.getName();
      }

      IdentityScope nextNextScope = nextScope.getScope();
      if(nextNextScope == null)
      {
         String name = nextScope.getName();
         if(isAdministrativeDomain(name))
            return identity.getName();
         else
            return identity.getName()+"."+scope.getName();
      }

      IdentityScope nextNextNextScope = nextNextScope.getScope();
      if(nextNextNextScope == null)
      {
         String name = nextNextScope.getName();
         if(isAdministrativeDomain(name))
            return identity.getName()+"."+scope.getName();
         else
            return identity.getName()+"."+scope.getName()+"."+nextScope.getName();
      }

      return identity.getName()+"."+parseContext(scope);
   }

   public String getName()
   {
      String context = fields[1].getText();
      if(context.length() > 0)
         if(context.charAt(0) == '.')
            return fields[2].getText()+context;
         else
            return fields[2].getText()+"."+context;
      return fields[2].getText();
   }

   public String getDomain()
   {
      return fields[0].getText();
   }

   public Password getPassword()
   {
      return new Password(fields[3].getText());
   }

   public Password getNewPassword()
   {
      return new Password(fields[4].getText());
   }

   public boolean isReady()
   {
      if((fields[0].getText().length() != 0) &&
         (fields[2].getText().length() != 0))
         return true;
      return false;
   }
} // class NdsPanel

/**
 * NdsLoginPanel
 */
class NdsLoginPanel
   extends NdsPanel
{
   static final String NDS_LOGIN_PANEL_ARGS[][] = {
      {LF.TREE,      LF.TREE_MNEMONIC,       LF.TREE_TOOLTIP},
      {LF.CONTEXT,   LF.CONTEXT_MNEMONIC,    LF.CONTEXT_TOOLTIP},
      {LF.NAME,      LF.NAME_MNEMONIC,       LF.NAME_TOOLTIP},
      {LF.PASSWORD,  LF.PASSWORD_MNEMONIC,   LF.PASSWORD_TOOLTIP},
   };

   NdsLoginPanel(Identity identity,BasicUserInterface bui)
   {
      super (identity, bui, LF.LOGIN_GIF, NDS_LOGIN_PANEL_ARGS);
   }

   public int getLastField ()
   {
      return 2;
   }
} // class NdsLoginPanel

/**
 * NdsModifyTokensPanel
 */
class NdsModifyTokensPanel
   extends NdsPanel
{
   static final String NDS_MODIFY_TOKENS_PANEL_ARGS[][] = {
      {LF.TREE,               LF.TREE_MNEMONIC,             LF.TREE_TOOLTIP},
      {LF.CONTEXT,            LF.CONTEXT_MNEMONIC,          LF.CONTEXT_TOOLTIP},
      {LF.NAME,               LF.NAME_MNEMONIC,             LF.NAME_TOOLTIP},
      {LF.PASSWORD,           LF.PASSWORD_MNEMONIC,         LF.PASSWORD_TOOLTIP},
      {LF.NEW_PASSWORD,       LF.NEW_PASSWORD_MNEMONIC,     LF.NEW_PASSWORD_TOOLTIP},
      {LF.CONFIRM_PASSWORD,   LF.CONFIRM_PASSWORD_MNEMONIC, LF.CONFIRM_PASSWORD_TOOLTIP}
   };

   NdsModifyTokensPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.MODIFYTOKENS_GIF,NDS_MODIFY_TOKENS_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 5;
   }

   public boolean isReady()
   {
      if(super.isReady())
         if(fields[4].getText().equals(fields[5].getText()))
            return true;
      return false;
   }
} // class NdsModifyTokensPanel

/**
 * NdsCreateTokensPanel
 */
class NdsCreateTokensPanel
   extends NdsPanel
{
   static final String NDS_CREATE_TOKENS_PANEL_ARGS[][] = {
      {LF.TREE,         LF.TREE_MNEMONIC,          LF.TREE_TOOLTIP},
      {LF.CONTEXT,      LF.CONTEXT_MNEMONIC,       LF.CONTEXT_TOOLTIP},
      {LF.NAME,         LF.NAME_MNEMONIC,          LF.NAME_TOOLTIP},
      {LF.NEW_PASSWORD, LF.NEW_PASSWORD_MNEMONIC,  LF.NEW_PASSWORD_TOOLTIP},
      {LF.CONFIRM_PASSWORD,   LF.CONFIRM_PASSWORD_MNEMONIC, LF.CONFIRM_PASSWORD_TOOLTIP}
   };

   NdsCreateTokensPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.CREATETOKENS_GIF,NDS_CREATE_TOKENS_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 4;
   }

   public boolean isReady()
   {
      if(super.isReady())
         if(fields[3].getText().equals(fields[4].getText()))
            return true;
      return false;
   }
} // class NdsCreateTokensPanel

/**
 * NdsVerifyTokensPanel
 */
class NdsVerifyTokensPanel
   extends NdsPanel
{
   static final String NDS_VERIFY_TOKENS_PANEL_ARGS[][] = {
      {LF.TREE,         LF.TREE_MNEMONIC,          LF.TREE_TOOLTIP},
      {LF.CONTEXT,      LF.CONTEXT_MNEMONIC,       LF.CONTEXT_TOOLTIP},
      {LF.NAME,         LF.NAME_MNEMONIC,          LF.NAME_TOOLTIP},
      {LF.PASSWORD,     LF.PASSWORD_MNEMONIC,      LF.PASSWORD_TOOLTIP}
   };

   NdsVerifyTokensPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.VERIFYTOKENS_GIF,NDS_VERIFY_TOKENS_PANEL_ARGS);
   }
} // class NdsVerifyTokensPanel


/**
 * NdsLogoutPanel
 */
class NdsLogoutPanel
   extends NdsPanel
{
   static final String NDS_LOGOUT_PANEL_ARGS[][] = {
      {LF.TREE,      LF.TREE_MNEMONIC,    LF.TREE_TOOLTIP},
      {LF.CONTEXT,   LF.CONTEXT_MNEMONIC, LF.CONTEXT_TOOLTIP},
      {LF.NAME,      LF.NAME_MNEMONIC,    LF.NAME_TOOLTIP}
   };

   NdsLogoutPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.LOGOUT_GIF,NDS_LOGOUT_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 2;
   }
} // class NdsLogoutPanel

/**
 * BinderyPanel
 */
class BinderyPanel
   extends BasePanel
{
   BinderyPanel(Identity identity,BasicUserInterface bui,String graphicsPath,String labelTitles[][])
   {
      super(bui,graphicsPath,labelTitles);
      fields[0].setText(parseDomain(identity));
      fields[1].setText(parseName(identity));
   }

   String parseName(Identity identity)
   {
      IdentityScope scope = identity.getScope();
      if(scope == null)
         return "";

      IdentityScope nextScope = scope.getScope();
      if(nextScope == null)
      {
         String name = scope.getName();
         if(isAdministrativeDomain(name))
            return "";
         else
            return identity.getName();
      }

      IdentityScope nextNextScope = nextScope.getScope();
      if(nextNextScope == null)
      {
         String name = nextScope.getName();
         if(isAdministrativeDomain(name))
            return identity.getName();
         else
            return identity.getName()+"."+scope.getName();
      }

      return identity.getName()+"."+parseName(scope);
   }

   public String getName()
   {
      return fields[1].getText();
   }

   public String getDomain()
   {
      return fields[0].getText();
   }

   // for bindery the password must be uppercase
   public Password getPassword()
   {
      return new Password(fields[2].getText().toUpperCase());
   }

   // for bindery the password must be uppercase
   public Password getNewPassword()
   {
      return new Password(fields[3].getText().toUpperCase());
   }

   public boolean isReady()
   {
      if((fields[0].getText().length() != 0) &&
         (fields[1].getText().length() != 0))
         return true;
      return false;
   }

   public int getLastField()
   {
      return 1;
   }
} // class BinderyPanel

/**
 * BinderyLoginPanel
 */
class BinderyLoginPanel
   extends BinderyPanel
{
   static final String BINDERY_LOGIN_PANEL_ARGS[][] = {
      {LF.SERVER,    LF.SERVER_MNEMONIC,     LF.SERVER_TOOLTIP},
      {LF.NAME,      LF.NAME_MNEMONIC,       LF.NAME_TOOLTIP},
      {LF.PASSWORD,  LF.PASSWORD_MNEMONIC,   LF.PASSWORD_TOOLTIP}
   };

   BinderyLoginPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.LOGIN_GIF,BINDERY_LOGIN_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 2;
   }
} // class BinderyLoginPanel

/**
 * BinderyModifyTokensPanel
 */
class BinderyModifyTokensPanel
   extends BinderyPanel
{
   static final String BINDERY_MODIFY_TOKENS_PANEL_ARGS[][] = {
      {LF.SERVER,             LF.SERVER_MNEMONIC,           LF.SERVER_TOOLTIP},
      {LF.NAME,               LF.NAME_MNEMONIC,             LF.NAME_TOOLTIP},
      {LF.PASSWORD,           LF.PASSWORD_MNEMONIC,         LF.PASSWORD_TOOLTIP},
      {LF.NEW_PASSWORD,       LF.NEW_PASSWORD_MNEMONIC,     LF.NEW_PASSWORD_TOOLTIP},
      {LF.CONFIRM_PASSWORD,   LF.CONFIRM_PASSWORD_MNEMONIC, LF.CONFIRM_PASSWORD_TOOLTIP}
   };

   BinderyModifyTokensPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.MODIFYTOKENS_GIF,BINDERY_MODIFY_TOKENS_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 4;
   }

   public boolean isReady()
   {
      if(super.isReady())
         if((fields[3].getText().equals(fields[4].getText())))
            return true;
      return false;
   }
} // class BinderyModifyTokensPanel

/**
 * BinderyCreateTokensPanel
 */
class BinderyCreateTokensPanel
   extends BinderyPanel
{
   static final String BINDERY_CREATE_TOKENS_PANEL_ARGS[][] = {
      {LF.SERVER,          LF.SERVER_MNEMONIC,        LF.SERVER_TOOLTIP},
      {LF.NAME,            LF.NAME_MNEMONIC,          LF.NAME_TOOLTIP},
      {LF.NEW_PASSWORD,    LF.NEW_PASSWORD_MNEMONIC,  LF.NEW_PASSWORD_TOOLTIP},
      {LF.CONFIRM_PASSWORD,   LF.CONFIRM_PASSWORD_MNEMONIC, LF.CONFIRM_PASSWORD_TOOLTIP}
   };

   BinderyCreateTokensPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.CREATETOKENS_GIF,BINDERY_CREATE_TOKENS_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 3;
   }

   public boolean isReady()
   {
      if(super.isReady())
         if((fields[2].getText().equals(fields[3].getText())))
            return true;
      return false;
   }

} // class BinderyCreateTokensPanel


/**
 * BinderyVerifyTokensPanel
 */
class BinderyVerifyTokensPanel
   extends BinderyPanel
{
   static final String BINDERY_VERIFY_TOKENS_PANEL_ARGS[][] = {
      {LF.SERVER,          LF.SERVER_MNEMONIC,        LF.SERVER_TOOLTIP},
      {LF.NAME,            LF.NAME_MNEMONIC,          LF.NAME_TOOLTIP},
      {LF.PASSWORD,        LF.PASSWORD_MNEMONIC,      LF.PASSWORD_TOOLTIP}
   };

   BinderyVerifyTokensPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.VERIFYTOKENS_GIF,BINDERY_VERIFY_TOKENS_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 2;
   }
} // class BinderyVerifyTokensPanel

/**
 * BinderyLogoutPanel
 */
class BinderyLogoutPanel
   extends BinderyPanel
{
   static final String BINDERY_LOGOUT_PANEL_ARGS[][] = {
      {LF.SERVER, LF.SERVER_MNEMONIC,  LF.SERVER_TOOLTIP},
      {LF.NAME,   LF.NAME_MNEMONIC, LF.NAME_TOOLTIP}
   };

   BinderyLogoutPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.LOGOUT_GIF,BINDERY_LOGOUT_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 1;
   }
} // class BinderyLogoutPanel

/**
 * LdapPanel
 *
class LdapPanel
   extends BasePanel
{
   LdapPanel(Identity identity,BasicUserInterface bui,String graphicsPath,String labelTitles[][])
   {
      super(bui,graphicsPath,labelTitles);
      fields[0].setText(parseName(identity));
   }

   String parseName(Identity identity)
   {
      return identity.getName();
   }

   public String getDomain()
   {
      return null;
   }

   public String getName()
   {
      return fields[0].getText();
   }

   public Password getPassword()
   {
      return new Password(fields[1].getText().toUpperCase());
   }

   public Password getNewPassword()
   {
      return null;
   }

   public boolean isReady()
   {
      return true;
   }

   public int getLastField()
   {
      return 0;
   }
} * class LdapPanel */

/**
 * LdapLoginPanel
 *
class LdapLoginPanel
   extends LdapPanel
{
   static final String LDAP_LOGIN_PANEL_ARGS[][] = {
      {LF.NAME,      LF.NAME_MNEMONIC,       LF.NAME_TOOLTIP},
      {LF.PASSWORD,  LF.PASSWORD_MNEMONIC,   LF.PASSWORD_TOOLTIP}
   };

   LdapLoginPanel(Identity identity,BasicUserInterface bui)
   {
      super(identity,bui,LF.LOGIN_GIF,LDAP_LOGIN_PANEL_ARGS);
   }

   public int getLastField()
   {
      return 1;
   }

    *
    * JFC bug work-around.
    * 
   public boolean isVisible()
   {
      if(firstTimeThrough == true && super.isVisible())
      {
         fields[2].requestFocus();
         fields[2].requestDefaultFocus();
         firstTimeThrough = false;
      }
      return super.isVisible();
   }

} * class LdapLoginPanel */

