dojo.provide("parus.embeddedMode");
dojo.require("dojo.dom-style");

dojo.require("parus.parus8");

if (!parus) parus = {};

if (!parus.embeddedMode) dojo.mixin(parus, {
  embeddedMode: {}
});

dojo.mixin(parus.embeddedMode, {

  tabId: "",

  _onClose: null,

  _onShow: null,

  version: null,

  startup: function(sessionContent) {
    parus.parus8._embeddedMode = true;

    var params = new URLSearchParams(window.location.search);
    this.tabId = params.get("tab_id");
    console.log("Balance: tab id is obtained:", this.tabId);

    window.addEventListener("message", this._windowEventListener);
    console.log("Balance: embeddedMode for tab detected: addEventListener registered");

    if (!this.tabId) {
      this.tabId = Date.now() + Math.floor(Math.random() * 100);
      this.postMessage("register", this.tabId, {
        url: document.URL
      });

    }

    setTimeout(dojo.hitch(this, function() {
      this.postMessage("ready", this.tabId, {});
    }), 100);

  },

  _windowEventListener: function(e) {
    console.log("Balance: event message fired", e, e.data);

    if (e.data.hasOwnProperty("action")) {

      if (e.data.action == "onTabCloseConfirm") {
        console.log("Balance: onTabCloseConfirm requested:", e.data.id);

        if (parus.embeddedMode.onTabCloseConfirm()) {
          parus.embeddedMode.closeTab();
        }
      }

      else if (e.data.action == "onShowTab") {
        console.log("Balance: onShowTab recieved:", e.data.id);
        parus.embeddedMode.onShowTab();
      }

      else if (e.data.action == "onGlobalChanged") {
        console.log("Balance: onGlobalChanged recieved", e.data);
        parus.embeddedMode.handleGlobalChanged(e.data.params["identifier"], e.data.params["value"]);
      }

      else if (e.data.action == "onGetVersion") {
        console.log("Balance: onGetVersion recieved", e.data);
        parus.embeddedMode.handleGetVersion(e.data.params["version"]);
      }


    }
  },

  postMessage: function(action, id, params) {
    window.top.postMessage({
      action: action,
      id: id || "",
      params: params || {}
    }, "*");

    console.log("Balance: message posted", action, id, params);
  },

  onTabCloseConfirm: function() {
    if (this._onClose && typeof this._onClose === "function") {
      this._onClose(this.tabId);
      return false;
    }

    return true;
  },

  onShowTab: function() {
    if (this._onShow && typeof this._onShow === "function") {
      this._onShow(this.tabId);
    }

    var done = [];

    dojo.query("*[widgetId]", document.body).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget && widget.dialogObject && dojo.isFunction(widget.dialogObject._startupResize)) {
        if (dojo.indexOf(done, widget.dialogObject.id) < 0) widget.dialogObject._activateResize();
        done.push(widget.dialogObject.id);
      }
      else {
        if (widget && widget.isInstanceOf && dojo.isFunction(widget.isInstanceOf) && (widget.isInstanceOf(dijit.Dialog) || widget.isInstanceOf(dijit.DialogUnderlay))) return;

        if (widget && widget.layout && dojo.isFunction(widget.layout)) widget.layout();
        if (widget && widget.resize && dojo.isFunction(widget.resize)) widget.resize();
      }
    });

    return true;
  },

  //public class methods
  openTab: function(id, title, url, confirmClose) {

    var pathname = location.pathname.split("/");
    pathname.pop();

    if (url.startsWith("..")) {
      url = url.substring(2);
      pathname.pop();
    }

    url = location.origin + (pathname.length ? pathname.join("/") : "") + url;

    confirmClose = (confirmClose == null) ? true : (confirmClose === true);

    this.postMessage("openTab", id, {
      title: title,
      url: url,
      confirmClose: confirmClose
    });
  },

  //public tab instance methods
  registerOnCloseCallback: function(onClose) {
    this._onClose = onClose;
  },

  registerOnShowCallback: function(onShow) {
    this._onShow = onShow;
  },

  changeTabTitle: function(title) {
    this.postMessage("changeTabTitle", this.tabId, {
      title: title
    });
  },

  changeTabState: function(modified) {
    this.postMessage("changeTabState", this.tabId, {
      modified: modified
    });
  },

  closeTab: function() {
    this.postMessage("closeTab", this.tabId);
  },

  handleGlobalChanged: function(identifier, value) {
    console.log("handleGlobalChanged", identifier, value);
    eval(identifier + "=(" + ((value && dojo.isObject(value) && Object.keys(value).length) ? dojo.toJson(value) : "null") + ")");
  },

  globalChanged: function(identifier, value) {
    this.postMessage("globalChanged", this.tabId, {
      identifier: identifier,
      value: value
    });
  },

  handleGetVersion: function(version) {
    console.log("version:", version);
    this.version = dojo.clone(version);
  }

});

if (dojo.isFF > 50) require(["dojo/dom-style", "dojo/_base/window", "dojo/dom"], function(domStyle, win, dom) {
  var old = domStyle.get;
  var def = {
    getComputedStyle: function(node) {
      var dv = node.ownerDocument.defaultView,
          w = dv.opener ? dv : win.global.window;
      return node.nodeType == 1 /* ELEMENT_NODE*/
      ? w.getComputedStyle(node, null) : {};
    },
    get: function( /*DOMNode|String*/ node, /*String?*/ name) {
      if ((arguments.length == 2) && (name == "opacity")) return this.getComputedStyle(dom.byId(node)).opacity;
      return old.apply(this, arguments);
    }
  };
  dojo.mixin(domStyle, def);
  dojo.getComputedStyle = domStyle.getComputedStyle;
});

if (!parus.aboutBoxWindow) dojo.mixin(parus, {
  aboutBoxWindow: {}
});

dojo.mixin(parus.aboutBoxWindow, {
  startup: function() {
    (function() {
      if (!parus.embeddedMode.version) setTimeout(arguments.callee, 100);
      else {
        loadingDiv.style.display = "none";
        parus.parus8.aboutBox(function() {
          parus.embeddedMode.closeTab();
        });
      }
    })()
  }
});