package core.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 com.jniwrapper.win32.ie.event.NewWindowEventHandler;
import core.BasicSample;
import org.w3c.dom.Element;

/**
 * This sample demonstrates browser listener
 * that forces to open new page in the same window instead new window.
 *
 * @author Alexei Orischenko
 */
public class SameWindowNavigationSample extends BasicSample
{
    public SameWindowNavigationSample()
    {
        super("Same Window Navigation");
    }

    protected void execute()
    {
        WebBrowser browser = getBrowser();
        browser.setNewWindowHandler(new NavigationHandler(browser));

        String content = "<html><body><a href=\"http://google.com\">Google</a><br />" +
                "<input type='button' onclick=\"window.open('google.com')\" value='Open New Window'>" +
                "</body></html>";

        browser.setContent(content);
    }

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

class NavigationHandler implements NewWindowEventHandler
{
    private WebBrowser _browser;

    public NavigationHandler(WebBrowser browser)
    {
        _browser = browser;
    }

    public NewWindowAction newWindow()
    {
        System.out.println("new window");

        try
        {
            String url = getUrl();
            System.out.println("url = " + url);

            if (url != null)
            {
                _browser.navigate(url);
            }
        }
        catch (Exception e)
        {
        }

        return new NewWindowAction(NewWindowAction.ACTION_CANCEL);
    }

    private String getUrl()
    {
        Element activeElement = _browser.getDocument().getActiveElement();
        String tagName = activeElement.getTagName();

        if ("a".equalsIgnoreCase(tagName))
        {
            return activeElement.getAttribute("href");
        }
        else
        {
            // button, other
        }

        return null;
    }
}
