(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();
	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);
		}
	}
	
	function init() {
		var appWin = document.getElementById("player_browser").contentWindow;
		if (appWin.document.location.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 = contentAPI;
		
		Cu.evalInSandbox(jsm.utils.getContentFromURL("resource://livemargins/3rd/jquery.js"),           sandbox, "1.8", "jquery.js");	
		Cu.evalInSandbox(jsm.utils.getContentFromURL("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.
	window.addEventListener("load", function() {
		document.getElementById("player_browser").addProgressListener(_progListener, Ci.nsIWebProgress.NOTIFY_ALL | Ci.nsIWebProgress.NOTIFY_STATE_ALL);
	}, false);
	
	window.addEventListener("unload", function() {
		document.getElementById("player_browser").removeProgressListener(_progListener, Ci.nsIWebProgress.NOTIFY_ALL | Ci.nsIWebProgress.NOTIFY_STATE_ALL);	
	}, false);
})();
