/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @fileoverview General purpose utilities that gadgets can use.
 */


/**
 * @class Provides general-purpose utility functions for onload.
 */
gadgets.util = gadgets.util || {};

(function() {

  var onLoadHandlers = [];

  /**
   * Registers an onload handler.
   * @param {function()} callback The handler to run.
   */
  gadgets.util.registerOnLoadHandler = function(callback) {
    onLoadHandlers.push(callback);
  };

  /**
   * Runs all functions registered via registerOnLoadHandler.
   * @private Only to be used by the container, not gadgets.
   */
  gadgets.util.runOnLoadHandlers = function() {
    gadgets.util.registerOnLoadHandler = function(cb) {
      cb();
    };

    if (onLoadHandlers) {
      for (var i = 0, j = onLoadHandlers.length; i < j; ++i) {
        try {
          onLoadHandlers[i]();
        } catch (ex) {
          gadgets.warn("Could not fire onloadhandler "+ ex.message);
        }
      }
      onLoadHandlers = undefined;  // No need to hold these references anymore.
    }
  };

  (function() {
    // If a script is statically inserted into the dom, use events
    // to call runOnLoadHandlers.
    // Try to attach to DOMContentLoaded if using a modern browser.
    gadgets.util.attachBrowserEvent(document,
            "DOMContentLoaded",
            gadgets.util.runOnLoadHandlers,
            false);
    // Always attach to window.onload as a fallback. We can safely ignore
    // any repeated calls to runOnLoadHandlers.
    var oldWindowOnload = window.onload;
    window.onload = function() {
      oldWindowOnload && oldWindowOnload();
      gadgets.util.runOnLoadHandlers();
    };
    // If a script is dynamically inserted into the page, the DOMContentLoaded
    // event will be fired before runOnLoadHandlers can be attached
    // to the event. In this case, find the script that loads the core libary
    // and attach runOnLoadHandlers to the script's onload event.
    var libParam = "";
    if (window && window.location && window.location.href) {
      libParam = gadgets.util.getUrlParameters(window.location.href).libs;
    }

    var regex = /(?:js\/)([^&|\.]+)/g;
    var match = regex.exec(libParam);

    if (match) {
      var url = decodeURIComponent(match[1]);
      var scripts = document.getElementsByTagName("script") || [];
      for (var i = 0; i < scripts.length; i++) {
        var script = scripts[i];
        var src = script.src;
        if (src && url && src.indexOf(url) !== -1) {
          // save a reference to the function that is already hooked up
          // to the event
          var oldonload = script.onload;
          script.onload = function() {
            oldonload && oldonload();
            gadgets.util.runOnLoadHandlers();
          };
        }
      }
    }
  })();
})();

