package dom;

/*
 * 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 com.jniwrapper.win32.ie.dom.HTMLElement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import core.BasicSample;

/**
 * This sample loads Google page, enters "JExplorer" in text field and clicks on Seach button.
 *
 * @author Alexei Orischenko
 */
public class SubmitFormSample extends BasicSample
{
    public SubmitFormSample()
    {
        super("Submit Form");
    }

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

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

        browser.navigate("http://google.com");
        browser.waitReady();

        // find text field in the page
        Element textInput = getTextInput(browser.getDocument());
        textInput.setAttribute("value", "JExplorer");

        // find Search button in the page
        HTMLElement searchButton = getSearchButton(browser.getDocument());

        showMessage("Submit form");
        searchButton.click();
    }

    private static Element getTextInput(Document document)
    {
        NodeList inputs = document.getElementsByTagName("input");

        for (int i = 0; i < inputs.getLength(); i++)
        {
            Element input = (Element) inputs.item(i);
            String type = input.getAttribute("type").toLowerCase();

            if ("text".equals(type))
            {
                return input;
            }
        }

        return null;
    }

    private static HTMLElement getSearchButton(Document document)
    {
        NodeList inputs = document.getElementsByTagName("input");
        for (int i = 0; i < inputs.getLength(); i++)
        {
            HTMLElement input = (HTMLElement) inputs.item(i);
            String name = input.getAttribute("name");

            if ("btnG".equals(name))
            {
                return input;
            }
        }

        return null;
    }

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