package examples.htmlkona;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import weblogic.html.*;

/**
 * This servlet uses Javascript for client-side processing.
 * 
 * @author Copyright (c) 1996-98 by WebLogic, Inc. All Rights Reserved.
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class SimpleFormWithJavascript extends HttpServlet {

  public synchronized void service(HttpServletRequest req, HttpServletResponse res) 
    throws IOException
  {
    try {
      res.setStatus(HttpServletResponse.SC_OK);
      res.setContentType("text/html");

      ServletPage hp = new ServletPage("Simple Form with Javascript");

      FormElement form = new FormElement("", "GET");

      // Make a table element for arranging the fields on the form
      TableElement tab = new TableElement();

      // Add the table to the Element
      form.addElement(tab);

      // Add one new row, and use addElement() to add 3 cells to the row
      tab.addElement(new TableRowElement()
		     .addElement(new InputElement("input")
				 .setValue("9 + 3")
				 .setSize(20)
				 .setMaxlen(20))
		     .addElement(new InputElement("button1", FieldType.button)
				 .setValue("Evaluate")
				 .setOnClick("compute(this.form)"))
		     .addElement(new InputElement("answer")
				 .setValue("The answer is: 12")
				 .setSize(20)
				 .setMaxlen(20)));
      
      // Use the getBodyElement() method to set attributes for the BODY tag.
      hp.getBodyElement()
	.setAttribute(BodyElement.bgColor, HtmlColor.white);
      
      // Call getBody() to add various elements to the page.
      hp.getBody()
        .addElement(MarkupElement.HorizontalRule)
        .addElement(new ScriptElement("document.write(\"This is a simple JavaScript "
				      + "Expression Evaluator.\")")) 
        .addElement(MarkupElement.BeginParagraph)
        .addElement(new ScriptElement("document.write(\"Enter an expression on the "
				      + "left and click on Evaluate.\")"))
	// Note that we use "\n" to force newlines in the ScriptElement to make
	// the JavaScript code line up properly.
        .addElement(new ScriptElement("function compute(form) {\n" + 
                    "  if (confirm(\"Evaluate Expression \" + form.input.value + \" ?\"))\n" + 
                    "    form.answer.value = \"The answer is: \" + eval(form.input.value);\n" +
                    "  else\n" +
                    "    alert(\"Try again and choose OK.\");\n" + 
                    "}"))
	
	// Finally, add the form to the page.
        .addElement(form)
        .addElement(MarkupElement.HorizontalLine)
	.addElement("Copyright 1996-2000 by BEA Systems, Inc. All Rights Reserved.");

      // Call the htmlKona output method with the return from the
      // ServletResponse object's getOutputStream() method
      hp.output(res.getOutputStream());
    }
    catch (Exception e) {
      defaults.showException(e, res.getOutputStream());
    }
  }
}
