(function() {
  var Cu = Components.utils;
  var Ci = Components.interfaces;
  var Cc = Components.classes;

  var jsm = { };
  Cu["import"]("resource://livemargins/webjsm.js", jsm);
  Cu["import"]("resource://livemargins/utils.jsm", jsm);

  var webjsm = new jsm.WebJsModule(window);
  webjsm.importScript("resource://livemargins/3rd/jquery.js");

  var logger = new jsm.utils.logger("lm4.gallery");
  var contentAPI = {
    log: function(msg) {
      logger.trace(msg);
    },

    ajax: function(options) {
      webjsm.jQuery.ajax(options);
    },

    setRequestHeader: function(request, header, value) {
      request.setRequestHeader(header, value);
    },

    makeObjAccessible: function(obj) {
      return jsm.utils.exposeReadOnly(obj);
    }
  };

  function init() {
    var appWin = document.getElementById("player_browser").contentWindow;
    var href = appWin.document.location.href;
    if (href.indexOf("resource://livemargins/apps/weather/weather.html") !== 0) {
      return;
    }

    var sandbox = new Cu.Sandbox(appWin);
    sandbox.window = appWin;
    sandbox.__proto__ = sandbox.window;
    sandbox.contentAPI = jsm.utils.exposeReadOnly(contentAPI);

    function evalInSandbox(url, sandboxObj, version) {
      Cu.evalInSandbox(jsm.utils.getContentFromURL(url), sandboxObj, version);
    }

    evalInSandbox("resource://livemargins/3rd/jquery.js",
                  sandbox, "1.8", "jquery.js");
    evalInSandbox("resource://livemargins/apps/weather/weather.js",
                  sandbox, "1.8", "weather.js");

    sandbox.init();

    appWin.addEventListener("unload", function() {
      delete sandbox.__proto__;
      for (var attr in sandbox) {
        delete sandbox[attr];
      }
    }, false);
  }

  var _progListener = new jsm.utils.browserLoadListener(null, init, null);
  // Can not listen to the "load" event, if xul is opened in dialog.
  // Don't know why.
  // Using progress listener to capture the load event instead.
  let playerBrowser = document.getElementById("player_browser");
  window.addEventListener("load", function() {
    let flag = Ci.nsIWebProgress.NOTIFY_ALL | Ci.nsIWebProgress.NOTIFY_STATE_ALL;
    playerBrowser.addProgressListener(_progListener, flag);
  }, false);

  window.addEventListener("unload", function() {
    let flag = Ci.nsIWebProgress.NOTIFY_ALL | Ci.nsIWebProgress.NOTIFY_STATE_ALL;
    playerBrowser.removeProgressListener(_progListener, flag);
  }, false);
})();

