// this package overrides functionality in the Dojo components
dojo.provide("ues.core.overrides");

(function () {
  // fix dojo._usesBorderBox so that calling marginBox as a setter
  // on an element using border-box works (original function doesn't check
  // CSS box-sizing)
  var orig_usesBorderBox = dojo._usesBorderBox;
  dojo._usesBorderBox = function (aNode) {
    var style;
    if (dojo.isIE) style = dojo.style(aNode, "MsBoxSizing");
    else if (dojo.isFF) style = dojo.style(aNode, "MozBoxSizing");
    else if (dojo.isWebKit) style = dojo.style(aNode, "WebkitBoxSizing");
    if (!style) style = dojo.style(aNode, "boxSizing");
    if (!style) return orig_usesBorderBox.apply(this, arguments);
    return ((dojo.isIE && dojo.isIE < 8) ? false : style == "border-box");
  };


  // fix dojo._getBorderBox (dojo was returning padding box instead of border box) - fix required
  // for correct positioning of dijit.Dialog
  dojo._getBorderBox = function (aNode, aCS) {
    var mb = dojo.marginBox(aNode, aCS);
    var me = dojo._getMarginExtents(aNode, aCS);
    return { l: mb.l, t: mb.t, w: mb.w - me.w, h: mb.h - me.h };
  };


  // add support for dynamic loading of non-JS files
  /**
   * Adds the resource to the page.<br>
   * Note that if the resource is already present in the page and it
   * wasn't loaded by this method, the resource will be added again.
   *
   * @param aResource The resource to load (without file extension).
   * @param aType The type of the resource. Currently, only "css" can be used.
   */
  dojo.requireResource = function (aResource, aType) {
    if (!dojo.requireResource._cache) dojo.requireResource._cache = {};

    switch (aType) {
      case "css":
        var url = dojo.moduleUrl(aResource).toString();
        url = url.substr(0, url.length - 1); // remove trailing "/"
        url += "." + aType;
        if (dojo.requireResource._cache[url]) return; // already present in the page
        var link = dojo.create("link", {
          type: "text/css",
          rel: "stylesheet",
          href: url
        });
        dojo.query("head")[0].appendChild(link);
        dojo.requireResource._cache[url] = true;
        break;
      default:
        throw "Unable to load resource '" + aResource + "' of type '" + aType + "' - the type isn't recognized.";
    }
  };


  // upgrade widget's connect & disconnect methods to be able to
  // disconnect handlers easily (by supplying the same parameters that
  // were used for connecting)
  dojo.require("dijit._Widget");

  var origConnect = dijit._Widget.prototype.connect;
  var origDisconnect = dijit._Widget.prototype.disconnect;
  dojo.extend(dijit._Widget, {
    __connects: [],
    connect: function (/*Object|null*/ obj, /*String|Function*/ event, /*String|Function*/ method) {
      // store parameters to the map so that we're able to disconnect the function
      // by using the same set of parameters
      var args = Array.prototype.slice.call(arguments, 0);
      var h = origConnect.apply(this, arguments);
      args.push(h);
      this.__connects.push(args);
      return h;
    },

    /**
     * @example
     * this.connect(this.domNode, "onclick", this._onClick);
     * this.connect(this.domNode, "onclick", this._onClick2);
     * this.disconnect(this.domNode, "onclick", null); // disconnects all "onclick"
     */
    disconnect: function (/* _Widget.Handle */ handles) {
      // /*Object|null*/ obj, /*String|Function*/ event, /*String|Function*/ method
      if (arguments.length > 1) {
        // disconnect all connects that were made by using the same set of parameters
        var newC = [];
        for (var i=0, len = this.__connects.length; i<len; ++i) {
          var c = this.__connects[i];
          for (var j=0; j<arguments.length; ++j) {
            if (arguments[j] === null || arguments[j] === undefined) continue;
            if (arguments[j] !== c[j]) break;
          }
          if (j == arguments.length) origDisconnect.call(this, c[c.length-1]);
          else newC.push(c);
        }
        this.__connects = newC;
        return;
      }
      origDisconnect.apply(this, arguments);
    }
  });

  // fix viewport box for handhelds & IE6
  dijit.getViewport = function () {
    // summary:
    //    Returns the dimensions and scroll position of the viewable area of a browser window
    var scrollRoot = (dojo.isIE && dojo.isIE<=6 ? dojo.doc.documentElement : dojo.body()); // FIXME Restyle layout to have scrollbars on HTML element & remove this whole override

    // get scroll position
    var scroll = dojo._docScroll(); // scrollRoot.scrollTop/Left should work
    var size;
    if (UES.isHandheld && "innerHeight" in window) size = { w: window.innerWidth, h: window.innerHeight };
    else size = { w: scrollRoot.clientWidth, h: scrollRoot.clientHeight };
    var res = { w: size.w, h: size.h, l: scroll.x, t: scroll.y };
    return res;
  };

  dijit._frames = new function(){
  	// summary:
  	//		cache of iframes
  	var queue = [];

  	this.pop = function(){
  		var iframe;
  		if(queue.length){
  			iframe = queue.pop();
  			iframe.style.display="";
  		}else{
  			if(dojo.isIE && dojo.isIE < 9){
  				var burl = dojo.config["dojoBlankHtmlUrl"] || (dojo.moduleUrl("dojo", "resources/blank.html")+"") || "javascript:\"\"";
  				var html="<iframe src='" + burl + "'"
  					+ " style='position: absolute; left: 0px; top: 0px;"
  					+ "z-index: -1; filter:Alpha(Opacity=\"0\");'>";
  				iframe = dojo.doc.createElement(html);
  			}else{
  			 	iframe = dojo.create("iframe");
  				iframe.src = 'javascript:""';
  				iframe.className = "dijitBackgroundIframe";
  				dojo.style(iframe, "opacity", 0.1);
  			}
  			iframe.tabIndex = -1; // Magic to prevent iframe from getting focus on tab keypress - as style didnt work.
  		}
  		return iframe;
  	};

  	this.push = function(iframe){
  		iframe.style.display="none";
  		queue.push(iframe);
  	}
  }();
  
})();
