package core;

/*
 * 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 javax.swing.JOptionPane;
import java.awt.Component;

/**
 * This sample accesses and changes javascript variables and attributes of DOM elements.
 *
 * @author Alexei Orischenko
 */
public class JavascriptSample extends BasicSample
{
    private static final String HTML_CONTENT =
            "<html><head>" +
            "<script>var counter = 1;</script>" +
            "</head><body>" +
            "<div id='theDiv'>initial text</div>" +
            "</body></html>";

    public JavascriptSample()
    {
        super("JavaScript");
    }

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

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

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

        // Get JavaScript counter variable
        String counter = (String) browser.executeScript("counter");
        info("counter variable = " + counter);
        String content = (String) browser.executeScript("document.all.theDiv.innerHTML");
        info("content of the div: " + content);

        showLog();

        JOptionPane.showMessageDialog((Component) browser, "The sample executes JavaScript");

        // Set JavaScript counter variable
        browser.executeScript("counter = 7;");

        clearLog();

        counter = (String) browser.executeScript("counter");
        info("counter variable = " + counter);

        browser.executeScript("document.all.theDiv.innerHTML = 'updated text'");

        content = (String) browser.executeScript("document.all.theDiv.innerHTML");
        info("content of the div: " + content);

        showLog();
    }

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