package e4s.tutorial;

import e4s.html.*;
import e4s.html.E4JavaScript.JSBODY;
import e4s.html.input.extended.*;
import e4s.servlet.E4ModuleImplementation;

/**
 * CHECKBOX Input element example. Shows how to use checkboxes and changing their values by the onclick.
 */
public class Example_CHECKBOX extends E4ModuleImplementation
{
   public static E4Method start = null;
   public static E4Method saveForm = null;
   
   // Define any generic names for three checkboxes
   private final static E4InputFieldName PARAM_CB_1 = E4InputFieldName.ANY();
   private final static E4InputFieldName PARAM_CB_2 = E4InputFieldName.ANY();
   private final static E4InputFieldName PARAM_CB_3 = E4InputFieldName.ANY();
   
   public void start( HTML html )
   {
      BODY body = html.BODY();
      body.Message(E4Message.CAPTION,"Checkbox example");
      body.P();
      
      // this is our form, when the user presses the submit button it will call function saveForm
      FORM form = body.FORM(saveForm);
      
      // this is a fieldset for layout purposes only
      E4Fieldset fieldset = form.FIELDSET();
      
      // this is creation of checkbox #1
      CHECKBOX cb1 = fieldset.CHECKBOX(PARAM_CB_1, "Checkbox One");
      cb1.setValue(true);
      
      // this is creation of checkbox #2, later it will become a E4JavaScript triggered by "onClick"
      CHECKBOX cb2 = fieldset.CHECKBOX(PARAM_CB_2, "Checkbox Two (changes #3 by onClick)");
      cb2.setLabelPosition(CHECKBOX.LABEL_POSITION_LEFT);
      
      // this is creation of checkbox #3
      CHECKBOX cb3 = fieldset.CHECKBOX(PARAM_CB_3, "Checkbox Three");

      // the submit button to the form
      form.P();
      form.BUTTON_Submit("Continue");

      // add a java script (event handler triggered by the onClick event) to checkbox-2 and toggle
      // the value of checkbox 3 depending on the value of checkbox 2. Please keep in mind, that
      // the onChange() trigger will not work when you click unless you do a keyboad input
      E4EventHandlerInputField evt = cb2.onClick();
      E4JavaScript.JSBODY jsBody = evt.JSBODY();
      
      jsBody.appendln("var frm = document.forms['" + form.getName() + "'];");
      jsBody.appendln("var boo = frm.elements." + cb2.getHtmlParamName() + ".checked;");
      jsBody.appendln("frm.elements." + cb3.getHtmlParamName() + ".checked = ! boo;");
   }
   
   /**
    * Called when the form becomes submitted.
    */
   public void saveForm( HTML html, E4CgiParams params )
   {
      html.println("Checkbox One has a value of " + params.getBool(PARAM_CB_1));
      html.BR();
      html.println("Checkbox Two has a value of " + params.getBool(PARAM_CB_2));
      html.BR();
      html.println("Checkbox Three has a value of " + params.getBool(PARAM_CB_3));
      html.P();
      
      html.A(start).println("start again");
   }
}