(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);
  Cu["import"]("resource://livemargins/apps/gallery/grabpicservice.js", jsm);
  var logger = new jsm.utils.logger("lm4.gallery");

  var contentAPI = {
    // Content apis for pref service
    getCharPref: function(prefName) {
      return Cc['@mozilla.org/preferences-service;1']
            .getService(Components.interfaces.nsIPrefService)
            .getBranch('extensions.livemargins.search.')
            .getCharPref(prefName);
    },

    getBoolPref: function(prefName) {
      return Cc['@mozilla.org/preferences-service;1']
            .getService(Components.interfaces.nsIPrefService)
            .getBranch('extensions.livemargins.search.')
            .getBoolPref(prefName);
    },

    setBoolPref: function(prefName, prefValue) {
      Cc['@mozilla.org/preferences-service;1']
            .getService(Components.interfaces.nsIPrefService)
            .getBranch('extensions.livemargins.search.')
            .setBoolPref(prefName, prefValue)
    },

    setCharPref: function(prefName, prefValue) {
      Cc['@mozilla.org/preferences-service;1']
            .getService(Components.interfaces.nsIPrefService)
            .getBranch('extensions.livemargins.search.')
            .setCharPref(prefName, prefValue)
    },

    // Content apis for GrabPicturesService
    GrabPicturesService: jsm.utils.wrapAsContentAPI(jsm.GrabPicturesService),

    getImageDataURL: function(image) {
      var fixedWidth = Math.min(image.width, image.height);
      var canvas = document.createElementNS("http://www.w3.org/1999/xhtml",
                                            "html:canvas");
      var context = canvas.getContext("2d");
      canvas.height = canvas.width = 75;
      context.drawImage(image, 0, 0, fixedWidth, fixedWidth, 0, 0, 75, 75);
      return canvas.toDataURL('image/png', '');
    },

    openFolderPicker: function(win, title) {
       var filePicker = Cc["@mozilla.org/filepicker;1"]
                          .createInstance(Ci.nsIFilePicker);
       filePicker.init(win, title, Ci.nsIFilePicker.modeGetFolder);

       if (filePicker.show() === Ci.nsIFilePicker.returnOK) {
        return filePicker.file;
      }

      return null;
    },

    log: function(msg) {
      logger.trace(msg);
    },
  };

  function init() {
    var appWin = document.getElementById("player_browser").contentWindow;

    let href = appWin.document.location.href;
    if (href.indexOf("resource://livemargins/apps/gallery/grabpic.htm") != 0) {
      return;
    }

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

    var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
            .getService(Ci.mozIJSSubScriptLoader);
    loader.loadSubScript("resource://livemargins/3rd/jquery.js", sandbox);
    loader.loadSubScript("resource://livemargins/3rd/jquery.scrollTo.js",
                         sandbox);
    loader.loadSubScript("resource://livemargins/3rd/template.js", sandbox);
    // charset can only be set in Gecko2.0
    // loader.loadSubScript("chrome://livemargins/content/apps/gallery/grabpic.js",
    //                      sandbox, "UTF-8");
    let jsUrl = "resource://livemargins/apps/gallery/grabpic.js";
    Cu.evalInSandbox(utils.getContentFromURL(jsUrl), sandbox);
    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, function() {
    init();
  }, null);

  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);
})();

