var timerid;
var didRedirect = false;

function onReadyStateChange()
{
  var redirected = false;
  var state = this.readyState;
  if (state == this.DONE) {
    if (this.status == 200) {
      redirected = this.responseText.toUpperCase().indexOf(app.validityId) < 0;
      console.log("XMLHttpRequest response " + (redirected ? "redirected" : "valid"));
      if (redirected) {
        timerid = setTimeout(check, 4000);
        onRedirected();
      } else
        onReady();
    } else {
      console.log("XMLHttpRequest status: "+ this.status);
      timerid = setTimeout(check, 4000);
    }
  }
}

function check()
{
  if (timerid) {
    clearTimeout(timerid);
    timerid = null;
  }

  if (app.network.available) {
    if (app.validityId) {
      console.log("Starting XMLHttpRequest for " + app.mainUrl);
      var req = new XMLHttpRequest();
      req.onreadystatechange = onReadyStateChange;
      req.open("GET", app.mainUrl);
      req.send();
    } else {
      console.log("Reloading page (no validity id) " + app.mainUrl);
      onReady();
    }
  } else
    timerid = setTimeout(check, 1000);
}

function init()
{
  const kWidth = 563;
  const kHeight = 560;

  appWindow.resizeTo(kWidth, kHeight, false);
  appWindow.setMinContentSize(kWidth, kHeight);
  appWindow.center();

  app.events.register("network.available", check);
  addEventListener("unload", function() {
    app.events.unregister("network.available", check);
  }, false);

  timerid = setTimeout(check, app.validityId ? 250 : 5000);

  var tryagain = document.getElementById('tryagain');
  if (tryagain)
    tryagain.addEventListener("click", onReady, false);

  appWindow.oncontextmenu = onContextMenu;
  addEventListener("unload", function() {
    appWindow.oncontextmenu = null;
  }, false);

}

function onContextMenu(menu)
{
  menu.deleteItemByTag( [9, 10, 40005, 40006] );
}

function onReady()
{
  document.location = app.mainUrl;
}

function onRedirected()
{
  if (!didRedirect) {
    didRedirect = true;
    app.system.openExternal("http://www.aim.com");
  }
}

addEventListener("load", init, true);
addEventListener("dblclick", check, true);
