(function() {
	var jsm = { };
	Components.utils["import"]("resource://livemargins/utils.jsm", jsm);
	Components.utils["import"]("resource://livemargins/intent.jsm", jsm);
	Components.utils['import']('resource://livemargins/appcenter.jsm', jsm);
	
	function _getAppUID() {	
		return widget.args.id;
	}
	
	document.getElementById("player_browser").addEventListener("DOMContentLoaded", function(evt) {
		if (!(evt.originalTarget instanceof HTMLDocument)) {
			return;
		}
		
		var view = evt.originalTarget.defaultView;
		if (!view || view.top != view) {
			return;
		}
		
		var unsafeWindow = view.window.wrappedJSObject;
		
		if (!unsafeWindow.navigator.apps) {
			unsafeWindow.navigator.apps = {
				services: {
					registerHandler: function(action, handler) {
						if (_getAppUID() != action) {
							throw new Error("Action id does not match.");
						}
						jsm.AppIntent.registerHandler(action, handler);
					}, 
					
					unregisterHandler: function(action, handler) {
						if (_getAppUID() != action) {
							throw new Error("Action id does not match.");
						}
						jsm.AppIntent.unregisterHandler(action, handler);
					}
				},
				
				updateAppInfo: function(appInfo) {
					if (!appInfo || !appInfo.appUID) {
						return;
					}
					
					// Only could be invoked from allowed sites.
					var strDomains = jsm.utils.getPref('appsites');
					var domains = strDomains.split(/\d*,\d*/);
					for (var i = 0; i < domains.length; i++) {
						if (jsm.utils.isChildDomain(view.document.location.hostname, domains[i])) {
							AppCenter.updateApp(appInfo);
							break;
						}
					}
				}
			};
		}
	}, false);
})();