var Cu = Components.utils;
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cr = Components.results;

var jumlib = {};
Components.utils.import("resource://mozmill/modules/jum.js", jumlib);

Cu.import("resource://unity/unity-window-helper.js");

var topsrcDir;
const ITERATIONS = 100;

function openTab(controller) {
    var self = { opened: false };
    function checkTabOpened() { self.opened = true; }
    controller.window.addEventListener("TabOpen", checkTabOpened, false);

    controller.mainMenu.click("#menu_newNavigatorTab");

    try {
      controller.waitFor(function () {
        return self.opened;
      }, "New tab has been opened");
    } finally {
      controller.window.removeEventListener("TabOpen", checkTabOpened, false);
    }
}

function setupModule(module) {
    var localFile = Components.classes["@mozilla.org/file/local;1"]
        .createInstance(Components.interfaces.nsILocalFile);
    localFile.initWithPath(module.__file__);
    topsrcDir = localFile.parent.parent.path;

    module.controller = mozmill.getBrowserController();
}

function test1() {
    var size = controller.tabs.length;
    for (var i = 0; i < ITERATIONS; i++) {
	openTab(controller);
	controller.open(topsrcDir + '/html-tests/dnd/2.html');
	controller.waitForPageLoad();

	var windowHelper = new UnityWindowHelper(new XPCNativeWrapper(controller.tabs.activeTab.defaultView));
	windowHelper.makeCloseCallback()();
    }
    jumlib.assertEquals(controller.tabs.length, size);
}

function test2() {
    var callbacks = [];
    var size = controller.tabs.length;
    for (var i = 0; i < ITERATIONS; i++) {
	openTab(controller);
	controller.open(topsrcDir + '/html-tests/dnd/2.html');
	controller.waitForPageLoad();

	callbacks.push((new UnityWindowHelper(new XPCNativeWrapper(controller.tabs.activeTab.defaultView))).makeCloseCallback());
    }

    for (var i = 0; i < ITERATIONS; i++) {
	callbacks[i]();
    }
    jumlib.assertEquals(controller.tabs.length, size);
}
