/*
 *  update interaction with DomainService to access graph with specific permission on July 8
 *
 *  update code to JDK1.1 beginning on July 10 by Li, Qian.
 *
 *  add ACL control and read/write switching mechanism on July 20 by Li,Qian
 */

package graphbrowser;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

import java.util.*;
import java.net.*;
import java.lang.Math;

import graph.*;
import jow.*;
import jowgraphservice.*;
import jowadmin.*;

// ***********************************************************
// *********************** GraphWindow ***********************
// ***********************************************************


public class GraphWindow extends Frame implements Runnable,WindowListener, ActionListener, AdjustmentListener, ItemListener{

  public static int PASTE_FINISHED = 0;
  public GraphApplet source;
  public Graph aGraph;
  URL dummyURL;
  UserID dummyUserID;
  public JOWGraphServiceInterface jowGraphService;
  MIME_Type type;

  public static Color LIGHTBLUE=new Color(160,224,255);
  //boolean graphWrite = false;
  //private boolean DisplayMoveNode = true;
  private BooleanValue DisplayMoveNode = new BooleanValue(false);

  private boolean recoverMode = false;
  private Vector  recoverNodeTable = new Vector();        //// store recovered node and related links

  public GraphEngine graphEngine;

  public boolean editMode = false;   // default is read
  private int pasteMode=PASTE_FINISHED;
  //public boolean pasteMode = false;

  public void disableRecoverNode() {
    recoverNodeTable.removeAllElements();
    recoverMode = false;
    nodeUnDelete.disable();
  }

  public void addDeleteNode(Node newnode) {
     recoverNodeTable.addElement(newnode);
     recoverMode = true;
     nodeUnDelete.setEnabled(true);
  }

  public void undeleteNode() {
     if ( recoverNodeTable.isEmpty()) {nodeUnDelete.disable();}
     Node node= (Node) recoverNodeTable.lastElement();
     if (node !=null) { node.setValid(true); node.setForwarded(false);
                         recoverNodeTable.removeElement(node);
                         if ( recoverNodeTable.isEmpty()) {nodeUnDelete.disable();}
                         }

        else {nodeUnDelete.disable();}

  }

  public boolean getDisplayMoveNode() {
    return DisplayMoveNode.getValue();
  }

  public void setDisplayMoveNode(boolean value) {
    DisplayMoveNode.setValue(value);
  }


    void buildAclWin() {
        // show PACL window

        GraphAclWin aclwin;
        // if select a node then open content object
        boolean forgraph=true;
        Node n = aGraph.getSelectedNode();
        if ( n != null )  {
        graphpanel.notfrommenu=false;

            URL url = n.getContent();
            if ( url != null )  {
                forgraph=false;
               //showError("No Content exist!");
            }
        }
        if (forgraph) { aclwin=new GraphAclWin(this,aGraph); }
            else aclwin=new GraphAclWin(this,n);
    }

  // enable/disable menuitems to switch between READ/WRITE Mode
  public void setReadWrite() {
    graphpanel.setNodePopup(editMode);
    copyMenu.setEnabled(editMode);
    moveMenu.setEnabled(editMode);
    if (!editMode) {

    systemNew.disable();
    systemSave.disable();
    systemOpen.setEnabled(true);
    systemImport.enable();
    contentType.disable();

    nodeAdd.disable();
    nodeDelete.disable();
    nodeUnDelete.disable();
    nodeOpenEdit.disable();
    nodeLabel.disable();
    linkMenu.disable();
    systemRefresh.enable();

    }
   else {
    systemOpen.setEnabled(false);
    systemNew.enable();
    systemSave.enable();
    systemRefresh.disable();
    systemImport.setEnabled(false);

    contentType.enable();

    nodeAdd.enable();
    nodeDelete.enable();
    nodeOpenEdit.enable();
    nodeLabel.enable();
    linkMenu.enable();

   }

  }

  public void showMessage(String msg) {
    messageArea.setText(msg);
    System.out.println(msg);
  }

  public void resetMessageColor() {
    if (editMode) {
        messageArea.setBackground(Color.yellow);
    } else {
        messageArea.setBackground(LIGHTBLUE);
     }
  }

  public void resetTitle() {
    setTitle("GraphWindow: "+"Username("+source.userName+")      Graph:("+ aGraph.getLabel()+")");

  }

  public void setMode(boolean mode) {
    editMode=mode;

preferenceEdit.setState(editMode);
preferenceDisplay.setState(!editMode);
resetMessageColor();
    setReadWrite();
  }

  public boolean isWrite() {
    return editMode;
  }

public  GraphWindow ( GraphApplet ga, JOWGraphServiceInterface ds, URL url )  {
    super ( "Graph Browser" );
    //init();
    Runtime.getRuntime().gc();
    jowGraphService = ga.getDomainService();
    graphEngine=ga.getGraphEngine();
    source = ga;
    try {
      aGraph = (Graph)ds.openGraph( url );
    } catch (JOWException e) {
        System.out.println("Graph Window: Open Graph Fail");
      }

    this.setTitle("GraphWindow: Username("+source.userName+") Graph:("+aGraph.getLabel()+")");

  }  // end GraphWindow ( JOWService ds, URL url )

public  GraphWindow ( GraphApplet ga, JOWGraphServiceInterface ds, Graph g )  {
    super("GraphWindow: Username("+ga.userName+") Graph:("+g.getLabel()+")");
    jowGraphService = ga.getDomainService();
    graphEngine=ga.getGraphEngine();
    source = ga;
    aGraph = g;
        Runtime.getRuntime().gc();

    //init();
  }  // end GraphWindow ( JOWService ds, Graph g )

  /*
  GraphWindow ( GraphApplet ga )  {
    super ( "Graph Browser" );
    init();
    source = ga;
    aGraph = new Net ( dummyURL, "A New Graph" );  // default
  }  // end GraphWindow constructor

  GraphWindow ( GraphApplet ga, int s )  {
    super ( "Graph Browser" );
    init();
    source = ga;

    if ( s == MIME_Type.TREE ) {
    aGraph = new Tree ( dummyURL, "A New Graph" );
    }
    if ( s == MIME_Type.LIST ) {
    aGraph = new Lst ( dummyURL, "A New Graph" );
    }
    if ( s == MIME_Type.NET ) {
    aGraph = new Net ( dummyURL, "A New Graph" );  // default
    }
  }  // end GraphWindow constructor

  */
  public void init()  {
    /*
    try {
        dummyURL = new URL ( "http://jbspc.cs.unc.edu/0000" );
    } catch( MalformedURLException e )  {
        System.out.println("MalformedURLException in GraphWindow");
    } */
    dummyUserID = new UserID();

    setReadWrite();

  }  // end init

  public void start () {
    graphEngine = source.getGraphEngine();
    //graphEngine = new GraphEngine(this);
    buildWindow ();
    graphpanel.start ();
  }  // end start

  public void stop () {
    graphpanel.stop ();
  }  // end stop

  public void run () {
  }  // end run


  public void showError(String msg) {
        System.out.println("GraphWindow ERROR:"+msg);
        messageArea.setText("ERROR:"+msg);
        LabelDialog ld=new LabelDialog(this,"Error Alarm",msg);
        ld.show();

  }
// ***************************** Menu Action Methods

  public void SystemNew () {
    Graph g=null;
    System.out.println ("GraphWindow:  SystemNew 1");
    // logic to ask user for MIME_Type
    type = new MIME_Type();

 /* GraphObject gobj = jowGraphService.createGraphObject( dummyUserID );
    URL u = gobj.getUID();
    Graph g = new Net( u, "A New Graph" );
 */
    try {
        g= jowGraphService.createGraph( );
        source.addGraphWindow ( jowGraphService, g ,true);
    } catch (JOWException e) {
        showError("Create Graph Fail."+e.getMessage());
      }

    //URL u = g.getUID();
    //n.setContent( u );
    //System.out.println ("  n.setcontent = "+u);
    //Graph g = new Net( u, "A New Graph" );

  }  // end SystemNew

  public void SystemNew ( Node n) {
    Graph g=null;
    if (!isWrite()) {
        showError("Operation Fail. Now you are in DISPLAY mode.");
        return;
       }
    // Qian:  ask user for MIME_Type
    GraphPropDialog  gpd=new GraphPropDialog(this,"Graph Property");
    // need to ask property
    gpd.setLabel(n.getLabel());
    gpd.show();
    String label=gpd.getLabel();


    // mt = gpd.getType();
    /*MIME_Type mt=new MIME_Type();
    mt.setBoth(MIME_Type.GRAPH, MIME_Type.NET); */
    MIME_Type mt=gpd.getType();

    if (mt.getType() != MIME_Type.GRAPH) { NodeCreateContent(mt,label); return;}
    try {
        g= jowGraphService.createGraph(aGraph.getUID() );
        g.setLabel(label);
    URL u = g.getUID();
    n.setContent( u );
    n.setContentType( mt );
    source.addGraphWindow ( jowGraphService, g, true);
    } catch (JOWException e) {
        showError("Operation Fail:"+e.getMessage());
      }
  }  // end SystemNew ( Node n)

  public void SystemNew ( Node n, MIME_Type mt ) {
    Graph g=null;

    // logic to ask user graph property
    GraphPropDialog  gpd=new GraphPropDialog(this,"Graph Property",mt);
    // no logic need to ask user for MIME_Type
    gpd.setLabel(n.getLabel());
    gpd.show();

    String label=gpd.getLabel();

    type = mt;
    try {
        g= jowGraphService.createGraph(aGraph.getUID());
        g.setLabel(label);
    URL u = g.getUID();
    n.setContent( u );
    n.setContentType( mt );
    System.out.println ("  n.setcontent = "+u);
    source.addGraphWindow ( jowGraphService, g ,true);
    } catch (JOWException e) {
        showError("Create Graph Fail."+e.getMessage());
      }
  }  // end SystemNew ( Node n, MIME_Type mt )


  //// login to other domain
  public UserID login() {
                    showMessage("You need to provide new login/password for access across domain");
                    //user are access a graph which is in another domain
                    //new login&password needed to access it

                    boolean ok=false;
                    MyDialog myd;
                    String v1=null,v2=null;

                    myd=new MyDialog( (Frame ) this,"New login needed for access across domain");
                    //myd=new MyDialog( (Frame) this.getParent(),"Input dialog");
                     while (!ok) {
                        myd.show();
                        v1=myd.getValue1();
                        v2=myd.getValue2();
                        System.out.println("v1="+v1);
                        System.out.println("v2="+v2);
                        if (v1 != null ) {
                              System.out.println("Register new login to server, please wait");
                        }else{
                            System.out.println("canceled");
                            return null;
                        }
                     }//while
                    return new UserID(v1,v2);
  }

  public Graph openGraph(URL url,int m) {
    Graph g=null;
    try {
        g = (Graph)jowGraphService.openGraph( url,m);
    } catch (JOWException e) {
       showError("Open Graph Fail");
       if(e.getType()==JOWException.USER_INVALID){

        showMessage("You need to provide new login/password for access across domain");
        boolean ok= false;
        while (!ok) {
          UserID userid = login();
          if (userid==null) return null;
          try {
            jowGraphService.registerUserToOtherRegion(userid, url);
             ok=true;
          }
           catch (JOWException e3) {
                             System.out.println("Registration failed");
          }
        } //// end while
       }
       else {
            //not a USER_INVALID exception, something else happend
//          System.out.println("GraphWindow.systemOpen cannot open grpah due to "+e);
            showError("Open Graph Fail due to "+e);
         }
      }
    return g;
  }

  public ContentObject openGraphContent(URL url) {
    ContentObject co=null;
    try {
        co = (ContentObject) jowGraphService.openGraphContent( url);
    } catch (JOWException e) {
        showError("Open Graph Content Fail");
      if(e.getType()==JOWException.USER_INVALID){
        showMessage("You need to provide new login/password for access across domain");
        boolean ok= false;
        while (!ok) {
          UserID userid = login();
          if (userid==null) return null;
          try {
            jowGraphService.registerUserToOtherRegion(userid, url);
             ok=true;
          }
           catch (JOWException e3) {
                             System.out.println("Registration failed");
          }
        } //// end while
      } else
        {
             showError("Open Graph Fail due to "+e);
        }
     }
    return co;
  }


  public void SystemOpen () {
    Graph g=null;

    // Qian:  logic to ask user for URL
    /*
    try {
        g = (Graph)jowGraphService.openGraph( dummyURL);
    } catch (JOWException e) {
        showError("Open Graph Fail");
      }
    Graph g = openGraph();
    */


    SystemOpenDialog dlgSysOpen=new SystemOpenDialog(this, "open a graph url");
    dlgSysOpen.show();
    String strURL=dlgSysOpen.getInputURLString();

    if(null!=strURL){
//        JavaAssert.println("url to be opened is "+strURL,2);
    }else{
//        JavaAssert.println("cancel button pressed",2);
        return;
    }

    URL urlToBeOpened=null;

    try{
        urlToBeOpened=new URL(strURL);
    }catch(MalformedURLException e){
            showError("malformed url in GraphWindow.SystemOpen due to "+e);
    }


    g = openGraph(urlToBeOpened, GDPermissionImpl.READ);




    if (g==null) return;
    source.addGraphWindow ( jowGraphService, g );
  }  // end SystemOpen

  public void SystemOpen ( URL url) {
   Graph g=null;
   System.out.println ("GraphWindow:  SystemOpen, url requested = "+url);
    //try {
      ////if (!editMode)
      //// ALWAYS READ MODE DEFAULT WHEN OPEN
      //{
        // read mode
        System.out.println("Read Mode Open");
        //g = (Graph)jowGraphService.openGraph( url, GDPermissionImpl.READ);
        g = openGraph( url, GDPermissionImpl.READ);
        if (g !=null) source.addGraphWindowForRead ( jowGraphService, g );
      //}
      /****
      else {
        // write mode
        System.out.println("Write Mode Open");
        g = (Graph)jowGraphService.openGraph( url,GDPermissionImpl.WRITE );
        source.addGraphWindow( jowGraphService, g,true );
        }
      ****/
      // register to applet with parent/child relationship
      source.GraphRelationTable.put(g.getUID(), aGraph.getUID());

      return;
      /*
    } catch (JOWException e) {
        System.out.println("Graph Window: Open Graph Fail."+e.getMessage());
      showError("Open Graph Error: "+e.getMessage());
      LabelDialog ld=new LabelDialog(this,"ERROR","Open Graph Error: "+e.getMessage());
      ld.show();
      }  */

  }  // end SystemOpen ( URL url)

  public void SystemRefresh() {

    try {
      showMessage("Reload the graph...");
      int temp;
      if (editMode) temp = GDPermissionImpl.WRITE;
         else temp = GDPermissionImpl.READ;
      Graph g = (Graph)jowGraphService.openGraph( aGraph.getUID(), temp );
      synchronized (aGraph) {
        aGraph=g;
        graphpanel.graph=g;
      }
      showMessage("Graph Refreshed.");
      return;
    } catch (JOWException e) {
        System.out.println("Graph Window: Open Graph Fail."+e.getMessage());
      showError("Open Graph Error: "+e.getMessage());
      LabelDialog ld=new LabelDialog(this,"ERROR","Open Graph Error: "+e.getMessage());
      ld.show();
      }
    disableRecoverNode();
  }

  public void SystemGoBack() {

    try {
      showMessage("Back to the parent graph...");

      // check if need to save
      if (isWrite())
      {

      MessageDialog msgd=new MessageDialog(this,"Alarm","Do you really want to save the graph before closing it");
      msgd.show();
      boolean ok=msgd.getValue();

        try {
          jowGraphService.closeGraph( aGraph,ok);
          } catch (JOWException e) {
          showError("Close Graph Fail"+e.getMessage());
        }
      }

      // get the parent graph

      URL pgurl = (URL) source.GraphRelationTable.get(aGraph.getUID()) ;
      if (pgurl == null) {
            showError("No parent Graph.");
            return;
       }
      Graph parentgraph = (Graph)jowGraphService.openGraph( pgurl);
      setMode(false);   // set as read mode
      synchronized (aGraph) {
        aGraph=parentgraph;
        graphpanel.graph=parentgraph;
      }
      this.setTitle("GraphWindow: Username("+source.userName+") Graph:("+aGraph.getLabel()+")");
      showMessage("Parent Graph Loaded.");
      return;
    } catch (JOWException e) {
        System.out.println("Graph Window: Open Graph Fail."+e.getMessage());
      showError("Open Graph Error: "+e.getMessage());
      LabelDialog ld=new LabelDialog(this,"ERROR","Open Graph Error: "+e.getMessage());
      ld.show();
      }

  }

  public void SystemImport() {

    // check if now it is in read mode
    if (this.isWrite()) {
        showError("Graph is in WRITE mode. Change to READ mode before you can import to the current Graph.");
        return;
    }
    // prompt with a dialog to get the  rootDirstr and rootURLstr
    ImportDataDialog importdialog = new ImportDataDialog(this);
    importdialog.show();
    String rootdir, rooturl;
    rootdir = importdialog.getValue1();
    rooturl = importdialog.getValue2();
    if (rootdir==null) return;
    if ((rooturl.trim().equals(""))) rooturl=null;
    // build a import utility
    try {
    DirWalkerForGraphImport importutil = new DirWalkerForGraphImport(rootdir,rooturl,this.jowGraphService);
   // begin import
    importutil.init();
    importutil.setRootGraph(aGraph.getUID().toString());
    System.out.println(aGraph.getUID().toString());
    // temp
    Dialog tmp = new Dialog(this, "Please wait...", false);
    tmp.show();
    importutil.importit();
    importutil.transform();
    tmp.hide();
    } catch (Exception e) {
        this.showError("import work failed");
      }
    }

  public void SystemExport() {
    // check if now it is in read mode
    if (this.isWrite()) {
        showError("Graph is in WRITE mode. Change to READ mode before you can import to the current Graph.");
        return;
    }

    ExportDataDialog exportdialog = new ExportDataDialog(this);
    exportdialog.show();
    String rootdir, exportrootdir;
    rootdir = exportdialog.getValue1();
    if (rootdir==null) return;
    exportrootdir = exportdialog.getValue2();
    //// Export work here
    WWWNGExport exportwork = new WWWNGExport(aGraph.getUID().toString(), rootdir,exportrootdir, jowGraphService);
    System.out.println("Export begin...");
    exportwork.export();
    System.out.println("End of Export!");
    return;
  }

  public void SystemClose () {

    //jowGraphService.saveGraphObject( aGraph );
    if (isWrite())
    {

    MessageDialog msgd=new MessageDialog(this,"Alarm","Do you really want to save the graph before closing it");
    msgd.show();
    boolean ok=msgd.getValue();

        try {
          jowGraphService.closeGraph( aGraph,ok);
          } catch (JOWException e) {
          showError("Close Graph Fail"+e.getMessage());
        }
    }
    this.hide();
    //this.dispose();
    source.removeWindow (this);
  }  // end SystemClose

  public void SystemSave () {
    //jowGraphService.saveGraphObject( aGraph );

   System.out.println ("GraphWindow Save Graph");

   try {

   showMessage("Saving the graph...");
   jowGraphService.saveGraph( aGraph );
   showMessage("Graph saved.");
    } catch (JOWException e) {
        showError("Save Graph Fail");
      }

  }  // end SystemSave

  public void NodeCreateContent ( MIME_Type mt,String label )  {
    Node n = aGraph.getSelectedNode();
    if ( n != null )  {
        int type = mt.getType();
        if ( type == MIME_Type.GRAPH )  {
            SystemNew( n, mt );
        }  else  {  // TEXT
            ContentObject co = new ContentObject ( aGraph );
            co.setType ( mt );
            n.setContent ( co.getUID() );
            n.setContentType ( mt );
            n.setLabel(label);
            source.addTextWindow ( jowGraphService, co );
        }  // end else
    }
  }  // end NodeCreateContent

  public void NodeOpenEdit ()  {
    Graph g = null;
    Node n = aGraph.getSelectedNode();
    if ( n != null )  {
        //// URL url = n.getContent();  hacking with Forwarding Mechanism ???
        URL url = graphEngine.getContentURL(n);

        if ( url == null )  {
        showError("No Content exist!");
        return; } // Qian:  add notice to user
        MIME_Type mt = n.getContentType();

        if ( mt.getType() == MIME_Type.GRAPH )  {
            //try {
                //g = (Graph)jowGraphService.openGraph( url );
                //source.addGraphWindow ( jowGraphService, g );
                SystemOpen(url);

            //} catch (JOWException e) {
            //    showError("Open Graph Fail."+e.getMessage() );
            //}
        }
        else  {  //ContentObject
         if ( mt.getType() == MIME_Type.TEXT )  {
           //try  {
           // ContentObject co = jowGraphService.openGraphContent ( url);
            ContentObject co = openGraphContent ( url);
            if (co !=null)   source.addTextWindow ( jowGraphService, co );
                else showError("Open Graph Content Fail.");
           //} catch (JOWException e) {
           //showError("Open Graph Content Fail."+e.getMessage());
           //}  // end catch
          }  // end else
         else
            showError("Edit of this content type is not Supported.");
        }
    }  // end if
  }  // end NodeOpenEdit

  public void NodeOpenDisplay ()  {
    Graph g;
    ContentObject co;
    Node n = aGraph.getSelectedNode();
    if ( n == null ) return;
    {
        //URL url = n.getContent();  ??? hacking with Forwarding
        URL url = graphEngine.getContentURL(n);

      if ( url == null )  {
        showError("No Content exist!");
        return; } // Qian:  add notice to user
        MIME_Type mt = n.getContentType();


        /*code added by Yufei Qian 052898 to support image mimetype*/

        if ( ( mt.getType() == MIME_Type.IMAGE) || ( mt.getType() == MIME_Type.TEXT ) )  {
                System.out.println("show image in graph window");
                try{
                 String strURLAssume=url.toString();
                 String strResolvedUserName=jowGraphService.resolveUserNameForURL(strURLAssume);

                      if (!jowGraphService.checkAclUserPermission( url,source.userName,GDPermissionImpl.READ))
                        { showError("User has no access to this specific content");  return;}
                      AppletContext ac = source.getAppletContext();
                     String strResolvedURL=jowGraphService.resolveURL(strURLAssume);

                //URL newurl=new URL(url.toString()+StrLock.encript(source.userName) );
                //URL newurl=new URL( GraphDomainServlet.DEFAULT_JAVASERVER +url.getFile().substring(1) + StrLock.encript(source.userName) );
//                URL newurl=new URL( GraphDomainServlet.DEFAULT_JAVASERVER +url.getFile().substring(1) + StrLock.encript(source.userName) );
                //URL newurl=new URL( GraphApplet.JAVA_SERVER +url.getFile().substring(1) + StrLock.encript(source.userName) );
                //System.out.println("url.getFile().substring(1)="+url.getFile().substring(1));
                //System.out.println(newurl.toString());
                ///// ac.showDocument ( newurl, "_blank" );
                URL newurl=new URL( strResolvedURL + StrLock.encript(strResolvedUserName) );
                ac.showDocument ( newurl, "ContentWin" );

                System.out.println("show to ContentWin");
               } catch (MalformedURLException urle) {
                  showError("MalformedURLException due to "+urle);
                }catch(JOWException e){
                       showError("JOWException due to "+e);
                }

        }
        /*end of code added by Yufei Qian 052898 to support image mimetype*/

        /*
        if ( mt.getType() == MIME_Type.TEXT )  {
            try {

              // read for checking ACL !!!!!
              if (!jowGraphService.checkAclUserPermission( url,source.userName,GDPermissionImpl.READ))
                { showError("User has no access to this specific content");  return;}
              AppletContext ac = source.getAppletContext();
              // in the near future, change the acl checking to the part of http response of URL content

              // showdocument ;
              try {
                //URL newurl=new URL(url.toString()+StrLock.encript(source.userName) );
//                URL newurl=new URL( GraphDomainServlet.DEFAULT_JAVASERVER +url.getFile().substring(1) + StrLock.encript(source.userName) );
                URL newurl=new URL( "http://warbler-cs.cs.unc.edu:8888/"  +url.getFile().substring(1) + StrLock.encript(source.userName) );
                System.out.println(newurl.toString());
                ac.showDocument ( newurl, "ContentWin" );
                System.out.println("show to ContentWin");
               } catch (MalformedURLException urle) {
                  System.out.println("URL exception !!!");
              }

           } catch (JOWException e) {
            System.out.println("Graph Window: Open Graph Content Fail."+e.getMessage());
           }  // end catch
        */
        else if ( mt.getType() == MIME_Type.GRAPH )  {
            //try {
                //g = (Graph)jowGraphService.openGraph( url );
                //source.addGraphWindowForRead ( jowGraphService, g );
                //source.NodeOpen();
                SystemOpen(url);

           // } catch (JOWException e) {
           //     showError("Open Graph Fail."+e.getMessage() );
           // }
        }  // end if

        else {
        //default action for other mime types
        showError("mime type not supported yet");
    }
    }  // end if
  }  // end NodeOpenDisplay

public void OpenContent()  {
    if ( editMode ) NodeOpenEdit();
    else NodeOpenDisplay();
}  //  end OpenContent

  public void HelpHelp () {
System.out.println ("HelpHelp in GraphWindow");
  }  // end HelpHelp


public void showNodeProperty() {
    if (aGraph.getSelectedNode() != null) {
        NodePropertyDialog nodepd=new NodePropertyDialog(this,aGraph.getSelectedNode(),editMode);
        nodepd.show();
    }
}

public void showGraphProperty() {
        GraphPropertyDialog graphpd=new GraphPropertyDialog(this,aGraph,editMode);
        graphpd.show();
        resetTitle();
}

// ***************************** Event Methods


// new Event methods updated for JDK1.1

// implement the WindowListener interface
public void windowActivated(WindowEvent e) {
}

public void windowClosed(WindowEvent e) {
}

public void windowClosing(WindowEvent e) {
        /******************************/
        SystemClose ();
        /******************************/
}

public void windowDeactivated(WindowEvent e) {
}

public void windowDeiconified(WindowEvent e) {
}

public void windowIconified(WindowEvent e) {
}

public void windowOpened(WindowEvent e) {
}


// Item Listener

public void itemStateChanged(ItemEvent e) {
    Object esource=e.getSource();

      if ( esource == preferenceEdit ) {
        //boolean current = preferenceEdit.getState();
        //System.out.println("preferenceEdit:  "+current);
        //preferenceDisplay.setState( !current );
        //editMode = current;
        //boolean current=preferenceEdit.getState();
        ////System.out.println("Edit item");
        //// preferenceEdit.setState(true);
        changeMode(true);
      }  //  end preferenceEdit

      else
      if ( esource == preferenceDisplay ) {
        //boolean current = preferenceDisplay.getState();
        ////System.out.println("Display item");
        changeMode(false);
        ////preferenceDisplay.setState(true);
      }
        else
        if ( esource == DisplayMoveNodeMI) {
          showMessage("change Cut Node Display Mode");
          //synchronized (aGraph)
          { DisplayMoveNode.setValue( ! DisplayMoveNode.getValue());
            DisplayMoveNodeMI.setState( DisplayMoveNode.getValue());
          }
          showMessage("change Cut Node Display Mode finished");
          //graphpanel.processGraph.start();
        }

}

/* mode = FINISHED then stop paste */
public void setPasteMode(int mode) {

  pasteMode = mode;
  if (mode != PASTE_FINISHED)
   {
    graphpanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    return;
   }
  else {
    graphpanel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    return;
  }
}

public int getPasteMode() {
  return pasteMode;
}
// Action Listener

public void actionPerformed(ActionEvent event) {

     //if (getPasteMode() != PASTE_FINISHED) {showMessage("In paste waiting mode"); return; }
     if (graphEngine.isSpecialWorking() ) {showMessage("In special mode."); return;}
        Object esource=event.getSource();
// Menu items

    if (esource instanceof MenuItem) {

      // System Menu Items

      if ( esource == systemNew ) {
        SystemNew ();
      }  //  end SystemNew
      if ( esource == systemOpen ) {
        SystemOpen ();
      }  //  end SystemOpen
      if ( esource == systemRefresh ) {
        graphpanel.notfrommenu=false;
        SystemRefresh ();
      }  //  end SystemOpen
      if ( esource == systemGoBack ) {
        graphpanel.notfrommenu=false;
        SystemGoBack ();
      }  //  end SystemOpen

      if ( esource == systemClose ) {
        SystemClose ();
      }  //  end SystemClose
      if ( esource == systemSave ) {
        graphpanel.notfrommenu=false;
        SystemSave ();
      }  //  end SystemSave

      if ( esource == systemImport ) {
        graphpanel.notfrommenu=false;
        SystemImport ();
      }  //  end SystemImport

      if ( esource == systemExport ) {
        graphpanel.notfrommenu=false;
        SystemExport ();
      }  //  end SystemImport


      // GraphMenu Items

      /*if ( esource == graphAutoLayout ) {
        graphpanel.GraphAutoLayout ();
      } */ //  end GraphAutoLayout

      if (esource ==graphProperty) {
        graphpanel.notfrommenu=false;

        showGraphProperty();
      }
      // Node Menu Items

      if ( esource == nodeAdd ) {
        graphpanel.NodeAdd ();
      }  //  end NodeAdd
      if ( esource == graphNet   ||
           esource == graphList  ||
           esource == graphTree  ||
           esource == textPlain  ||
           esource == textHTML) {
        MIME_Type mt = new MIME_Type();
        if ( esource == graphNet ) mt.setBoth(MIME_Type.GRAPH, MIME_Type.NET);
        if ( esource == graphList ) mt.setBoth(MIME_Type.GRAPH, MIME_Type.LIST);
        if ( esource == graphTree ) mt.setBoth(MIME_Type.GRAPH, MIME_Type.TREE);
        if ( esource == textPlain ) mt.setBoth(MIME_Type.TEXT, MIME_Type.PLAIN);
        if ( esource == textHTML ) mt.setBoth(MIME_Type.TEXT, MIME_Type.HTML);
System.out.println("******: MIME_Type="+mt.getType()+"/"+mt.getSubtype());
        graphpanel.notfrommenu=false;
        NodeCreateContent ( mt,"NULL");
      }  //  end nodeCreateContent

      if ( esource == nodeOpenEdit ) {
        graphpanel.notfrommenu=false;
        NodeOpenEdit ();
      }  //  end NodeOpenEdit

      if ( esource == nodeOpenDisplay ) {
        graphpanel.notfrommenu=false;
        NodeOpenDisplay();
      }  //  end nodeOpenDisplay

      if ( esource == nodeHyperlinks ) {
        graphpanel.notfrommenu=false;
        graphpanel.NodeHyperlinks ();
      }  //  end NodeHyperlinks
      if (esource == nodeLabel ) {
        graphpanel.notfrommenu=false;
        graphpanel.NodeLabel ();
      }  //  end NodeLabel
      if ( esource == nodeColor ) {
        graphpanel.NodeColor ();
      }  //  end NodeColor
      if ( esource == nodeProperty) {
        graphpanel.notfrommenu=false;
        showNodeProperty();
      }
      // Link Menu Items

      if ( esource == linkAdd ) {
        graphpanel.notfrommenu=false;
        graphpanel.LinkAdd ();
      }  //  end LinkAdd
      if ( esource == linkDelete ) {
        graphpanel.LinkDelete ();
      }  //  end LinkDelete

       //  end preferenceDisplay

      // Help Menu Items

      if (esource== aclmenu) {
        graphpanel.notfrommenu=false;
        buildAclWin();
      } /*if (esource ==readwritemenu) {
        changeMode();
      } */

      if ( esource == helpHelp ) {
        graphpanel.notfrommenu=false;
        HelpHelp ();
      }  //  end HelpHelp

      /*
      if ( esource == cutNodeMenu ) {
        showMessage("Want to Cut Object");
        if ( graphpanel.copyNode(MyClipBoard.CUT) ) showMessage("Cut Operation Succeeded!");
          else  showMessage("Cut Operation Failed!");
      }*/


      if ( esource == nodeDelete ) {
        showMessage("want to Delete Node");
        graphpanel.NodeDelete ();

      }  //  end NodeDelete

      if ( esource == nodeUnDelete) {
        showMessage("Undo Delete Node");
        // Undo ???
        undeleteNode();

      }

      if ( esource == copyMenu ) {
        showMessage("Want to Copy Object");
        if ( graphpanel.copyNode(GraphEngine.COPY) ) showMessage("Copying...");
          else  showMessage("Copy Operation Failed!");
      }

      if (esource == moveMenu) {
        showMessage("want to move Object");
        if (graphpanel.moveNode(GraphEngine.MOVE) ) showMessage("Moving...");
          else  showMessage("Move Operation Failed!");

      }

/*
      if ( esource == pasteContentReference ) {   //  reference
        showMessage("Want to Paste Object by reference");
        if ( graphpanel.pasteNodeByReference() )
            { showMessage("Paste Operation Succeeded!");
            }
          else  showMessage("Paste Operation Failed!");
       }
      if ( esource == pasteContentValue ) {
        showMessage("Want to Paste Content Object by one layer Content");
        if ( graphpanel.pasteNodeByValue(MyClipBoard.CLONE_ONELAYER) )
            { showMessage("Paste Operation Succeeded!");
            }
          else  showMessage("Paste Operation Failed!");
       }

      if ( esource == pasteByValueMenu ) {
        showMessage("Want to Paste Graph Object by one layer Content");
        if (graphpanel.pasteNodeByValue(MyClipBoard.CLONE_ONELAYER) )
            { showMessage("Paste Operation Succeeded!");
            }
          else  showMessage("Paste Operation Failed!");
       }
      if (esource == pasteByValueWithReferenceMenu) {
        showMessage("Want to Paste Object by one layer Reference");
        if ( graphpanel.pasteNodeByValue(MyClipBoard.CLONE_ONELAYER_REFERENCE))
            { showMessage("Paste Operation Succeeded!");
            }
          else  showMessage("Paste Operation Failed!");
       }
      if ( esource == pasteByValueRecursionMenu ) {
        showMessage("Want to Paste Object by recursion");
        if ( graphpanel.pasteNodeByValue(MyClipBoard.CLONE_RECURSION) )
            { showMessage("Paste Operation Succeeded!");
            }
          else  showMessage("Paste Operation Failed!");
      }
      if ( esource == pasteByValueRecursionWithReferenceMenu ) {
        showMessage("Want to Paste Object by recursion With Reference");
        if ( graphpanel.pasteNodeByValue(MyClipBoard.CLONE_RECURSION_REFERENCE) )
            { showMessage("Paste Operation Succeeded!");
            }
          else  showMessage("Paste Operation Failed!");
      }

*/


//// most lastest change  May 30
/*      if ( esource == pasteContentReference ) {   //  reference
        showMessage("Want to Paste Object by reference");
        setPasteMode(MyClipBoard.CLONE_REFERENCE);
       }
      if ( esource == pasteContentValue ) {
        showMessage("Want to Paste Content Object by one layer Content");
        setPasteMode(MyClipBoard.CLONE_ONELAYER);
       }

      if ( esource == pasteGraphValue ) {
        showMessage("Want to Paste Node by Value");
        PasteModeDialog modedialog = new PasteModeDialog(this);
        modedialog.show();
        int temp = modedialog.getValue();
        if (temp ==0) return;  // cancelled
        setPasteMode(temp);
       }
*/
/*
      if ( esource == pasteByValueMenu ) {
        showMessage("Want to Paste Graph Object by one layer Content");
        setPasteMode(MyClipBoard.CLONE_ONELAYER);
       }
      if (esource == pasteByValueWithReferenceMenu) {
        showMessage("Want to Paste Object by one layer Reference");
        setPasteMode(MyClipBoard.CLONE_ONELAYER_REFERENCE);
       }
      if ( esource == pasteByValueRecursionMenu ) {
        showMessage("Want to Paste Object by recursion");
        setPasteMode(MyClipBoard.CLONE_RECURSION);
      }
      if ( esource == pasteByValueRecursionWithReferenceMenu ) {
        showMessage("Want to Paste Object by recursion With Reference");
        setPasteMode(MyClipBoard.CLONE_RECURSION_REFERENCE);
      }
*/

 }  // end MenuItem
}



public void changeMode(boolean newmode) {
  LabelDialog ld;

  if (newmode==isWrite()) return;

  if (!newmode) { // CHANGE TO READ MODE
    // close it as write first
   try {
      //// preferenceEdit.setState( false );
      URL url=aGraph.getUID();

    MessageDialog msgd=new MessageDialog(this,"Alarm","Do you really want to save the (changed) graph before changing mode");
    msgd.show();
    boolean ok=msgd.getValue();

      if (ok) showMessage("Saving the graph...");
      jowGraphService.closeGraph(aGraph,ok);
      showMessage("Loading the graph with READ MODE...");
      Graph newGraph= (Graph) jowGraphService.openGraph( url);
      if (newGraph !=null) {
            aGraph=newGraph;
            graphpanel.graph=newGraph;
            //setTitle("Username("+source.userName+") Graph:("+aGraph.getLabel()+")");
            resetTitle();
            System.out.println("change to DISPLAY mode");
            newmode = false;
            setMode(false);

                }
           else showError("No graph for read available");
         } catch (JOWException e1) {
      //// preferenceEdit.setState( true );
            setMode(true);

            System.out.println("Graph Applet Change Mode Fail:"+e1.getMessage());
      showError("Change Mode to DISPLAY Fail:"+e1.getMessage());
            }

     }
  else
   try {
      //// preferenceDisplay.setState( false );
      showMessage("Loading the graph...");
      URL url=aGraph.getUID();
      Graph newGraph= (Graph) jowGraphService.openGraph( url, GDPermissionImpl.WRITE );
      if (newGraph !=null) {
            aGraph=newGraph;
            graphpanel.graph=newGraph;
            //setTitle("Username("+source.userName+") Graph:("+aGraph.getLabel()+")");
            resetTitle();

            System.out.println("change to WRITE mode");
            setMode(true);
                }
           else showError("No graph for write available");
         } catch (JOWException e2) {
            System.out.println("Graph Applet open Graph for EDIT Fail:"+e2.getMessage());
            showError("open Graph for Write Fail:"+e2.getMessage());
            setMode(false);
            //// preferenceDisplay.setState( true );
            return;
            }
    String name,name2;
    if (isWrite()) { name="Edit";}
      else { name="Display"; }
      //readwritemenu.setLabel("Change Mode to "+name2);
      //ld=new LabelDialog(this,"Reminder"," Mode is Changed to "+name);
      //ld.show();
      showMessage("Reminder: Mode has been changed to "+name);


}

public void adjustmentValueChanged(AdjustmentEvent event) {

// Scroll bar
  Scrollbar bar=(Scrollbar) event.getAdjustable();
	if ( bar == scrollbarV) {
	    System.out.println("vertical scrollbar");
		if (event.getAdjustmentType() == AdjustmentEvent.TRACK) {
		    System.out.println("TRACK"+event.getValue());
			int v = event.getValue();
			graphpanel.setOffScreenY(v);
			scrollbarV.setValue(v);
			Graphics g = graphpanel.getGraphics();
			graphpanel.update(g);
		}  // end SCROLL_ABSOLUTE
		if (event.getAdjustmentType() == AdjustmentEvent.BLOCK_INCREMENT) {
		    System.out.println("BLOCK_INCREMENT");
			int delta = scrollbarV.getPageIncrement();
			int v = graphpanel.bumpOffScreenY(delta );
			scrollbarV.setValue(v);
		}  // end SCROLL_PAGE_DOWN
		if (event.getAdjustmentType() == AdjustmentEvent.BLOCK_DECREMENT) {
		    System.out.println("BLOCK_DECREMENT");
			int delta = scrollbarV.getPageIncrement();
			int v = graphpanel.bumpOffScreenY(-delta );
			scrollbarV.setValue(v);
		}  // end SCROLL_PAGE_UP
		if (event.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT) {
		    System.out.println("UNIT_INCREMENT");
			int delta = scrollbarV.getLineIncrement();
			int v = graphpanel.bumpOffScreenY(delta );
			scrollbarV.setValue(v);
			Graphics g = graphpanel.getGraphics();
			graphpanel.update(g);
		}  // end SCROLL_LINE_DOWN
		if (event.getAdjustmentType() == AdjustmentEvent.UNIT_DECREMENT) {
		    System.out.println("UNIT_DECREMENT");
			int delta = scrollbarV.getLineIncrement();
			int v = graphpanel.bumpOffScreenY(-delta );
			scrollbarV.setValue(v);
			Graphics g = graphpanel.getGraphics();
			graphpanel.update(g);
		}  // end SCROLL_LINE_UP
	}  // end scrollbarV

	if ( bar == scrollbarH) {
		if (event.getAdjustmentType() == AdjustmentEvent.TRACK) {
			int v = event.getValue();
			graphpanel.setOffScreenX(v);
			scrollbarH.setValue(v);
			Graphics g = graphpanel.getGraphics();
			graphpanel.update(g);
		}  // end SCROLL_ABSOLUTE
		if (event.getAdjustmentType() == AdjustmentEvent.BLOCK_INCREMENT) {
			int delta = scrollbarV.getPageIncrement();
			int v = graphpanel.bumpOffScreenX(delta );
			scrollbarH.setValue(v);
		}  // end SCROLL_PAGE_DOWN
		if (event.getAdjustmentType() == AdjustmentEvent.BLOCK_DECREMENT) {
			int delta = scrollbarV.getPageIncrement();
			int v = graphpanel.bumpOffScreenX(-delta );
			scrollbarH.setValue(v);
		}  // end SCROLL_PAGE_UP
		if (event.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT) {
			int delta = scrollbarV.getLineIncrement();
			int v = graphpanel.bumpOffScreenX(delta );
			scrollbarH.setValue(v);
			Graphics g = graphpanel.getGraphics();
			graphpanel.update(g);
		}  // end SCROLL_LINE_DOWN
		if (event.getAdjustmentType() == AdjustmentEvent.UNIT_DECREMENT) {
			int delta = scrollbarV.getLineIncrement();
			int v = graphpanel.bumpOffScreenX(-delta );
			scrollbarH.setValue(v);
			Graphics g = graphpanel.getGraphics();
			graphpanel.update(g);
		}  // end SCROLL_LINE_UP
	}  // end scrollbarH

}




// ***************************** BuildWindow

   /*
   Since GraphWindow extends Frame, BuildWindow uses self
   as the outer container.  Hence, events are captured in
   this class.
   */


//  Global variables for window


   Menu systemMenu;
      MenuItem systemNew, systemOpen, systemRefresh, systemSave, systemClose,systemGoBack,
               systemImport, systemExport;

   Menu graphMenu;
      //MenuItem graphAutoLayout;
      MenuItem graphProperty;

   Menu nodeMenu;
      MenuItem nodeAdd, nodeDelete, nodeUnDelete, nodeOpenEdit, nodeOpenDisplay, nodeProperty, nodeHyperlinks,
         nodeLabel, nodeColor;
      MenuItem copyMenu;
      MenuItem moveMenu;
      Menu contentType;
      MenuItem graphNet, graphList, graphTree, textPlain, textHTML;

   Menu linkMenu;
      MenuItem linkAdd, linkDelete;

   Menu preferenceMenu;
      CheckboxMenuItem preferenceDisplay, preferenceEdit;
      CheckboxMenuItem DisplayMoveNodeMI;
   Menu manageMenu;
      MenuItem aclmenu;
      MenuItem readwritemenu;
   Menu helpMenu;
      MenuItem helpHelp;

   //Menu testMenu;
      MenuItem cutNodeMenu;


      MenuItem pasteContentReference;
      MenuItem pasteContentValue;  // non-graph content

      MenuItem pasteGraphValue;    // graph-content

/*
      Menu     pasteOneLevel;
      Menu     pasteNLevel;

      MenuItem pasteByValueMenu;               // 1 layer content
      MenuItem pasteByValueWithReferenceMenu;  // 1 layer reference

      MenuItem pasteByValueRecursionMenu;               // n layer content
      MenuItem pasteByValueRecursionWithReferenceMenu;  // n layer reference
*/

  public GraphPanel graphpanel; //area for graph
  Scrollbar scrollbarV, scrollbarH;
  //TextField messageArea;  // area for messages
  Label messageArea;
  int maxX = 1000;  // max size of virtual area for graphpanel
  int maxY = 1000;

  public void buildWindow () {

  Panel menuPanel;  // area for menus
  Panel bottomPanel;  // area for horizontal scrollbar

    graphpanel = new GraphPanel(this, aGraph, maxX, maxY);
    menuPanel = new Panel();
    bottomPanel = new Panel();  // area for scroolbar

    this.setLayout (new BorderLayout());
    bottomPanel .setLayout (new BorderLayout());
    menuPanel .setLayout (new FlowLayout());

    scrollbarV = new Scrollbar(1, 0, 250, 0, maxY);
    scrollbarV.setLineIncrement(10);
    scrollbarV.setPageIncrement(250);

    scrollbarH = new Scrollbar(0, 0, 250, 0, maxX);
    scrollbarH.setLineIncrement(10);
    scrollbarH.setPageIncrement(250);


    //messageArea = new TextField();
    //messageArea.setEditable(false);
    messageArea = new Label();
    messageArea.setText("messages");
    //messageArea.setBackground(Color.yellow);
    resetMessageColor();
    //messageArea.setBackground(Color.yellow);
    MenuBar mb = new MenuBar();

    systemMenu = new Menu("System");
      systemNew = new MenuItem ( "New" );
      systemMenu.add( systemNew );
      systemOpen = new MenuItem ( "Open" );
      systemMenu.add( systemOpen );
      systemRefresh=new MenuItem("Refresh");
      systemMenu.add(systemRefresh);
      systemGoBack=new MenuItem("Back");
      systemMenu.add(systemGoBack);
      systemSave = new MenuItem ( "Save" );
      systemMenu.add( systemSave );
      systemClose = new MenuItem ( "Close" );
      systemMenu.add( systemClose );
      systemMenu.addSeparator();
      systemImport=new MenuItem("Import");
      systemMenu.add(systemImport);
      systemExport=new MenuItem("Export");
      systemMenu.add(systemExport);

    graphMenu = new Menu("Graph");
    graphProperty=new MenuItem("Properties");
    graphMenu.add(graphProperty);

     // graphAutoLayout = new MenuItem ( "AutoLayout" );
     //graphMenu .add( graphAutoLayout );
     //  graphMenu.add(new CheckboxMenuItem("AutoLayout"));


    contentType = new Menu("Create Content");
      graphNet = new MenuItem ( "graph/net" );
      contentType.add ( graphNet );
      graphList = new MenuItem ( "graph/list" );
      contentType.add ( graphList );
      graphTree = new MenuItem ( "graph/tree" );
      contentType.add ( graphTree );
      textPlain = new MenuItem ( "text/plain" );
      contentType.add ( textPlain );
      textHTML = new MenuItem ( "text/html" );
      contentType.add ( textHTML );

      nodeMenu = new Menu("Node");
      nodeAdd = new MenuItem ( "Add" );
      nodeMenu .add( nodeAdd );
      nodeDelete = new MenuItem ( "Delete" );
      nodeMenu.add( nodeDelete );
      nodeUnDelete = new MenuItem("Undelete");
      nodeMenu.add( nodeUnDelete );
      nodeMenu.addSeparator();
      // begin Cut/Copy/Paste

      copyMenu= new MenuItem ( "Copy Node" );
      moveMenu= new MenuItem("Move Node");

      nodeMenu.add( copyMenu);
      nodeMenu.add( moveMenu);

      //// old stuff
      cutNodeMenu = new MenuItem("Cut Node");
      pasteContentReference= new MenuItem ( "Paste by Reference" );
      pasteContentValue = new MenuItem("Paste by Value");
      pasteGraphValue = new MenuItem("Paste by Value");  // for radiobutton check
      pasteContentReference.addActionListener(this);
      pasteContentValue.addActionListener(this);
      pasteGraphValue.addActionListener(this);


      /*
      pasteOneLevel = new Menu("One Layer");
      pasteNLevel = new Menu("Traversing");

      pasteByValueMenu= new MenuItem ( "Value of non-graph content" );
      pasteByValueWithReferenceMenu= new MenuItem ( "Reference to non-graph content" );

      pasteByValueRecursionMenu= new MenuItem ( "Value of non-graph content" );
      pasteByValueRecursionWithReferenceMenu= new MenuItem ( "Reference to non-graph content" );

      pasteByValueMenu.addActionListener(this);
      pasteByValueWithReferenceMenu.addActionListener(this);
      pasteByValueRecursionMenu.addActionListener(this);
      pasteByValueRecursionWithReferenceMenu.addActionListener(this);

      pasteOneLevel.add(pasteByValueWithReferenceMenu);
      pasteOneLevel.add(pasteByValueMenu);

      pasteNLevel.add(pasteByValueRecursionWithReferenceMenu);
      pasteNLevel.add(pasteByValueRecursionMenu);
      pasteGraphValue.add(pasteOneLevel);
      pasteGraphValue.add(pasteNLevel);
      */

      ////nodeMenu.add( cutNodeMenu);

      ////nodeMenu.add( pasteContentReference);
      ////nodeMenu.add( pasteContentValue);

      ////setPasteMenu(source.pasteMode);  // if true  Graph Menu



      // end Cut/Copy/Paste


      nodeMenu.addSeparator();

      nodeMenu .add( contentType );
      nodeOpenEdit = new MenuItem ( "Edit Content" );
      nodeMenu .add( nodeOpenEdit );
      nodeOpenDisplay = new MenuItem ( "Display Content" );
      nodeMenu .add( nodeOpenDisplay );
      nodeMenu.addSeparator();
      nodeLabel = new MenuItem ( "Label" );
      nodeMenu.add( nodeLabel );
      nodeProperty=new MenuItem("Properties");
      nodeMenu.add(nodeProperty);
      //nodeColor= new MenuItem ( "Color" );
      //nodeMenu .add( nodeColor);
      nodeMenu.addSeparator();
      nodeHyperlinks = new MenuItem ( "Hyperlinks" );
      nodeMenu .add( nodeHyperlinks );

    linkMenu = new Menu("Link");
      linkAdd = new MenuItem ( "Add" );
      linkMenu .add( linkAdd );
      linkDelete = new MenuItem ( "Delete" );
      linkMenu .add( linkDelete );

    preferenceMenu = new Menu("Preferences");
      preferenceEdit = new CheckboxMenuItem ( "Edit", false );
      preferenceMenu.add( preferenceEdit );
      preferenceDisplay = new CheckboxMenuItem ( "Display", true );
      preferenceMenu.add( preferenceDisplay );
      preferenceMenu.addSeparator();
      DisplayMoveNodeMI = new CheckboxMenuItem("Display Moved Node", false);
      DisplayMoveNode.setValue(false);
      preferenceMenu.add( DisplayMoveNodeMI );

    manageMenu = new Menu("Admin");
      aclmenu=new MenuItem("ACL...");

    //manageMenu.add(readwritemenu);
    manageMenu.add(aclmenu);

    aclmenu.addActionListener(this);
    //readwritemenu.addActionListener(this);

    helpMenu = new Menu ("Help");
      helpHelp= new MenuItem ( "Help" );
      helpMenu.add( helpHelp);

    //testMenu = new Menu ("Edit");

    mb.add(systemMenu);
    mb.add(graphMenu);
    mb.add(nodeMenu);
    mb.add(linkMenu);
    //mb.add(testMenu);
    mb.add(preferenceMenu);

    mb.add(manageMenu);
    mb.add(helpMenu);


    mb.setHelpMenu(helpMenu);

    this.setMenuBar(mb);

    bottomPanel.add("North", scrollbarH);
    bottomPanel.add("South", messageArea);

    graphpanel.setBackground(Color.white);
    graphpanel.setForeground(Color.blue);

    //this.setTitle("Graph Browser");

    this.add("Center", graphpanel);
    this.add("South", bottomPanel);
    this.add("East", scrollbarV);

    //add listener to this

    scrollbarV.addAdjustmentListener(this);
    scrollbarH.addAdjustmentListener(this);

    systemMenu.addActionListener(this);
    systemNew.addActionListener(this);
    systemOpen.addActionListener(this);
    systemRefresh.addActionListener(this);
    systemGoBack.addActionListener(this);
    systemSave.addActionListener(this);
    systemClose.addActionListener(this);
    systemImport.addActionListener(this);
    systemExport.addActionListener(this);
    graphProperty.addActionListener(this);

    graphNet.addActionListener(this);
    graphList.addActionListener(this);
    graphTree.addActionListener(this);
    textPlain.addActionListener(this);
    textHTML.addActionListener(this);
    nodeMenu.addActionListener(this);
    nodeAdd.addActionListener(this);
    nodeDelete.addActionListener(this);
    nodeUnDelete.addActionListener(this);

    contentType.addActionListener(this);
    nodeOpenEdit.addActionListener(this);
    nodeOpenDisplay.addActionListener(this);
    nodeLabel.addActionListener(this);
    nodeProperty.addActionListener(this);
    nodeHyperlinks.addActionListener(this);

    linkAdd.addActionListener(this);
    linkDelete.addActionListener(this);

    preferenceEdit.addItemListener(this);
    preferenceDisplay.addItemListener(this);
    DisplayMoveNodeMI.addItemListener(this);
    helpHelp.addActionListener(this);

    cutNodeMenu.addActionListener(this);
    copyMenu.addActionListener(this);
    moveMenu.addActionListener(this);

    this.addWindowListener(this);

    this.resize(600, 500);
    this.show();

  }  // end buildWindow

    public void setPasteMenu(boolean type) {
        // type = true;  Menu for Graph
        // type = false; Menu for Content
        //if (type == source.pasteMode) return;
        source.pasteMode=type;
        if (type) {
            // Menu for Graph
            //// nodeMenu.remove(pasteContentValue);        changed for popup???
            //// nodeMenu.insert(pasteGraphValue,6);
            }
         else {
            // Menu for Content
            //// nodeMenu.remove(pasteGraphValue);          changed for popup???
            //// nodeMenu.insert(pasteContentValue,6);
          }

    }


   public void setMenuEnabled(boolean mode)
   {
      systemMenu.setEnabled(mode);
      graphMenu.setEnabled(mode);
      nodeMenu.setEnabled(mode);
      preferenceMenu.setEnabled(mode);
      manageMenu.setEnabled(mode);
      helpMenu.setEnabled(mode);

      if (mode) setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        else setCursor(new Cursor(Cursor.HAND_CURSOR));
      setReadWrite();
      linkMenu.setEnabled(mode);
   }

}  // end GraphWindow




