package dom.event;

/*
 * Copyright (c) 2002-2007 TeamDev Ltd. All rights reserved.
 *
 * Use is subject to license terms.
 *
 * The complete licence text can be found at
 * http://www.teamdev.com/winpack/license.jsf
 */

import com.jniwrapper.win32.ie.WebBrowser;
import org.w3c.dom.Element;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import core.BasicSample;

/**
 * This sample demonstrates the technique of adding onchange event listener to select element.
 *
 * @author Alexei Orischenko
 */
public class SelectElementSample extends BasicSample
{
    private static final String HTML_CONTENT = "<html>" +
                    "<body>" +
                    "Product: " +
                    "<select id='product'>" +
                    "<option value='pizza'>Pizza</option>" +
                    "<option value='ice_cream'>Ice Cream</option>" +
                    "</select>" +
                    "</body>" +
                    "</html>";

    public SelectElementSample()
    {
        super("Element Event Listener");
    }

    protected void execute()
    {
        WebBrowser browser = getBrowser();

        // wait when the browser will be ready to work
        browser.waitReady();

        browser.setContent(HTML_CONTENT);
        browser.waitReady();

        Element select = browser.getDocument().getElementById("product");

        setupChangeListener(select);

        showMessage("Please choose product.");
    }

    private void setupChangeListener(final Element select)
    {
        EventTarget eventTarget = (EventTarget)select;

        eventTarget.addEventListener("onchange", new EventListener()
        {
            public void handleEvent(Event evt)
            {
                Element target = (Element) evt.getTarget();

                // Gets current value of select target
                String value = target.getAttribute("value");
                showMessageSwingLoop("Selected product: " + value);
            }
        }, false);
    }

    public static void main(String[] args) throws Exception
    {
        new SelectElementSample().run();
    }
}
