import java.applet.*;
import java.awt.*;
import java.util.*;
import java. net.*;

public class ImageButton extends Applet
{
 int i = 1;
 int x, y, x2, y2;
 MediaTracker tracker;
 Vector areas, sta, urls, images, music;
 String imagename, status, about;
 String nextarea;
 Image image, img, im;
 StringTokenizer st;
 URL u;
 Graphics g;
 int X, Y;
 Rectangle r, rl;
 AudioClip sound;

public void init()
{
 tracker = new MediaTracker(this);
 areas = new Vector();
 sta = new Vector();
 urls = new Vector();
 images = new Vector();
 music = new Vector();
  
 
about = getParameter("author Rain Ausmaa|rainex@sgic.fi"); //pieni suojaus
if (about != null) 
imagename = getParameter("imagename");

 image = getImage(getDocumentBase(), imagename);
 tracker.addImage(image, 0);
 
 while ((nextarea = getParameter("area" + i++)) != null)
{
  st = new StringTokenizer(nextarea, ",");
 
  x = Integer.parseInt(st.nextToken());
  y = Integer.parseInt(st.nextToken());
  x2 = Integer.parseInt(st.nextToken());
  y2 = Integer.parseInt(st.nextToken());
  r = new Rectangle(x, y, x2, y2);
  areas.addElement(r);

  status = new String(st.nextToken());
  sta.addElement(status);
 
  img = getImage(getDocumentBase(), st.nextToken());
  images.addElement(img);
  tracker.addImage(img, 1);
  
  sound = getAudioClip(getDocumentBase(), st.nextToken());
  music.addElement(sound);
 
 try {
 u = new URL(getDocumentBase(), st.nextToken());
 urls.addElement(u);
     }
 
 catch (MalformedURLException e) {}

}

try { tracker.waitForID(0); tracker.waitForID(1); im = image;}
catch (InterruptedException e) {}

}
public void paint(Graphics g)
{
  g.drawImage(im, X, Y, this);
}

public void update(Graphics g)
{
 paint(g);
}



public boolean mouseMove(Event evt, int x, int y)
{
  Rectangle newRect = findRectangle(x, y);
  if(newRect != null)
  {
  r = (Rectangle) areas.elementAt(areas.indexOf(newRect));
  status = (String) sta.elementAt(areas.indexOf(newRect));
  img = (Image) images.elementAt(areas.indexOf(newRect));
  im = img; X = r.x; Y = r.y; 
  showStatus(status);
  
  }
  else { 
        im = image; X = 0; Y = 0; showStatus(""); //rl = r;
       } 
repaint();
return true;
 
}


public boolean mouseExit(Event evt, int x, int y)
{
  im = image; X = 0; Y = 0; showStatus(""); 
  //rl = r;
 repaint();  
 return true;
}


public boolean mouseDown(Event evt, int x, int y)
{
 Rectangle newRect = findRectangle(x, y);
 if(newRect != null)
  {
   sound = (AudioClip) music.elementAt(areas.indexOf(newRect));
   u = (URL) urls.elementAt(areas.indexOf(newRect));
   getAppletContext().showDocument(u);
   sound.play();
  }
    
  return true;

}

Rectangle findRectangle(int x, int y)
{
 Enumeration e = areas.elements();
 Rectangle p = null;
 
 while(e.hasMoreElements())
 {
  p = (Rectangle)e.nextElement();
  if(p.inside(x, y)) return p;
 }
 return null;
}

}
